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 |
|---|---|---|---|---|---|
32,566 | def runscgi(func):
from flup.server.scgi import WSGIServer
my_server = makeserver(WSGIServer)
if (len(sys.argv) > 2):
args = sys.argv[:]
args.remove('scgi')
hostport = args[1]
hostport = hostport.split(':', 1)
if (len(hostport) == 2):
hostport = (hostport[0], int(hostport[1]))
else:
hostport = ('localhost', int(hostport[0]))
else:
hostport = ('localhost', 4000)
return my_server(func, bindAddress=hostport).run()
| [
"def",
"runscgi",
"(",
"func",
")",
":",
"from",
"flup",
".",
"server",
".",
"scgi",
"import",
"WSGIServer",
"my_server",
"=",
"makeserver",
"(",
"WSGIServer",
")",
"if",
"(",
"len",
"(",
"sys",
".",
"argv",
")",
">",
"2",
")",
":",
"args",
"=",
"s... | runs a wsgi-function with an scgi server . | train | false |
32,567 | def test_cnot_gate():
circuit = CNotGate(1, 0)
assert (represent(circuit, nqubits=2) == Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]))
circuit = (circuit * Qubit('111'))
assert (matrix_to_qubit(represent(circuit, nqubits=3)) == qapply(circuit))
circuit = CNotGate(1, 0)
assert (Dagger(circuit) == circuit)
assert (Dagger(Dagger(circuit)) == circuit)
assert ((circuit * circuit) == 1)
| [
"def",
"test_cnot_gate",
"(",
")",
":",
"circuit",
"=",
"CNotGate",
"(",
"1",
",",
"0",
")",
"assert",
"(",
"represent",
"(",
"circuit",
",",
"nqubits",
"=",
"2",
")",
"==",
"Matrix",
"(",
"[",
"[",
"1",
",",
"0",
",",
"0",
",",
"0",
"]",
",",
... | test the cnot gate . | train | false |
32,569 | def dump_csv(query, file_or_name, include_header=True, close_file=True, append=True, csv_writer=None):
if isinstance(file_or_name, basestring):
fh = open(file_or_name, ((append and 'a') or 'w'))
else:
fh = file_or_name
if append:
fh.seek(0, 2)
writer = (csv_writer or csv.writer(fh, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL))
if include_header:
header = []
for (idx, node) in enumerate(query._select):
if node._alias:
header.append(node._alias)
elif isinstance(node, (Field, Func)):
header.append(node.name)
else:
header.append(('col_%s' % idx))
writer.writerow(header)
for row in query.tuples().iterator():
writer.writerow(row)
if close_file:
fh.close()
return fh
| [
"def",
"dump_csv",
"(",
"query",
",",
"file_or_name",
",",
"include_header",
"=",
"True",
",",
"close_file",
"=",
"True",
",",
"append",
"=",
"True",
",",
"csv_writer",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"file_or_name",
",",
"basestring",
")",... | create a csv dump of a query . | train | false |
32,570 | def wns_send_message(uri, message=None, xml_data=None, raw_data=None, **kwargs):
if message:
wns_type = 'wns/toast'
if isinstance(message, str):
message = {'text': [message]}
prepared_data = _wns_prepare_toast(data=message, **kwargs)
elif xml_data:
xml = dict_to_xml_schema(xml_data)
wns_type = ('wns/%s' % xml.tag)
prepared_data = ET.tostring(xml)
elif raw_data:
wns_type = 'wns/raw'
prepared_data = raw_data
else:
raise TypeError('At least one of the following parameters must be set:`message`, `xml_data`, `raw_data`')
_wns_send(uri=uri, data=prepared_data, wns_type=wns_type)
| [
"def",
"wns_send_message",
"(",
"uri",
",",
"message",
"=",
"None",
",",
"xml_data",
"=",
"None",
",",
"raw_data",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"if",
"message",
":",
"wns_type",
"=",
"'wns/toast'",
"if",
"isinstance",
"(",
"message",
",",
... | sends a notification request to wns . | train | false |
32,572 | def buildSharedCrossedNetwork():
N = FeedForwardNetwork('shared-crossed')
h = 1
a = LinearLayer(2, name='a')
b = LinearLayer(h, name='b')
c = LinearLayer(h, name='c')
d = LinearLayer(2, name='d')
N.addInputModule(a)
N.addModule(b)
N.addModule(c)
N.addOutputModule(d)
m1 = MotherConnection(h)
m1.params[:] = scipy.array((1,))
m2 = MotherConnection(h)
m2.params[:] = scipy.array((2,))
N.addConnection(SharedFullConnection(m1, a, b, inSliceTo=1))
N.addConnection(SharedFullConnection(m1, a, c, inSliceFrom=1))
N.addConnection(SharedFullConnection(m2, b, d, outSliceFrom=1))
N.addConnection(SharedFullConnection(m2, c, d, outSliceTo=1))
N.sortModules()
return N
| [
"def",
"buildSharedCrossedNetwork",
"(",
")",
":",
"N",
"=",
"FeedForwardNetwork",
"(",
"'shared-crossed'",
")",
"h",
"=",
"1",
"a",
"=",
"LinearLayer",
"(",
"2",
",",
"name",
"=",
"'a'",
")",
"b",
"=",
"LinearLayer",
"(",
"h",
",",
"name",
"=",
"'b'",... | build a network with shared connections . | train | false |
32,573 | @with_setup(prepare_stdout, registry.clear)
def test_jsonreport_output_with_different_filename():
with check_jsonreport(u'error_traceback', u'custom_filename.json'):
runner = Runner(feature_name(u'error_traceback'), enable_jsonreport=True, jsonreport_filename=u'custom_filename.json')
runner.run()
| [
"@",
"with_setup",
"(",
"prepare_stdout",
",",
"registry",
".",
"clear",
")",
"def",
"test_jsonreport_output_with_different_filename",
"(",
")",
":",
"with",
"check_jsonreport",
"(",
"u'error_traceback'",
",",
"u'custom_filename.json'",
")",
":",
"runner",
"=",
"Runne... | test jsonreport output with different filename . | train | false |
32,574 | @register.inclusion_tag('zinnia/tags/dummy.html', takes_context=True)
def zinnia_breadcrumbs(context, root_name='', template='zinnia/tags/breadcrumbs.html'):
path = context['request'].path
context_object = get_context_first_object(context, ['object', 'category', 'tag', 'author'])
context_page = context.get('page_obj')
breadcrumbs = retrieve_breadcrumbs(path, context_object, context_page, root_name)
return {'template': template, 'breadcrumbs': breadcrumbs}
| [
"@",
"register",
".",
"inclusion_tag",
"(",
"'zinnia/tags/dummy.html'",
",",
"takes_context",
"=",
"True",
")",
"def",
"zinnia_breadcrumbs",
"(",
"context",
",",
"root_name",
"=",
"''",
",",
"template",
"=",
"'zinnia/tags/breadcrumbs.html'",
")",
":",
"path",
"=",... | return a breadcrumb for the application . | train | false |
32,575 | def get_factory_modules():
mods = [x.get('module', None) for x in Factory.classes.values()]
return [m for m in mods if m]
| [
"def",
"get_factory_modules",
"(",
")",
":",
"mods",
"=",
"[",
"x",
".",
"get",
"(",
"'module'",
",",
"None",
")",
"for",
"x",
"in",
"Factory",
".",
"classes",
".",
"values",
"(",
")",
"]",
"return",
"[",
"m",
"for",
"m",
"in",
"mods",
"if",
"m",... | returns a list of all the modules registered in the kivy factory . | train | false |
32,576 | @task(time_limit=time_limits['hard'], soft_time_limit=time_limits['soft'])
def resize_video(src, pk, user_pk=None, **kw):
instance = Preview.objects.get(pk=pk)
user = (UserProfile.objects.get(pk=user_pk) if user_pk else None)
try:
copy_stored_file(src, src, src_storage=private_storage, dst_storage=local_storage)
result = _resize_video(src, instance, **kw)
except Exception as err:
log.error(('Error on processing video: %s' % err))
_resize_error(src, instance, user)
raise
if (not result):
log.error('Error on processing video, _resize_video not True.')
_resize_error(src, instance, user)
log.info('Video resize complete.')
instance.addon.update(modified=datetime.datetime.now())
| [
"@",
"task",
"(",
"time_limit",
"=",
"time_limits",
"[",
"'hard'",
"]",
",",
"soft_time_limit",
"=",
"time_limits",
"[",
"'soft'",
"]",
")",
"def",
"resize_video",
"(",
"src",
",",
"pk",
",",
"user_pk",
"=",
"None",
",",
"**",
"kw",
")",
":",
"instance... | try and resize a video and cope if it fails . | train | false |
32,577 | def _get_fields(url):
handle = _open(url)
fields = handle.read().strip().split()
handle.close()
return fields
| [
"def",
"_get_fields",
"(",
"url",
")",
":",
"handle",
"=",
"_open",
"(",
"url",
")",
"fields",
"=",
"handle",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"handle",
".",
"close",
"(",
")",
"return",
"fields"
] | queries a togows url for a plain text list of values . | train | false |
32,578 | def build_es_conn_config(conf):
parsed_conf = {}
parsed_conf['use_ssl'] = False
parsed_conf['verify_certs'] = True
parsed_conf['http_auth'] = None
parsed_conf['es_username'] = None
parsed_conf['es_password'] = None
parsed_conf['aws_region'] = None
parsed_conf['boto_profile'] = None
parsed_conf['es_host'] = conf['es_host']
parsed_conf['es_port'] = conf['es_port']
parsed_conf['es_url_prefix'] = ''
parsed_conf['es_conn_timeout'] = conf.get('es_conn_timeout', 20)
parsed_conf['send_get_body_as'] = conf.get('es_send_get_body_as', 'GET')
if ('es_username' in conf):
parsed_conf['es_username'] = conf['es_username']
parsed_conf['es_password'] = conf['es_password']
if ('aws_region' in conf):
parsed_conf['aws_region'] = conf['aws_region']
if ('boto_profile' in conf):
parsed_conf['boto_profile'] = conf['boto_profile']
if ('use_ssl' in conf):
parsed_conf['use_ssl'] = conf['use_ssl']
if ('verify_certs' in conf):
parsed_conf['verify_certs'] = conf['verify_certs']
if ('es_url_prefix' in conf):
parsed_conf['es_url_prefix'] = conf['es_url_prefix']
return parsed_conf
| [
"def",
"build_es_conn_config",
"(",
"conf",
")",
":",
"parsed_conf",
"=",
"{",
"}",
"parsed_conf",
"[",
"'use_ssl'",
"]",
"=",
"False",
"parsed_conf",
"[",
"'verify_certs'",
"]",
"=",
"True",
"parsed_conf",
"[",
"'http_auth'",
"]",
"=",
"None",
"parsed_conf",
... | given a conf dictionary w/ raw config properties use_ssl . | train | false |
32,580 | def acpi_tables(attrs=None, where=None):
return _osquery_cmd(table='acpi_tables', attrs=attrs, where=where)
| [
"def",
"acpi_tables",
"(",
"attrs",
"=",
"None",
",",
"where",
"=",
"None",
")",
":",
"return",
"_osquery_cmd",
"(",
"table",
"=",
"'acpi_tables'",
",",
"attrs",
"=",
"attrs",
",",
"where",
"=",
"where",
")"
] | return acpi_tables information from osquery cli example: . | train | false |
32,583 | def num_ini_spaces(strng):
ini_spaces = ini_spaces_re.match(strng)
if ini_spaces:
return ini_spaces.end()
else:
return 0
| [
"def",
"num_ini_spaces",
"(",
"strng",
")",
":",
"ini_spaces",
"=",
"ini_spaces_re",
".",
"match",
"(",
"strng",
")",
"if",
"ini_spaces",
":",
"return",
"ini_spaces",
".",
"end",
"(",
")",
"else",
":",
"return",
"0"
] | return the number of initial spaces in a string . | train | false |
32,585 | def _slow_pivot(index, columns, values):
tree = {}
for (i, (idx, col)) in enumerate(zip(index, columns)):
if (col not in tree):
tree[col] = {}
branch = tree[col]
branch[idx] = values[i]
return DataFrame(tree)
| [
"def",
"_slow_pivot",
"(",
"index",
",",
"columns",
",",
"values",
")",
":",
"tree",
"=",
"{",
"}",
"for",
"(",
"i",
",",
"(",
"idx",
",",
"col",
")",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"index",
",",
"columns",
")",
")",
":",
"if",
"(",
... | produce pivot table based on 3 columns of this dataframe . | train | false |
32,586 | def net2wider_experiment():
train_data = (train_x, train_y)
validation_data = (validation_x, validation_y)
print('\nExperiment of Net2WiderNet ...')
print('\nbuilding teacher model ...')
(teacher_model, _) = make_teacher_model(train_data, validation_data, nb_epoch=3)
print('\nbuilding wider student model by random padding ...')
make_wider_student_model(teacher_model, train_data, validation_data, 'random-pad', nb_epoch=3)
print('\nbuilding wider student model by net2wider ...')
make_wider_student_model(teacher_model, train_data, validation_data, 'net2wider', nb_epoch=3)
| [
"def",
"net2wider_experiment",
"(",
")",
":",
"train_data",
"=",
"(",
"train_x",
",",
"train_y",
")",
"validation_data",
"=",
"(",
"validation_x",
",",
"validation_y",
")",
"print",
"(",
"'\\nExperiment of Net2WiderNet ...'",
")",
"print",
"(",
"'\\nbuilding teacher... | benchmark performances of (1) a teacher model . | train | false |
32,587 | def pushtoken(token, tokens):
(yield token)
for t in tokens:
(yield t)
| [
"def",
"pushtoken",
"(",
"token",
",",
"tokens",
")",
":",
"(",
"yield",
"token",
")",
"for",
"t",
"in",
"tokens",
":",
"(",
"yield",
"t",
")"
] | return new generator starting with token followed by all tokens in tokens . | train | false |
32,588 | def is_valid_ext_comm_attr(attr):
if (not isinstance(attr, str)):
return False
tokens = attr.rsplit(':', 1)
if (len(tokens) != 2):
return False
try:
if ('.' in tokens[0]):
if (not is_valid_ipv4(tokens[0])):
return False
else:
int(tokens[0])
int(tokens[1])
except (ValueError, socket.error):
return False
return True
| [
"def",
"is_valid_ext_comm_attr",
"(",
"attr",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"attr",
",",
"str",
")",
")",
":",
"return",
"False",
"tokens",
"=",
"attr",
".",
"rsplit",
"(",
"':'",
",",
"1",
")",
"if",
"(",
"len",
"(",
"tokens",
")"... | validates *attr* as string representation of rt or soo . | train | true |
32,589 | def grade(adjective, suffix=COMPARATIVE):
b = predicative(adjective)
if ((suffix == SUPERLATIVE) and b.endswith(('s', u'\xdf'))):
suffix = suffix[1:]
return ((adjective[:len(b)] + suffix) + adjective[len(b):])
| [
"def",
"grade",
"(",
"adjective",
",",
"suffix",
"=",
"COMPARATIVE",
")",
":",
"b",
"=",
"predicative",
"(",
"adjective",
")",
"if",
"(",
"(",
"suffix",
"==",
"SUPERLATIVE",
")",
"and",
"b",
".",
"endswith",
"(",
"(",
"'s'",
",",
"u'\\xdf'",
")",
")"... | creates draganddrop instance from user_input and correct_answer and calls draganddrop . | train | true |
32,590 | @contextlib.contextmanager
def create_tempfile(content=None):
(fd, tmp) = tempfile.mkstemp()
if content:
if (sys.version_info >= (3, 0)):
os.write(fd, bytes(content, 'ascii'))
else:
os.write(fd, content)
try:
(yield tmp)
finally:
os.close(fd)
os.remove(tmp)
| [
"@",
"contextlib",
".",
"contextmanager",
"def",
"create_tempfile",
"(",
"content",
"=",
"None",
")",
":",
"(",
"fd",
",",
"tmp",
")",
"=",
"tempfile",
".",
"mkstemp",
"(",
")",
"if",
"content",
":",
"if",
"(",
"sys",
".",
"version_info",
">=",
"(",
... | create a new temporary file . | train | false |
32,591 | def init(mpstate):
return SerialModule(mpstate)
| [
"def",
"init",
"(",
"mpstate",
")",
":",
"return",
"SerialModule",
"(",
"mpstate",
")"
] | initialize module globals . | train | false |
32,594 | def with_header(header=None):
def wrap(func):
@functools.wraps(func)
def wrapped(cls, remaining_attrs):
result = list(func(cls, remaining_attrs))
if result:
(yield u'')
(yield u'.. raw:: html')
(yield u'')
(yield u' <hr>')
(yield u'')
if header:
(yield (header + u':'))
(yield u'')
for row in result:
(yield row)
return wrapped
return wrap
| [
"def",
"with_header",
"(",
"header",
"=",
"None",
")",
":",
"def",
"wrap",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"cls",
",",
"remaining_attrs",
")",
":",
"result",
"=",
"list",
"(",
"func",
... | decorator that adds a section header if theres a any output the decorated function should yield output lines; if there are any the header gets added . | train | false |
32,595 | @blueprint.route('/sources/<source>/meters/<meter>')
def list_samples_by_source(source, meter):
return _list_samples(source=source, meter=meter, project=acl.get_limited_to_project(flask.request.headers))
| [
"@",
"blueprint",
".",
"route",
"(",
"'/sources/<source>/meters/<meter>'",
")",
"def",
"list_samples_by_source",
"(",
"source",
",",
"meter",
")",
":",
"return",
"_list_samples",
"(",
"source",
"=",
"source",
",",
"meter",
"=",
"meter",
",",
"project",
"=",
"a... | return a list of raw samples for the source . | train | false |
32,596 | def demo_multifeature_template():
postag(templates=[Template(Word([0]), Pos([(-2), (-1)]))])
| [
"def",
"demo_multifeature_template",
"(",
")",
":",
"postag",
"(",
"templates",
"=",
"[",
"Template",
"(",
"Word",
"(",
"[",
"0",
"]",
")",
",",
"Pos",
"(",
"[",
"(",
"-",
"2",
")",
",",
"(",
"-",
"1",
")",
"]",
")",
")",
"]",
")"
] | templates can have more than a single feature . | train | false |
32,597 | def test_fitness(genome):
return 1
| [
"def",
"test_fitness",
"(",
"genome",
")",
":",
"return",
"1"
] | simple class for calculating fitnesses . | train | false |
32,598 | def expected(decorator, func):
return (decorator(func) if (not hasattr(func, '_api')) else func)
| [
"def",
"expected",
"(",
"decorator",
",",
"func",
")",
":",
"return",
"(",
"decorator",
"(",
"func",
")",
"if",
"(",
"not",
"hasattr",
"(",
"func",
",",
"'_api'",
")",
")",
"else",
"func",
")"
] | decorate func with decorator if func is not wrapped yet . | train | false |
32,599 | def format_stack(f=None, limit=None):
if (f is None):
try:
raise ZeroDivisionError
except ZeroDivisionError:
f = sys.exc_info()[2].tb_frame.f_back
return format_list(extract_stack(f, limit))
| [
"def",
"format_stack",
"(",
"f",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"if",
"(",
"f",
"is",
"None",
")",
":",
"try",
":",
"raise",
"ZeroDivisionError",
"except",
"ZeroDivisionError",
":",
"f",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
... | shorthand for format_list(extract_stack) . | train | true |
32,601 | def add_view_permissions(sender, **kwargs):
for content_type in ContentType.objects.all():
codename = ('view_%s' % content_type.model)
if (not Permission.objects.filter(content_type=content_type, codename=codename)):
Permission.objects.create(content_type=content_type, codename=codename, name=('Can view %s' % content_type.name))
| [
"def",
"add_view_permissions",
"(",
"sender",
",",
"**",
"kwargs",
")",
":",
"for",
"content_type",
"in",
"ContentType",
".",
"objects",
".",
"all",
"(",
")",
":",
"codename",
"=",
"(",
"'view_%s'",
"%",
"content_type",
".",
"model",
")",
"if",
"(",
"not... | this syncdb hooks takes care of adding a view permission too all our content types . | train | false |
32,602 | def get_oldest(class_name):
for (cls, wdict) in six.iteritems(live_refs):
if (cls.__name__ == class_name):
if (not wdict):
break
return min(six.iteritems(wdict), key=itemgetter(1))[0]
| [
"def",
"get_oldest",
"(",
"class_name",
")",
":",
"for",
"(",
"cls",
",",
"wdict",
")",
"in",
"six",
".",
"iteritems",
"(",
"live_refs",
")",
":",
"if",
"(",
"cls",
".",
"__name__",
"==",
"class_name",
")",
":",
"if",
"(",
"not",
"wdict",
")",
":",... | get the oldest object for a specific class name . | train | false |
32,603 | def split_sff(sff_file_handles, map_file_handle, outdir='/tmp/'):
try:
(flowgrams, header) = cat_sff_files(sff_file_handles)
except ValueError:
raise FileFormatError(('Wrong flogram file format. Make sure you pass the sff.txt format ' + 'produced by sffinfo. The binary .sff will not work here.'))
(inverse_map, map_count) = build_inverse_barcode_map(parse_fasta(map_file_handle))
filenames = []
for barcode_id in map_count.keys():
fh = open((outdir + barcode_id), 'w')
write_sff_header(header, fh, map_count[barcode_id])
fh.close()
filenames.append((outdir + barcode_id))
for f in flowgrams:
if (f.Name in inverse_map):
barcode_id = inverse_map[f.Name]
fh = open((outdir + barcode_id), 'a')
fh.write((f.createFlowHeader() + '\n'))
return filenames
| [
"def",
"split_sff",
"(",
"sff_file_handles",
",",
"map_file_handle",
",",
"outdir",
"=",
"'/tmp/'",
")",
":",
"try",
":",
"(",
"flowgrams",
",",
"header",
")",
"=",
"cat_sff_files",
"(",
"sff_file_handles",
")",
"except",
"ValueError",
":",
"raise",
"FileForma... | splits a sff . | train | false |
32,604 | def tab_in_leading(s):
n = (len(s) - len(s.lstrip()))
if (not (s[n:(n + 3)] in ['...', '>>>'])):
check = s[:n]
else:
smore = s[(n + 3):]
check = (s[:n] + smore[:(len(smore) - len(smore.lstrip()))])
return (not (check.expandtabs() == check))
| [
"def",
"tab_in_leading",
"(",
"s",
")",
":",
"n",
"=",
"(",
"len",
"(",
"s",
")",
"-",
"len",
"(",
"s",
".",
"lstrip",
"(",
")",
")",
")",
"if",
"(",
"not",
"(",
"s",
"[",
"n",
":",
"(",
"n",
"+",
"3",
")",
"]",
"in",
"[",
"'...'",
",",... | returns true if there are tabs in the leading whitespace of a line . | train | false |
32,605 | def getBool(s):
return (str(s).lower() in ('y', 'yes', '1', 'true'))
| [
"def",
"getBool",
"(",
"s",
")",
":",
"return",
"(",
"str",
"(",
"s",
")",
".",
"lower",
"(",
")",
"in",
"(",
"'y'",
",",
"'yes'",
",",
"'1'",
",",
"'true'",
")",
")"
] | is it a boolean? . | train | false |
32,607 | def escape_dn_chars(dn):
return dn
| [
"def",
"escape_dn_chars",
"(",
"dn",
")",
":",
"return",
"dn"
] | escape all dn special characters found in s with a back-slash . | train | false |
32,608 | def get_full_dir_name(path):
if (sys.platform == 'win32'):
return path
import System
if is_netstandard:
import clr
clr.AddReference('System.IO.FileSystem')
return System.IO.DirectoryInfo(path).FullName
| [
"def",
"get_full_dir_name",
"(",
"path",
")",
":",
"if",
"(",
"sys",
".",
"platform",
"==",
"'win32'",
")",
":",
"return",
"path",
"import",
"System",
"if",
"is_netstandard",
":",
"import",
"clr",
"clr",
".",
"AddReference",
"(",
"'System.IO.FileSystem'",
")... | removes ~# from short file names . | train | false |
32,610 | def haveInternetAccess(forceCheck=False):
global haveInternet
if (forceCheck or (haveInternet is None)):
sites = ['http://www.google.com/', 'http://www.opendns.com/']
for wait in [0.3, 0.7]:
for site in sites:
try:
urllib.request.urlopen(site, timeout=wait)
haveInternet = True
return True
except Exception:
pass
else:
haveInternet = False
return haveInternet
| [
"def",
"haveInternetAccess",
"(",
"forceCheck",
"=",
"False",
")",
":",
"global",
"haveInternet",
"if",
"(",
"forceCheck",
"or",
"(",
"haveInternet",
"is",
"None",
")",
")",
":",
"sites",
"=",
"[",
"'http://www.google.com/'",
",",
"'http://www.opendns.com/'",
"]... | detect active internet connection or fail quickly . | train | false |
32,612 | def register_writer(data_format, data_class, function, force=False):
if ((not ((data_format, data_class) in _writers)) or force):
_writers[(data_format, data_class)] = function
else:
raise IORegistryError(u"Writer for format '{0}' and class '{1}' is already defined".format(data_format, data_class.__name__))
if (data_class not in _delayed_docs_classes):
_update__doc__(data_class, u'write')
| [
"def",
"register_writer",
"(",
"data_format",
",",
"data_class",
",",
"function",
",",
"force",
"=",
"False",
")",
":",
"if",
"(",
"(",
"not",
"(",
"(",
"data_format",
",",
"data_class",
")",
"in",
"_writers",
")",
")",
"or",
"force",
")",
":",
"_write... | register a table writer function . | train | false |
32,613 | def parse_string_set(source, info):
source.expect('<')
name = parse_name(source, True)
source.expect('>')
if ((name is None) or (name not in info.kwargs)):
raise error('undefined named list', source.string, source.pos)
return make_string_set(info, name)
| [
"def",
"parse_string_set",
"(",
"source",
",",
"info",
")",
":",
"source",
".",
"expect",
"(",
"'<'",
")",
"name",
"=",
"parse_name",
"(",
"source",
",",
"True",
")",
"source",
".",
"expect",
"(",
"'>'",
")",
"if",
"(",
"(",
"name",
"is",
"None",
"... | parses a string set reference . | train | false |
32,615 | def server_group_field_data(request):
server_groups = server_group_list(request)
if server_groups:
server_groups_list = [(sg.id, sg.name) for sg in server_groups]
server_groups_list.sort(key=(lambda obj: obj[1]))
return ([('', _('Select Server Group'))] + server_groups_list)
return [('', _('No server groups available'))]
| [
"def",
"server_group_field_data",
"(",
"request",
")",
":",
"server_groups",
"=",
"server_group_list",
"(",
"request",
")",
"if",
"server_groups",
":",
"server_groups_list",
"=",
"[",
"(",
"sg",
".",
"id",
",",
"sg",
".",
"name",
")",
"for",
"sg",
"in",
"s... | returns a list of tuples of all server groups . | train | true |
32,616 | def parse_coords(lines):
pcoa_results = OrdinationResults.read(lines)
return (pcoa_results.site_ids, pcoa_results.site, pcoa_results.eigvals, pcoa_results.proportion_explained)
| [
"def",
"parse_coords",
"(",
"lines",
")",
":",
"pcoa_results",
"=",
"OrdinationResults",
".",
"read",
"(",
"lines",
")",
"return",
"(",
"pcoa_results",
".",
"site_ids",
",",
"pcoa_results",
".",
"site",
",",
"pcoa_results",
".",
"eigvals",
",",
"pcoa_results",... | parse skbios ordination results file into coords . | train | false |
32,617 | @csrf_exempt
@require_sync_session
@api_handle_error_with_json
def device_upload(data, session):
try:
result = save_serialized_models(data.get('devices', '[]'), src_version=session.client_version)
except Exception as e:
logging.debug(('Exception uploading devices (in api_views): %s' % e))
result = {'error': e.message, 'saved_model_count': 0}
session.models_uploaded += result['saved_model_count']
session.errors += result.has_key('error')
return JsonResponse(result)
| [
"@",
"csrf_exempt",
"@",
"require_sync_session",
"@",
"api_handle_error_with_json",
"def",
"device_upload",
"(",
"data",
",",
"session",
")",
":",
"try",
":",
"result",
"=",
"save_serialized_models",
"(",
"data",
".",
"get",
"(",
"'devices'",
",",
"'[]'",
")",
... | this device is getting device-related objects from another device . | train | false |
32,618 | def bias_variable(shape):
initial = tf.random_normal(shape, mean=0.0, stddev=0.01)
return tf.Variable(initial)
| [
"def",
"bias_variable",
"(",
"shape",
")",
":",
"initial",
"=",
"tf",
".",
"random_normal",
"(",
"shape",
",",
"mean",
"=",
"0.0",
",",
"stddev",
"=",
"0.01",
")",
"return",
"tf",
".",
"Variable",
"(",
"initial",
")"
] | helper function to create a bias variable initialized with a constant value . | train | false |
32,619 | def tweets_for(query_type, args, per_user=None):
lookup = {u'query_type': query_type, u'value': args[0]}
try:
tweets = Tweet.objects.get_for(**lookup)
except TwitterQueryException:
return []
if (per_user is not None):
_tweets = defaultdict(list)
for tweet in tweets:
if (len(_tweets[tweet.user_name]) < per_user):
_tweets[tweet.user_name].append(tweet)
tweets = sum(_tweets.values(), [])
tweets.sort(key=(lambda t: t.created_at), reverse=True)
if ((len(args) > 1) and str(args[(-1)]).isdigit()):
tweets = tweets[:int(args[(-1)])]
return tweets
| [
"def",
"tweets_for",
"(",
"query_type",
",",
"args",
",",
"per_user",
"=",
"None",
")",
":",
"lookup",
"=",
"{",
"u'query_type'",
":",
"query_type",
",",
"u'value'",
":",
"args",
"[",
"0",
"]",
"}",
"try",
":",
"tweets",
"=",
"Tweet",
".",
"objects",
... | retrieve tweets for a user . | train | true |
32,620 | def default_get_id():
return None
| [
"def",
"default_get_id",
"(",
")",
":",
"return",
"None"
] | default get_id . | train | false |
32,622 | def _upstart_delete(name):
if HAS_UPSTART:
if os.path.exists('/etc/init/{0}.conf'.format(name)):
os.rename('/etc/init/{0}.conf'.format(name), '/etc/init/{0}.conf.removed'.format(name))
return True
| [
"def",
"_upstart_delete",
"(",
"name",
")",
":",
"if",
"HAS_UPSTART",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"'/etc/init/{0}.conf'",
".",
"format",
"(",
"name",
")",
")",
":",
"os",
".",
"rename",
"(",
"'/etc/init/{0}.conf'",
".",
"format",
"(... | delete an upstart service . | train | true |
32,623 | def table_has_constraint(table, name, db):
t = sa.Table(table, db.metadata, autoload=True, autoload_with=db.engine)
for c in t.constraints:
if (c.name == name):
return True
return False
| [
"def",
"table_has_constraint",
"(",
"table",
",",
"name",
",",
"db",
")",
":",
"t",
"=",
"sa",
".",
"Table",
"(",
"table",
",",
"db",
".",
"metadata",
",",
"autoload",
"=",
"True",
",",
"autoload_with",
"=",
"db",
".",
"engine",
")",
"for",
"c",
"i... | utility to find a constraint name in alembic migrations . | train | true |
32,624 | def create_button(text=u'', layout=None, tooltip=None, icon=None, enabled=True, default=False):
button = QtWidgets.QPushButton()
button.setCursor(Qt.PointingHandCursor)
if text:
button.setText(text)
if (icon is not None):
button.setIcon(icon)
button.setIconSize(QtCore.QSize(defs.small_icon, defs.small_icon))
if (tooltip is not None):
button.setToolTip(tooltip)
if (layout is not None):
layout.addWidget(button)
if (not enabled):
button.setEnabled(False)
if default:
button.setDefault(True)
return button
| [
"def",
"create_button",
"(",
"text",
"=",
"u''",
",",
"layout",
"=",
"None",
",",
"tooltip",
"=",
"None",
",",
"icon",
"=",
"None",
",",
"enabled",
"=",
"True",
",",
"default",
"=",
"False",
")",
":",
"button",
"=",
"QtWidgets",
".",
"QPushButton",
"... | create a button . | train | false |
32,625 | def create_status_line(**params):
max_size = (get_terminal_size().columns - 1)
for fmt in PROGRESS_FORMATS:
status = fmt.format(**params)
if (len(status) <= max_size):
break
return status
| [
"def",
"create_status_line",
"(",
"**",
"params",
")",
":",
"max_size",
"=",
"(",
"get_terminal_size",
"(",
")",
".",
"columns",
"-",
"1",
")",
"for",
"fmt",
"in",
"PROGRESS_FORMATS",
":",
"status",
"=",
"fmt",
".",
"format",
"(",
"**",
"params",
")",
... | creates a status line with appropriate size . | train | true |
32,626 | def getfixturemarker(obj):
try:
return getattr(obj, '_pytestfixturefunction', None)
except KeyboardInterrupt:
raise
except Exception:
return None
| [
"def",
"getfixturemarker",
"(",
"obj",
")",
":",
"try",
":",
"return",
"getattr",
"(",
"obj",
",",
"'_pytestfixturefunction'",
",",
"None",
")",
"except",
"KeyboardInterrupt",
":",
"raise",
"except",
"Exception",
":",
"return",
"None"
] | return fixturemarker or none if it doesnt exist or raised exceptions . | train | false |
32,627 | def may_certify_for_course(certificates_display_behavior, certificates_show_before_end, has_ended):
show_early = ((certificates_display_behavior in ('early_with_info', 'early_no_info')) or certificates_show_before_end)
return (show_early or has_ended)
| [
"def",
"may_certify_for_course",
"(",
"certificates_display_behavior",
",",
"certificates_show_before_end",
",",
"has_ended",
")",
":",
"show_early",
"=",
"(",
"(",
"certificates_display_behavior",
"in",
"(",
"'early_with_info'",
",",
"'early_no_info'",
")",
")",
"or",
... | returns whether it is acceptable to show the student a certificate download link for a course . | train | false |
32,628 | def pdb_invoke(method, arg):
import pdb
getattr(pdb.Pdb(nosigint=True), method)(arg)
| [
"def",
"pdb_invoke",
"(",
"method",
",",
"arg",
")",
":",
"import",
"pdb",
"getattr",
"(",
"pdb",
".",
"Pdb",
"(",
"nosigint",
"=",
"True",
")",
",",
"method",
")",
"(",
"arg",
")"
] | run pdb . | train | false |
32,629 | def write_models(model, data, field=None):
if hasattr(data, 'hashes'):
data = hashes_data(data)
written = []
for hash_ in data:
if field:
if (field not in hash_):
raise KeyError(('The "%s" field is required for all update operations' % field))
model_kwargs = {field: hash_[field]}
model_obj = model.objects.get(**model_kwargs)
for (to_set, val) in hash_.items():
setattr(model_obj, to_set, val)
model_obj.save()
else:
model_obj = model.objects.create(**hash_)
written.append(model_obj)
reset_sequence(model)
return written
| [
"def",
"write_models",
"(",
"model",
",",
"data",
",",
"field",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"data",
",",
"'hashes'",
")",
":",
"data",
"=",
"hashes_data",
"(",
"data",
")",
"written",
"=",
"[",
"]",
"for",
"hash_",
"in",
"data",
":... | create or update models for each data hash . | train | true |
32,632 | def _read_fragments(size, length, dir='.'):
filename = (((dir + '/') + _FRAGMENT_FILE) % (size, length))
with open(filename, 'r') as fp:
flist = []
fid = 0
for l in fp.readlines():
if ((l[0] == '*') or (l[0] == '\n')):
continue
sl = l.split()
if (sl[1] == '------'):
f = Fragment(length, fid)
flist.append(f)
fid += 1
continue
coord = numpy.array([float(x) for x in sl[0:3]])
f.add_residue('XXX', coord)
return flist
| [
"def",
"_read_fragments",
"(",
"size",
",",
"length",
",",
"dir",
"=",
"'.'",
")",
":",
"filename",
"=",
"(",
"(",
"(",
"dir",
"+",
"'/'",
")",
"+",
"_FRAGMENT_FILE",
")",
"%",
"(",
"size",
",",
"length",
")",
")",
"with",
"open",
"(",
"filename",
... | read a fragment spec file (available from u{URL} and return a list of fragment objects . | train | false |
32,633 | def truncate_fasta_qual(fasta_fp, qual_fp, output_dir, base_pos):
qual_lines = open(qual_fp, 'U')
fasta_lines = open(fasta_fp, 'U')
qual_scores = parse_qual_score(qual_lines, value_cast_f=str)
(fasta_seqs, seq_order) = parse_fasta_file(fasta_lines)
verify_equivalency(fasta_seqs, qual_scores)
(trunc_fasta_seqs, trunc_qual_scores) = truncate_seqs(fasta_seqs, qual_scores, base_pos)
(fasta_out_fp, qual_out_fp) = get_output_filepaths(output_dir, fasta_fp, qual_fp)
write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order)
write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order)
| [
"def",
"truncate_fasta_qual",
"(",
"fasta_fp",
",",
"qual_fp",
",",
"output_dir",
",",
"base_pos",
")",
":",
"qual_lines",
"=",
"open",
"(",
"qual_fp",
",",
"'U'",
")",
"fasta_lines",
"=",
"open",
"(",
"fasta_fp",
",",
"'U'",
")",
"qual_scores",
"=",
"pars... | main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: nucleotide position to truncate the fasta and quality score at . | train | false |
32,634 | def test_handshake_protocol(message, transport):
proto = 'chat'
message.headers.extend(gen_ws_headers(proto)[0])
(_, resp_headers, _, _, protocol) = do_handshake(message.method, message.headers, transport, protocols=[proto])
assert (protocol == proto)
resp_headers = dict(resp_headers)
assert (resp_headers['Sec-Websocket-Protocol'] == proto)
| [
"def",
"test_handshake_protocol",
"(",
"message",
",",
"transport",
")",
":",
"proto",
"=",
"'chat'",
"message",
".",
"headers",
".",
"extend",
"(",
"gen_ws_headers",
"(",
"proto",
")",
"[",
"0",
"]",
")",
"(",
"_",
",",
"resp_headers",
",",
"_",
",",
... | tests if one protocol is returned by do_handshake . | train | false |
32,637 | def MigratingUserRel(name, relation, disable_ids_fn=False, disable_reverse_ids_fn=False, permission_class=None):
mgr = MemoizedUserRelManager(name, relation, permission_class, disable_ids_fn, disable_reverse_ids_fn)
class URM:
pass
setattr(URM, ('is_' + name), mgr.get)
setattr(URM, ('get_' + name), mgr.get)
setattr(URM, ('add_' + name), staticmethod(mgr.add))
setattr(URM, ('remove_' + name), staticmethod(mgr.remove))
setattr(URM, ('each_' + name), mgr.by_thing)
setattr(URM, (name + '_permission_class'), permission_class)
if (not disable_ids_fn):
setattr(URM, mgr.ids_fn_name, mgr.ids)
if (not disable_reverse_ids_fn):
setattr(URM, mgr.reverse_ids_fn_name, staticmethod(mgr.reverse_ids))
return URM
| [
"def",
"MigratingUserRel",
"(",
"name",
",",
"relation",
",",
"disable_ids_fn",
"=",
"False",
",",
"disable_reverse_ids_fn",
"=",
"False",
",",
"permission_class",
"=",
"None",
")",
":",
"mgr",
"=",
"MemoizedUserRelManager",
"(",
"name",
",",
"relation",
",",
... | replacement for userrel to be used during migrations away from the system . | train | false |
32,638 | def init_store_from_template(translation_project, template_store):
if (translation_project.file_style == 'gnu'):
target_path = get_translated_name_gnu(translation_project, template_store)
else:
target_path = get_translated_name(translation_project, template_store)
target_dir = os.path.dirname(target_path)
if (not os.path.exists(target_dir)):
os.makedirs(target_dir)
output_file = template_store.file.store
output_file.settargetlanguage(translation_project.language.code)
output_file.savefile(target_path)
| [
"def",
"init_store_from_template",
"(",
"translation_project",
",",
"template_store",
")",
":",
"if",
"(",
"translation_project",
".",
"file_style",
"==",
"'gnu'",
")",
":",
"target_path",
"=",
"get_translated_name_gnu",
"(",
"translation_project",
",",
"template_store"... | initialize a new file for translation_project using template_store . | train | false |
32,639 | def create_tracker_session(tracker_url, timeout):
(tracker_type, tracker_address, announce_page) = parse_tracker_url(tracker_url)
if (tracker_type == u'UDP'):
return UdpTrackerSession(tracker_url, tracker_address, announce_page, timeout)
else:
return HttpTrackerSession(tracker_url, tracker_address, announce_page, timeout)
| [
"def",
"create_tracker_session",
"(",
"tracker_url",
",",
"timeout",
")",
":",
"(",
"tracker_type",
",",
"tracker_address",
",",
"announce_page",
")",
"=",
"parse_tracker_url",
"(",
"tracker_url",
")",
"if",
"(",
"tracker_type",
"==",
"u'UDP'",
")",
":",
"return... | creates a tracker session with the given tracker url . | train | false |
32,640 | def generate_keyfile(csrf_key, session_key):
output = file_template.safe_substitute(dict(csrf_key=csrf_key, session_key=session_key))
if os.path.exists(file_path):
if (options.force is None):
print "Warning: secret_keys.py file exists. Use 'generate_keys.py --force' to force overwrite."
else:
write_file(output)
else:
write_file(output)
| [
"def",
"generate_keyfile",
"(",
"csrf_key",
",",
"session_key",
")",
":",
"output",
"=",
"file_template",
".",
"safe_substitute",
"(",
"dict",
"(",
"csrf_key",
"=",
"csrf_key",
",",
"session_key",
"=",
"session_key",
")",
")",
"if",
"os",
".",
"path",
".",
... | generate random keys for csrf- and session key . | train | false |
32,642 | def _RecComputeRebalanceSize(mapping, server_id, dspath, subpath):
total = 0
fulldir = utils.JoinPath(dspath, subpath)
for comp in os.listdir(fulldir):
if (comp == constants.REBALANCE_DIRECTORY):
continue
path = utils.JoinPath(fulldir, comp)
(name, unused_extension) = os.path.splitext(comp)
if (name in COPY_EXCEPTIONS):
logging.info('Skip %s', comp)
continue
if os.path.isdir(path):
total += _RecComputeRebalanceSize(mapping, server_id, dspath, utils.JoinPath(subpath, comp))
elif os.path.isfile(path):
key = common.MakeDestinationKey(subpath, name)
where = sutils.MapKeyToServer(mapping, key)
if (where != server_id):
logging.info('Need to move %s from %d to %d', path, server_id, where)
total += os.path.getsize(path)
else:
logging.info('File %s stays here', path)
return total
| [
"def",
"_RecComputeRebalanceSize",
"(",
"mapping",
",",
"server_id",
",",
"dspath",
",",
"subpath",
")",
":",
"total",
"=",
"0",
"fulldir",
"=",
"utils",
".",
"JoinPath",
"(",
"dspath",
",",
"subpath",
")",
"for",
"comp",
"in",
"os",
".",
"listdir",
"(",... | recursively compute the size of files that need to be moved . | train | false |
32,643 | def list_quotas(profile=None):
conn = _auth(profile)
return conn.list_quotas()
| [
"def",
"list_quotas",
"(",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
")",
"return",
"conn",
".",
"list_quotas",
"(",
")"
] | fetches all tenants quotas cli example: . | train | false |
32,644 | def get_compiled_query(query_string, needles):
compiled_query = None
for word in get_query_words(query_string):
inner_query = None
for needle in needles:
q = Q(**{(u'%s__icontains' % needle): word})
inner_query = (q if (inner_query is None) else (inner_query | q))
compiled_query = (inner_query if (compiled_query is None) else (compiled_query & inner_query))
return compiled_query
| [
"def",
"get_compiled_query",
"(",
"query_string",
",",
"needles",
")",
":",
"compiled_query",
"=",
"None",
"for",
"word",
"in",
"get_query_words",
"(",
"query_string",
")",
":",
"inner_query",
"=",
"None",
"for",
"needle",
"in",
"needles",
":",
"q",
"=",
"Q"... | get compiled query compile query string into q objects and return it . | train | false |
32,645 | def strip_comment_marker(text):
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
| [
"def",
"strip_comment_marker",
"(",
"text",
")",
":",
"lines",
"=",
"[",
"]",
"for",
"line",
"in",
"text",
".",
"splitlines",
"(",
")",
":",
"lines",
".",
"append",
"(",
"line",
".",
"lstrip",
"(",
"'#'",
")",
")",
"text",
"=",
"textwrap",
".",
"de... | strip # markers at the front of a block of comment text . | train | true |
32,646 | def fitsinfo(filename):
try:
fits.info(filename)
except IOError as e:
log.error(str(e))
return
| [
"def",
"fitsinfo",
"(",
"filename",
")",
":",
"try",
":",
"fits",
".",
"info",
"(",
"filename",
")",
"except",
"IOError",
"as",
"e",
":",
"log",
".",
"error",
"(",
"str",
"(",
"e",
")",
")",
"return"
] | print a summary of the hdus in a fits file . | train | false |
32,647 | def meet(a, b, pointerType=HYPERNYM):
return (intersection(closure(a, pointerType), closure(b, pointerType)) + [None])[0]
| [
"def",
"meet",
"(",
"a",
",",
"b",
",",
"pointerType",
"=",
"HYPERNYM",
")",
":",
"return",
"(",
"intersection",
"(",
"closure",
"(",
"a",
",",
"pointerType",
")",
",",
"closure",
"(",
"b",
",",
"pointerType",
")",
")",
"+",
"[",
"None",
"]",
")",
... | return the meet of a and b under the pointertype relationship . | train | false |
32,648 | def _get_jinja_error_message(tb_data):
try:
line = _get_jinja_error_slug(tb_data)
return u'{0}({1}):\n{3}'.format(*line)
except IndexError:
pass
return None
| [
"def",
"_get_jinja_error_message",
"(",
"tb_data",
")",
":",
"try",
":",
"line",
"=",
"_get_jinja_error_slug",
"(",
"tb_data",
")",
"return",
"u'{0}({1}):\\n{3}'",
".",
"format",
"(",
"*",
"line",
")",
"except",
"IndexError",
":",
"pass",
"return",
"None"
] | return an understandable message from jinja error output . | train | false |
32,650 | def get_credential(tenant_id, credential_id):
session = db.get_session()
try:
cred = session.query(l2network_models.Credential).filter_by(tenant_id=tenant_id).filter_by(credential_id=credential_id).one()
return cred
except exc.NoResultFound:
raise c_exc.CredentialNotFound(credential_id=credential_id, tenant_id=tenant_id)
| [
"def",
"get_credential",
"(",
"tenant_id",
",",
"credential_id",
")",
":",
"session",
"=",
"db",
".",
"get_session",
"(",
")",
"try",
":",
"cred",
"=",
"session",
".",
"query",
"(",
"l2network_models",
".",
"Credential",
")",
".",
"filter_by",
"(",
"tenant... | lists the creds for given a cred_id and tenant_id . | train | false |
32,651 | def model_json_decoder(dct):
if (u'__model__' in dct):
model_name = dct.pop(u'__model__')
if (model_name in immutable._models):
cls = immutable._models[model_name]
return cls(**dct)
return dct
| [
"def",
"model_json_decoder",
"(",
"dct",
")",
":",
"if",
"(",
"u'__model__'",
"in",
"dct",
")",
":",
"model_name",
"=",
"dct",
".",
"pop",
"(",
"u'__model__'",
")",
"if",
"(",
"model_name",
"in",
"immutable",
".",
"_models",
")",
":",
"cls",
"=",
"immu... | automatically deserialize mopidy models from json . | train | false |
32,652 | def _login(**kwargs):
connargs = dict()
def _connarg(name, key=None):
"\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n "
if (key is None):
key = name
if (name in kwargs):
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if (val is not None):
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if ('url' not in connargs):
connargs['url'] = _frontend_url()
try:
if (connargs['user'] and connargs['password'] and connargs['url']):
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError:
return False
| [
"def",
"_login",
"(",
"**",
"kwargs",
")",
":",
"connargs",
"=",
"dict",
"(",
")",
"def",
"_connarg",
"(",
"name",
",",
"key",
"=",
"None",
")",
":",
"if",
"(",
"key",
"is",
"None",
")",
":",
"key",
"=",
"name",
"if",
"(",
"name",
"in",
"kwargs... | this function is used internally and should not ever be called directly . | train | true |
32,654 | def load_nodegraph(filename):
nodegraph = _Nodegraph(1, [1])
nodegraph.load(filename)
return nodegraph
| [
"def",
"load_nodegraph",
"(",
"filename",
")",
":",
"nodegraph",
"=",
"_Nodegraph",
"(",
"1",
",",
"[",
"1",
"]",
")",
"nodegraph",
".",
"load",
"(",
"filename",
")",
"return",
"nodegraph"
] | load a nodegraph object from the given filename and return it . | train | false |
32,655 | def new(rsa_key):
return PKCS115_SigScheme(rsa_key)
| [
"def",
"new",
"(",
"rsa_key",
")",
":",
"return",
"PKCS115_SigScheme",
"(",
"rsa_key",
")"
] | create a new aes cipher . | train | false |
32,656 | def getMinimumByComplexPaths(paths):
minimum = complex(9.876543219876543e+17, 9.876543219876543e+17)
for path in paths:
for point in path:
minimum = getMinimum(minimum, point)
return minimum
| [
"def",
"getMinimumByComplexPaths",
"(",
"paths",
")",
":",
"minimum",
"=",
"complex",
"(",
"9.876543219876543e+17",
",",
"9.876543219876543e+17",
")",
"for",
"path",
"in",
"paths",
":",
"for",
"point",
"in",
"path",
":",
"minimum",
"=",
"getMinimum",
"(",
"min... | get a complex with each component the minimum of the respective components of complex paths . | train | false |
32,657 | def gnp_random_graph(n, p, seed=None, directed=False):
if directed:
G = nx.DiGraph()
else:
G = nx.Graph()
G.add_nodes_from(range(n))
G.name = ('gnp_random_graph(%s,%s)' % (n, p))
if (p <= 0):
return G
if (p >= 1):
return complete_graph(n, create_using=G)
if (not (seed is None)):
random.seed(seed)
if G.is_directed():
edges = itertools.permutations(range(n), 2)
else:
edges = itertools.combinations(range(n), 2)
for e in edges:
if (random.random() < p):
G.add_edge(*e)
return G
| [
"def",
"gnp_random_graph",
"(",
"n",
",",
"p",
",",
"seed",
"=",
"None",
",",
"directed",
"=",
"False",
")",
":",
"if",
"directed",
":",
"G",
"=",
"nx",
".",
"DiGraph",
"(",
")",
"else",
":",
"G",
"=",
"nx",
".",
"Graph",
"(",
")",
"G",
".",
... | returns a g_{n . | train | false |
32,658 | def varint(i):
if (i < len(_varint_cache)):
return _varint_cache[i]
return _varint(i)
| [
"def",
"varint",
"(",
"i",
")",
":",
"if",
"(",
"i",
"<",
"len",
"(",
"_varint_cache",
")",
")",
":",
"return",
"_varint_cache",
"[",
"i",
"]",
"return",
"_varint",
"(",
"i",
")"
] | encodes the given integer into a string of the minimum number of bytes . | train | false |
32,660 | def add_codec(charset, codecname):
CODEC_MAP[charset] = codecname
| [
"def",
"add_codec",
"(",
"charset",
",",
"codecname",
")",
":",
"CODEC_MAP",
"[",
"charset",
"]",
"=",
"codecname"
] | add a codec that map characters in the given charset to/from unicode . | train | false |
32,661 | def svd_compressed(a, k, n_power_iter=0, seed=None, name=None):
comp = compression_matrix(a, k, n_power_iter=n_power_iter, seed=seed)
a_compressed = comp.dot(a)
(v, s, u) = tsqr(a_compressed.T, name, compute_svd=True)
u = comp.T.dot(u)
v = v.T
u = u[:, :k]
s = s[:k]
v = v[:k, :]
return (u, s, v)
| [
"def",
"svd_compressed",
"(",
"a",
",",
"k",
",",
"n_power_iter",
"=",
"0",
",",
"seed",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"comp",
"=",
"compression_matrix",
"(",
"a",
",",
"k",
",",
"n_power_iter",
"=",
"n_power_iter",
",",
"seed",
"=... | randomly compressed rank-k thin singular value decomposition . | train | false |
32,663 | def get_image_json(image):
preview_image = image.get_rendition(u'max-165x165')
return json.dumps({u'id': image.id, u'edit_link': reverse(u'wagtailimages:edit', args=(image.id,)), u'title': image.title, u'preview': {u'url': preview_image.url, u'width': preview_image.width, u'height': preview_image.height}})
| [
"def",
"get_image_json",
"(",
"image",
")",
":",
"preview_image",
"=",
"image",
".",
"get_rendition",
"(",
"u'max-165x165'",
")",
"return",
"json",
".",
"dumps",
"(",
"{",
"u'id'",
":",
"image",
".",
"id",
",",
"u'edit_link'",
":",
"reverse",
"(",
"u'wagta... | helper function: given an image . | train | false |
32,664 | @register.filter
def min_value(object_list, field):
value_list = [getattr(o, field, None) for o in object_list]
return min(value_list)
| [
"@",
"register",
".",
"filter",
"def",
"min_value",
"(",
"object_list",
",",
"field",
")",
":",
"value_list",
"=",
"[",
"getattr",
"(",
"o",
",",
"field",
",",
"None",
")",
"for",
"o",
"in",
"object_list",
"]",
"return",
"min",
"(",
"value_list",
")"
] | returns the min value given an object_list and a field . | train | false |
32,665 | @frappe.whitelist()
def remove_attach():
import frappe.utils.file_manager
fid = frappe.form_dict.get(u'fid')
return frappe.utils.file_manager.remove_file(fid)
| [
"@",
"frappe",
".",
"whitelist",
"(",
")",
"def",
"remove_attach",
"(",
")",
":",
"import",
"frappe",
".",
"utils",
".",
"file_manager",
"fid",
"=",
"frappe",
".",
"form_dict",
".",
"get",
"(",
"u'fid'",
")",
"return",
"frappe",
".",
"utils",
".",
"fil... | remove attachment . | train | false |
32,666 | def get_jinja_environment(allow_undefined=False, trim_blocks=True, lstrip_blocks=True):
import jinja2
undefined = (jinja2.Undefined if allow_undefined else jinja2.StrictUndefined)
env = jinja2.Environment(undefined=undefined, trim_blocks=trim_blocks, lstrip_blocks=lstrip_blocks)
env.filters.update(get_filters())
env.tests['in'] = (lambda item, list: (item in list))
return env
| [
"def",
"get_jinja_environment",
"(",
"allow_undefined",
"=",
"False",
",",
"trim_blocks",
"=",
"True",
",",
"lstrip_blocks",
"=",
"True",
")",
":",
"import",
"jinja2",
"undefined",
"=",
"(",
"jinja2",
".",
"Undefined",
"if",
"allow_undefined",
"else",
"jinja2",
... | sets the environment for jinja . | train | false |
32,667 | def batch_dot(x, y, axes=None):
if isinstance(axes, int):
axes = (axes, axes)
if (axes is None):
axes = [(x.ndim - 1), (y.ndim - 2)]
out = T.batched_tensordot(x, y, axes=axes)
if (ndim(out) == 1):
out = expand_dims(out, 1)
return out
| [
"def",
"batch_dot",
"(",
"x",
",",
"y",
",",
"axes",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"axes",
",",
"int",
")",
":",
"axes",
"=",
"(",
"axes",
",",
"axes",
")",
"if",
"(",
"axes",
"is",
"None",
")",
":",
"axes",
"=",
"[",
"(",
... | batchwise dot product . | train | false |
32,668 | def set_by_domain(domain):
BACKEND.set_config_by_domain(domain)
| [
"def",
"set_by_domain",
"(",
"domain",
")",
":",
"BACKEND",
".",
"set_config_by_domain",
"(",
"domain",
")"
] | for a given request domain . | train | false |
32,669 | def installed_solvers():
installed = []
for (name, solver) in SOLVERS.items():
if solver.is_installed():
installed.append(name)
return installed
| [
"def",
"installed_solvers",
"(",
")",
":",
"installed",
"=",
"[",
"]",
"for",
"(",
"name",
",",
"solver",
")",
"in",
"SOLVERS",
".",
"items",
"(",
")",
":",
"if",
"solver",
".",
"is_installed",
"(",
")",
":",
"installed",
".",
"append",
"(",
"name",
... | list the installed solvers . | train | false |
32,670 | def getAllExperimentDirectories(excludedExperiments=[]):
excludedDirectories = ['exp', 'inference', 'networks', 'legacy']
excludedDirectories.extend(excludedExperiments)
return getAllDirectoriesWithFile(path='experiments', filename='description.py', excludeDirs=excludedDirectories)
| [
"def",
"getAllExperimentDirectories",
"(",
"excludedExperiments",
"=",
"[",
"]",
")",
":",
"excludedDirectories",
"=",
"[",
"'exp'",
",",
"'inference'",
",",
"'networks'",
",",
"'legacy'",
"]",
"excludedDirectories",
".",
"extend",
"(",
"excludedExperiments",
")",
... | experiment directories are the directories with a description . | train | false |
32,671 | def reverse_geocode(lat, lng):
try:
result = get_first_mapbox_geocode_result(('%s,%s' % (lng, lat)))
except HTTPError:
logger.exception('HTTP status error when calling Mapbox.')
raise GeoLookupException
except ConnectionError:
logger.exception('Cannot open connection to Mapbox.')
raise GeoLookupException
if result:
return result_to_country_region_city(result)
else:
return (None, None, None)
| [
"def",
"reverse_geocode",
"(",
"lat",
",",
"lng",
")",
":",
"try",
":",
"result",
"=",
"get_first_mapbox_geocode_result",
"(",
"(",
"'%s,%s'",
"%",
"(",
"lng",
",",
"lat",
")",
")",
")",
"except",
"HTTPError",
":",
"logger",
".",
"exception",
"(",
"'HTTP... | reverse geocoding is the process of converting geographic coordinates into a human-readable address . | train | false |
32,673 | def set_credentials_file(username=None, api_key=None, stream_ids=None, proxy_username=None, proxy_password=None):
if (not check_file_permissions()):
raise exceptions.PlotlyError("You don't have proper file permissions to run this function.")
ensure_local_plotly_files()
credentials = get_credentials_file()
if isinstance(username, six.string_types):
credentials['username'] = username
if isinstance(api_key, six.string_types):
credentials['api_key'] = api_key
if isinstance(proxy_username, six.string_types):
credentials['proxy_username'] = proxy_username
if isinstance(proxy_password, six.string_types):
credentials['proxy_password'] = proxy_password
if isinstance(stream_ids, (list, tuple)):
credentials['stream_ids'] = stream_ids
utils.save_json_dict(CREDENTIALS_FILE, credentials)
ensure_local_plotly_files()
| [
"def",
"set_credentials_file",
"(",
"username",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"stream_ids",
"=",
"None",
",",
"proxy_username",
"=",
"None",
",",
"proxy_password",
"=",
"None",
")",
":",
"if",
"(",
"not",
"check_file_permissions",
"(",
")",
... | set the keyword-value pairs in ~/ . | train | false |
32,674 | def parse_illumina_line(l, barcode_length, rev_comp_barcode, barcode_in_sequence=False):
fields = l.strip().split(':')
y_position_subfields = fields[4].split('#')
y_position = int(y_position_subfields[0])
sequence = fields[5]
qual_string = fields[6]
if barcode_in_sequence:
barcode = sequence[:barcode_length]
sequence = sequence[barcode_length:]
qual_string = qual_string[barcode_length:]
else:
barcode = y_position_subfields[1][:barcode_length]
if rev_comp_barcode:
barcode = str(DNA(barcode).rc())
result = {'Full description': ':'.join(fields[:5]), 'Machine Name': fields[0], 'Channel Number': int(fields[1]), 'Tile Number': int(fields[2]), 'X Position': int(fields[3]), 'Y Position': y_position, 'Barcode': barcode, 'Full Y Position Field': fields[4], 'Sequence': sequence, 'Quality Score': qual_string}
return result
| [
"def",
"parse_illumina_line",
"(",
"l",
",",
"barcode_length",
",",
"rev_comp_barcode",
",",
"barcode_in_sequence",
"=",
"False",
")",
":",
"fields",
"=",
"l",
".",
"strip",
"(",
")",
".",
"split",
"(",
"':'",
")",
"y_position_subfields",
"=",
"fields",
"[",... | parses a single line of illumina data . | train | false |
32,677 | def send_interrupt(process):
try:
os.kill(process.pid, SIGINT)
except OSError:
pass
except TypeError:
pass
except UnboundLocalError:
pass
except AttributeError:
pass
| [
"def",
"send_interrupt",
"(",
"process",
")",
":",
"try",
":",
"os",
".",
"kill",
"(",
"process",
".",
"pid",
",",
"SIGINT",
")",
"except",
"OSError",
":",
"pass",
"except",
"TypeError",
":",
"pass",
"except",
"UnboundLocalError",
":",
"pass",
"except",
... | sends interrupt signal to processs pid . | train | false |
32,680 | def getWidthHex(number, width):
return ('0000%s' % hex(number)[2:])[(- width):]
| [
"def",
"getWidthHex",
"(",
"number",
",",
"width",
")",
":",
"return",
"(",
"'0000%s'",
"%",
"hex",
"(",
"number",
")",
"[",
"2",
":",
"]",
")",
"[",
"(",
"-",
"width",
")",
":",
"]"
] | get the first width hexadecimal digits . | train | false |
32,681 | @track_time_change(hour=7, minute=0, second=0)
def wake_up(hass, now):
if (not TARGET_ID):
return
if (device_tracker.is_on(hass) and (not core.is_on(hass, TARGET_ID))):
_LOGGER.info('People home at 7AM, turning it on')
core.turn_on(hass, TARGET_ID)
| [
"@",
"track_time_change",
"(",
"hour",
"=",
"7",
",",
"minute",
"=",
"0",
",",
"second",
"=",
"0",
")",
"def",
"wake_up",
"(",
"hass",
",",
"now",
")",
":",
"if",
"(",
"not",
"TARGET_ID",
")",
":",
"return",
"if",
"(",
"device_tracker",
".",
"is_on... | turn light on in the morning . | train | false |
32,683 | def nearestPoint(a, b, c):
magnitude = np.linalg.norm((b - a))
if (magnitude == 0):
raise Exception, 'Line segment cannot be 0 length'
return (((b - a) * np.dot(((c - a) / magnitude), ((b - a) / magnitude))) + a)
| [
"def",
"nearestPoint",
"(",
"a",
",",
"b",
",",
"c",
")",
":",
"magnitude",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"(",
"b",
"-",
"a",
")",
")",
"if",
"(",
"magnitude",
"==",
"0",
")",
":",
"raise",
"Exception",
",",
"'Line segment cannot be 0... | nearest point to point c on line a_b . | train | false |
32,685 | def render_token_data_response(token_id, token_data):
headers = [('X-Subject-Token', token_id)]
return wsgi.render_response(body=token_data, status=(http_client.OK, http_client.responses[http_client.OK]), headers=headers)
| [
"def",
"render_token_data_response",
"(",
"token_id",
",",
"token_data",
")",
":",
"headers",
"=",
"[",
"(",
"'X-Subject-Token'",
",",
"token_id",
")",
"]",
"return",
"wsgi",
".",
"render_response",
"(",
"body",
"=",
"token_data",
",",
"status",
"=",
"(",
"h... | render token data http response . | train | false |
32,686 | def getTricomplexrotate(transformWords):
rotate = euclidean.getWiddershinsUnitPolar(math.radians(float(transformWords[0])))
return [rotate, complex((- rotate.imag), rotate.real), complex()]
| [
"def",
"getTricomplexrotate",
"(",
"transformWords",
")",
":",
"rotate",
"=",
"euclidean",
".",
"getWiddershinsUnitPolar",
"(",
"math",
".",
"radians",
"(",
"float",
"(",
"transformWords",
"[",
"0",
"]",
")",
")",
")",
"return",
"[",
"rotate",
",",
"complex"... | get matrixsvg by transformwords . | train | false |
32,688 | def read_images_from_disk(input_queue):
label = input_queue[1]
file_contents = tf.read_file(input_queue[0])
example = tf.image.decode_png(file_contents, channels=3)
return (example, label)
| [
"def",
"read_images_from_disk",
"(",
"input_queue",
")",
":",
"label",
"=",
"input_queue",
"[",
"1",
"]",
"file_contents",
"=",
"tf",
".",
"read_file",
"(",
"input_queue",
"[",
"0",
"]",
")",
"example",
"=",
"tf",
".",
"image",
".",
"decode_png",
"(",
"f... | consumes a single filename and label as a -delimited string . | train | false |
32,689 | @testing.requires_testing_data
def test_make_inverse_operator_bads():
fwd_op = read_forward_solution_meg(fname_fwd, surf_ori=True)
evoked = _get_evoked()
noise_cov = read_cov(fname_cov)
bad = evoked.info['bads'].pop()
inv_ = make_inverse_operator(evoked.info, fwd_op, noise_cov, loose=None)
union_good = (set(noise_cov['names']) & set(evoked.ch_names))
union_bads = (set(noise_cov['bads']) & set(evoked.info['bads']))
evoked.info['bads'].append(bad)
assert_true((len((set(inv_['info']['ch_names']) - union_good)) == 0))
assert_true((len((set(inv_['info']['bads']) - union_bads)) == 0))
| [
"@",
"testing",
".",
"requires_testing_data",
"def",
"test_make_inverse_operator_bads",
"(",
")",
":",
"fwd_op",
"=",
"read_forward_solution_meg",
"(",
"fname_fwd",
",",
"surf_ori",
"=",
"True",
")",
"evoked",
"=",
"_get_evoked",
"(",
")",
"noise_cov",
"=",
"read_... | test mne inverse computation given a mismatch of bad channels . | train | false |
32,690 | def copy_files_matching_pattern(file_path_pattern, dest):
for file in glob.glob(file_path_pattern):
shutil.copy(file, dest)
| [
"def",
"copy_files_matching_pattern",
"(",
"file_path_pattern",
",",
"dest",
")",
":",
"for",
"file",
"in",
"glob",
".",
"glob",
"(",
"file_path_pattern",
")",
":",
"shutil",
".",
"copy",
"(",
"file",
",",
"dest",
")"
] | copies files matching the specified pattern to the destination directory . | train | false |
32,691 | def _get_svc_path(name='*', status=None):
if (not SERVICE_DIR):
raise CommandExecutionError('Could not find service directory.')
ena = set()
for el in glob.glob(os.path.join(SERVICE_DIR, name)):
if _is_svc(el):
ena.add(os.readlink(el))
log.trace('found enabled service path: {0}'.format(el))
if (status == 'ENABLED'):
return sorted(ena)
ava = set()
for d in AVAIL_SVR_DIRS:
for el in glob.glob(os.path.join(d, name)):
if _is_svc(el):
ava.add(el)
log.trace('found available service path: {0}'.format(el))
if (status == 'DISABLED'):
ret = ava.difference(ena)
else:
ret = ava.union(ena)
return sorted(ret)
| [
"def",
"_get_svc_path",
"(",
"name",
"=",
"'*'",
",",
"status",
"=",
"None",
")",
":",
"if",
"(",
"not",
"SERVICE_DIR",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'Could not find service directory.'",
")",
"ena",
"=",
"set",
"(",
")",
"for",
"el",
"... | return a list of paths to services with name that have the specified status name a glob for service name . | train | true |
32,692 | def add_cell_to_task_log(task_log, cell_name):
task_log['id'] = cell_with_item(cell_name, task_log['id'])
task_log['host'] = cell_with_item(cell_name, task_log['host'])
| [
"def",
"add_cell_to_task_log",
"(",
"task_log",
",",
"cell_name",
")",
":",
"task_log",
"[",
"'id'",
"]",
"=",
"cell_with_item",
"(",
"cell_name",
",",
"task_log",
"[",
"'id'",
"]",
")",
"task_log",
"[",
"'host'",
"]",
"=",
"cell_with_item",
"(",
"cell_name"... | fix task_log attributes that should be unique . | train | false |
32,694 | def getWidthMultipliedPath(path, widthMultiplier):
for (pointIndex, point) in enumerate(path):
path[pointIndex] = complex((point.real * widthMultiplier), point.imag)
return path
| [
"def",
"getWidthMultipliedPath",
"(",
"path",
",",
"widthMultiplier",
")",
":",
"for",
"(",
"pointIndex",
",",
"point",
")",
"in",
"enumerate",
"(",
"path",
")",
":",
"path",
"[",
"pointIndex",
"]",
"=",
"complex",
"(",
"(",
"point",
".",
"real",
"*",
... | get width multiplied path . | train | false |
32,695 | @must_be_logged_in
def unconfirmed_email_add(auth=None):
user = auth.user
json_body = request.get_json()
try:
token = json_body['token']
except KeyError:
raise HTTPError(http.BAD_REQUEST, data={'message_short': 'Missing token', 'message_long': 'Must provide a token'})
try:
user.confirm_email(token, merge=True)
except exceptions.InvalidTokenError:
raise InvalidTokenError(http.BAD_REQUEST, data={'message_short': 'Invalid user token', 'message_long': 'The user token is invalid'})
except exceptions.EmailConfirmTokenError as e:
raise HTTPError(http.BAD_REQUEST, data={'message_short': e.message_short, 'message_long': e.message_long})
user.save()
return ({'status': 'success', 'removed_email': json_body['address']}, 200)
| [
"@",
"must_be_logged_in",
"def",
"unconfirmed_email_add",
"(",
"auth",
"=",
"None",
")",
":",
"user",
"=",
"auth",
".",
"user",
"json_body",
"=",
"request",
".",
"get_json",
"(",
")",
"try",
":",
"token",
"=",
"json_body",
"[",
"'token'",
"]",
"except",
... | called at login if user confirms their merge or email add . | train | false |
32,697 | def get_pkg_id(pkg):
pkg = _quote(pkg)
package_ids = []
temp_dir = __salt__['temp.dir'](prefix='pkg-')
try:
cmd = 'xar -t -f {0} | grep PackageInfo'.format(pkg)
out = __salt__['cmd.run'](cmd, python_shell=True, output_loglevel='quiet')
files = out.split('\n')
if ('Error opening' not in out):
cmd = 'xar -x -f {0} {1}'.format(pkg, ' '.join(files))
__salt__['cmd.run'](cmd, cwd=temp_dir, output_loglevel='quiet')
for f in files:
i = _get_pkg_id_from_pkginfo(os.path.join(temp_dir, f))
if len(i):
package_ids.extend(i)
else:
package_ids = _get_pkg_id_dir(pkg)
finally:
__salt__['file.remove'](temp_dir)
return package_ids
| [
"def",
"get_pkg_id",
"(",
"pkg",
")",
":",
"pkg",
"=",
"_quote",
"(",
"pkg",
")",
"package_ids",
"=",
"[",
"]",
"temp_dir",
"=",
"__salt__",
"[",
"'temp.dir'",
"]",
"(",
"prefix",
"=",
"'pkg-'",
")",
"try",
":",
"cmd",
"=",
"'xar -t -f {0} | grep Package... | attempt to get the package id from a . | train | true |
32,698 | def test_slice_getslice_forbidden():
class foo:
def __getslice__(self, i, j):
return 42
def __getitem__(self, index):
return 23
AreEqual(foo()[::None], 23)
AreEqual(foo()[::None], 23)
| [
"def",
"test_slice_getslice_forbidden",
"(",
")",
":",
"class",
"foo",
":",
"def",
"__getslice__",
"(",
"self",
",",
"i",
",",
"j",
")",
":",
"return",
"42",
"def",
"__getitem__",
"(",
"self",
",",
"index",
")",
":",
"return",
"23",
"AreEqual",
"(",
"f... | providing no value for step forbids calling __getslice__ . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.