labNo
float64
1
10
taskNo
float64
0
4
questioner
stringclasses
2 values
question
stringlengths
9
201
code
stringlengths
18
30.3k
startLine
float64
0
192
endLine
float64
0
196
questionType
stringclasses
4 values
answer
stringlengths
2
905
src
stringclasses
3 values
code_processed
stringlengths
12
28.3k
id
stringlengths
2
5
raw_code
stringlengths
20
30.3k
raw_comment
stringlengths
10
242
comment
stringlengths
9
207
q_code
stringlengths
66
30.3k
null
null
null
What have only one role ?
def test_imap_many_folders_one_role(monkeypatch, constants): folders = constants['imap_folders'] duplicates = [(('\\HasNoChildren', '\\Trash'), '/', u'[Gmail]/Trash'), ('\\HasNoChildren', '/', u'[Gmail]/Sent')] folders += duplicates client = patch_generic_client(monkeypatch, folders) raw_folders = client.folders() folder_names = client.folder_names() for role in ['inbox', 'trash', 'drafts', 'sent', 'spam']: assert (role in folder_names) number_roles = (2 if (role in ['sent', 'trash']) else 1) test_set = filter((lambda x: (x == role)), map((lambda y: y.role), raw_folders)) assert (len(test_set) == number_roles), 'assigned wrong number of {}'.format(role)
null
null
null
accounts with many folders with similar system folders
codeqa
def test imap many folders one role monkeypatch constants folders constants['imap folders']duplicates [ '\\ Has No Children' '\\ Trash' '/' u'[ Gmail]/ Trash' '\\ Has No Children' '/' u'[ Gmail]/ Sent' ]folders + duplicatesclient patch generic client monkeypatch folders raw folders client folders folder names client folder names for role in ['inbox' 'trash' 'drafts' 'sent' 'spam'] assert role in folder names number roles 2 if role in ['sent' 'trash'] else 1 test set filter lambda x x role map lambda y y role raw folders assert len test set number roles 'assignedwrongnumberof{}' format role
null
null
null
null
Question: What have only one role ? Code: def test_imap_many_folders_one_role(monkeypatch, constants): folders = constants['imap_folders'] duplicates = [(('\\HasNoChildren', '\\Trash'), '/', u'[Gmail]/Trash'), ('\\HasNoChildren', '/', u'[Gmail]/Sent')] folders += duplicates client = patch_generic_client(monkeypatch, folders) raw_folders = client.folders() folder_names = client.folder_names() for role in ['inbox', 'trash', 'drafts', 'sent', 'spam']: assert (role in folder_names) number_roles = (2 if (role in ['sent', 'trash']) else 1) test_set = filter((lambda x: (x == role)), map((lambda y: y.role), raw_folders)) assert (len(test_set) == number_roles), 'assigned wrong number of {}'.format(role)
null
null
null
What do accounts with many folders with similar system folders have ?
def test_imap_many_folders_one_role(monkeypatch, constants): folders = constants['imap_folders'] duplicates = [(('\\HasNoChildren', '\\Trash'), '/', u'[Gmail]/Trash'), ('\\HasNoChildren', '/', u'[Gmail]/Sent')] folders += duplicates client = patch_generic_client(monkeypatch, folders) raw_folders = client.folders() folder_names = client.folder_names() for role in ['inbox', 'trash', 'drafts', 'sent', 'spam']: assert (role in folder_names) number_roles = (2 if (role in ['sent', 'trash']) else 1) test_set = filter((lambda x: (x == role)), map((lambda y: y.role), raw_folders)) assert (len(test_set) == number_roles), 'assigned wrong number of {}'.format(role)
null
null
null
only one role
codeqa
def test imap many folders one role monkeypatch constants folders constants['imap folders']duplicates [ '\\ Has No Children' '\\ Trash' '/' u'[ Gmail]/ Trash' '\\ Has No Children' '/' u'[ Gmail]/ Sent' ]folders + duplicatesclient patch generic client monkeypatch folders raw folders client folders folder names client folder names for role in ['inbox' 'trash' 'drafts' 'sent' 'spam'] assert role in folder names number roles 2 if role in ['sent' 'trash'] else 1 test set filter lambda x x role map lambda y y role raw folders assert len test set number roles 'assignedwrongnumberof{}' format role
null
null
null
null
Question: What do accounts with many folders with similar system folders have ? Code: def test_imap_many_folders_one_role(monkeypatch, constants): folders = constants['imap_folders'] duplicates = [(('\\HasNoChildren', '\\Trash'), '/', u'[Gmail]/Trash'), ('\\HasNoChildren', '/', u'[Gmail]/Sent')] folders += duplicates client = patch_generic_client(monkeypatch, folders) raw_folders = client.folders() folder_names = client.folder_names() for role in ['inbox', 'trash', 'drafts', 'sent', 'spam']: assert (role in folder_names) number_roles = (2 if (role in ['sent', 'trash']) else 1) test_set = filter((lambda x: (x == role)), map((lambda y: y.role), raw_folders)) assert (len(test_set) == number_roles), 'assigned wrong number of {}'.format(role)
null
null
null
How is the parent set ?
def test_parent(): parent = Parent() t = usertypes.Timer(parent) assert (t.parent() is parent)
null
null
null
correctly
codeqa
def test parent parent Parent t usertypes Timer parent assert t parent is parent
null
null
null
null
Question: How is the parent set ? Code: def test_parent(): parent = Parent() t = usertypes.Timer(parent) assert (t.parent() is parent)
null
null
null
What do a string or tuple represent as path ?
def traverse(resource, path): if is_nonstr_iter(path): if path: path = _join_path_tuple(tuple(path)) else: path = '' path = ascii_native_(path) if (path and (path[0] == '/')): resource = find_root(resource) reg = get_current_registry() request_factory = reg.queryUtility(IRequestFactory) if (request_factory is None): from pyramid.request import Request request_factory = Request request = request_factory.blank(path) request.registry = reg traverser = reg.queryAdapter(resource, ITraverser) if (traverser is None): traverser = ResourceTreeTraverser(resource) return traverser(request)
null
null
null
a path
codeqa
def traverse resource path if is nonstr iter path if path path join path tuple tuple path else path ''path ascii native path if path and path[ 0 ] '/' resource find root resource reg get current registry request factory reg query Utility I Request Factory if request factory is None from pyramid request import Requestrequest factory Requestrequest request factory blank path request registry regtraverser reg query Adapter resource I Traverser if traverser is None traverser Resource Tree Traverser resource return traverser request
null
null
null
null
Question: What do a string or tuple represent as path ? Code: def traverse(resource, path): if is_nonstr_iter(path): if path: path = _join_path_tuple(tuple(path)) else: path = '' path = ascii_native_(path) if (path and (path[0] == '/')): resource = find_root(resource) reg = get_current_registry() request_factory = reg.queryUtility(IRequestFactory) if (request_factory is None): from pyramid.request import Request request_factory = Request request = request_factory.blank(path) request.registry = reg traverser = reg.queryAdapter(resource, ITraverser) if (traverser is None): traverser = ResourceTreeTraverser(resource) return traverser(request)
null
null
null
What is representing a path as path ?
def traverse(resource, path): if is_nonstr_iter(path): if path: path = _join_path_tuple(tuple(path)) else: path = '' path = ascii_native_(path) if (path and (path[0] == '/')): resource = find_root(resource) reg = get_current_registry() request_factory = reg.queryUtility(IRequestFactory) if (request_factory is None): from pyramid.request import Request request_factory = Request request = request_factory.blank(path) request.registry = reg traverser = reg.queryAdapter(resource, ITraverser) if (traverser is None): traverser = ResourceTreeTraverser(resource) return traverser(request)
null
null
null
a string or tuple
codeqa
def traverse resource path if is nonstr iter path if path path join path tuple tuple path else path ''path ascii native path if path and path[ 0 ] '/' resource find root resource reg get current registry request factory reg query Utility I Request Factory if request factory is None from pyramid request import Requestrequest factory Requestrequest request factory blank path request registry regtraverser reg query Adapter resource I Traverser if traverser is None traverser Resource Tree Traverser resource return traverser request
null
null
null
null
Question: What is representing a path as path ? Code: def traverse(resource, path): if is_nonstr_iter(path): if path: path = _join_path_tuple(tuple(path)) else: path = '' path = ascii_native_(path) if (path and (path[0] == '/')): resource = find_root(resource) reg = get_current_registry() request_factory = reg.queryUtility(IRequestFactory) if (request_factory is None): from pyramid.request import Request request_factory = Request request = request_factory.blank(path) request.registry = reg traverser = reg.queryAdapter(resource, ITraverser) if (traverser is None): traverser = ResourceTreeTraverser(resource) return traverser(request)
null
null
null
When did projects modify ?
@pytest.mark.cmd @pytest.mark.django_db def test_list_projects_modified_since(capfd): call_command('list_projects', '--modified-since=5') (out, err) = capfd.readouterr() assert ('project0' in out) assert ('project1' in out)
null
null
null
since a revision
codeqa
@pytest mark cmd@pytest mark django dbdef test list projects modified since capfd call command 'list projects' '--modified-since 5' out err capfd readouterr assert 'project 0 ' in out assert 'project 1 ' in out
null
null
null
null
Question: When did projects modify ? Code: @pytest.mark.cmd @pytest.mark.django_db def test_list_projects_modified_since(capfd): call_command('list_projects', '--modified-since=5') (out, err) = capfd.readouterr() assert ('project0' in out) assert ('project1' in out)
null
null
null
When does the code replace ?
def replace(s, old, new, maxsplit=0): return s.replace(old, new, maxsplit)
null
null
null
str
codeqa
def replace s old new maxsplit 0 return s replace old new maxsplit
null
null
null
null
Question: When does the code replace ? Code: def replace(s, old, new, maxsplit=0): return s.replace(old, new, maxsplit)
null
null
null
What does the code destroy ?
def destroy(ctid_or_name): return _vzctl('destroy', ctid_or_name)
null
null
null
the container
codeqa
def destroy ctid or name return vzctl 'destroy' ctid or name
null
null
null
null
Question: What does the code destroy ? Code: def destroy(ctid_or_name): return _vzctl('destroy', ctid_or_name)
null
null
null
What does the code ensure ?
@py.test.mark.parametrize('item_name', [item.name for item in six._urllib_robotparser_moved_attributes]) def test_move_items_urllib_robotparser(item_name): if (sys.version_info[:2] >= (2, 6)): assert (item_name in dir(six.moves.urllib.robotparser)) getattr(six.moves.urllib.robotparser, item_name)
null
null
null
that everything loads correctly
codeqa
@py test mark parametrize 'item name' [item name for item in six urllib robotparser moved attributes] def test move items urllib robotparser item name if sys version info[ 2] > 2 6 assert item name in dir six moves urllib robotparser getattr six moves urllib robotparser item name
null
null
null
null
Question: What does the code ensure ? Code: @py.test.mark.parametrize('item_name', [item.name for item in six._urllib_robotparser_moved_attributes]) def test_move_items_urllib_robotparser(item_name): if (sys.version_info[:2] >= (2, 6)): assert (item_name in dir(six.moves.urllib.robotparser)) getattr(six.moves.urllib.robotparser, item_name)
null
null
null
How do everything load ?
@py.test.mark.parametrize('item_name', [item.name for item in six._urllib_robotparser_moved_attributes]) def test_move_items_urllib_robotparser(item_name): if (sys.version_info[:2] >= (2, 6)): assert (item_name in dir(six.moves.urllib.robotparser)) getattr(six.moves.urllib.robotparser, item_name)
null
null
null
correctly
codeqa
@py test mark parametrize 'item name' [item name for item in six urllib robotparser moved attributes] def test move items urllib robotparser item name if sys version info[ 2] > 2 6 assert item name in dir six moves urllib robotparser getattr six moves urllib robotparser item name
null
null
null
null
Question: How do everything load ? Code: @py.test.mark.parametrize('item_name', [item.name for item in six._urllib_robotparser_moved_attributes]) def test_move_items_urllib_robotparser(item_name): if (sys.version_info[:2] >= (2, 6)): assert (item_name in dir(six.moves.urllib.robotparser)) getattr(six.moves.urllib.robotparser, item_name)
null
null
null
What does the code provide ?
def _section_membership(course, access, is_white_label): course_key = course.id ccx_enabled = (settings.FEATURES.get('CUSTOM_COURSES_EDX', False) and course.enable_ccx) section_data = {'section_key': 'membership', 'section_display_name': _('Membership'), 'access': access, 'ccx_is_enabled': ccx_enabled, 'is_white_label': is_white_label, 'enroll_button_url': reverse('students_update_enrollment', kwargs={'course_id': unicode(course_key)}), 'unenroll_button_url': reverse('students_update_enrollment', kwargs={'course_id': unicode(course_key)}), 'upload_student_csv_button_url': reverse('register_and_enroll_students', kwargs={'course_id': unicode(course_key)}), 'modify_beta_testers_button_url': reverse('bulk_beta_modify_access', kwargs={'course_id': unicode(course_key)}), 'list_course_role_members_url': reverse('list_course_role_members', kwargs={'course_id': unicode(course_key)}), 'modify_access_url': reverse('modify_access', kwargs={'course_id': unicode(course_key)}), 'list_forum_members_url': reverse('list_forum_members', kwargs={'course_id': unicode(course_key)}), 'update_forum_role_membership_url': reverse('update_forum_role_membership', kwargs={'course_id': unicode(course_key)})} return section_data
null
null
null
data for the corresponding dashboard section
codeqa
def section membership course access is white label course key course idccx enabled settings FEATURES get 'CUSTOM COURSES EDX' False and course enable ccx section data {'section key' 'membership' 'section display name' ' Membership' 'access' access 'ccx is enabled' ccx enabled 'is white label' is white label 'enroll button url' reverse 'students update enrollment' kwargs {'course id' unicode course key } 'unenroll button url' reverse 'students update enrollment' kwargs {'course id' unicode course key } 'upload student csv button url' reverse 'register and enroll students' kwargs {'course id' unicode course key } 'modify beta testers button url' reverse 'bulk beta modify access' kwargs {'course id' unicode course key } 'list course role members url' reverse 'list course role members' kwargs {'course id' unicode course key } 'modify access url' reverse 'modify access' kwargs {'course id' unicode course key } 'list forum members url' reverse 'list forum members' kwargs {'course id' unicode course key } 'update forum role membership url' reverse 'update forum role membership' kwargs {'course id' unicode course key } }return section data
null
null
null
null
Question: What does the code provide ? Code: def _section_membership(course, access, is_white_label): course_key = course.id ccx_enabled = (settings.FEATURES.get('CUSTOM_COURSES_EDX', False) and course.enable_ccx) section_data = {'section_key': 'membership', 'section_display_name': _('Membership'), 'access': access, 'ccx_is_enabled': ccx_enabled, 'is_white_label': is_white_label, 'enroll_button_url': reverse('students_update_enrollment', kwargs={'course_id': unicode(course_key)}), 'unenroll_button_url': reverse('students_update_enrollment', kwargs={'course_id': unicode(course_key)}), 'upload_student_csv_button_url': reverse('register_and_enroll_students', kwargs={'course_id': unicode(course_key)}), 'modify_beta_testers_button_url': reverse('bulk_beta_modify_access', kwargs={'course_id': unicode(course_key)}), 'list_course_role_members_url': reverse('list_course_role_members', kwargs={'course_id': unicode(course_key)}), 'modify_access_url': reverse('modify_access', kwargs={'course_id': unicode(course_key)}), 'list_forum_members_url': reverse('list_forum_members', kwargs={'course_id': unicode(course_key)}), 'update_forum_role_membership_url': reverse('update_forum_role_membership', kwargs={'course_id': unicode(course_key)})} return section_data
null
null
null
What does the code find ?
def log(mat, tiny=0.0, target=None): if (not target): target = mat err_code = _cudamat.apply_log(mat.p_mat, target.p_mat, ct.c_float(tiny)) if err_code: raise generate_exception(err_code) return target
null
null
null
the natural logarithm of each element of the matrix mat
codeqa
def log mat tiny 0 0 target None if not target target materr code cudamat apply log mat p mat target p mat ct c float tiny if err code raise generate exception err code return target
null
null
null
null
Question: What does the code find ? Code: def log(mat, tiny=0.0, target=None): if (not target): target = mat err_code = _cudamat.apply_log(mat.p_mat, target.p_mat, ct.c_float(tiny)) if err_code: raise generate_exception(err_code) return target
null
null
null
How does the code get vector3 ?
def getVector3ByDictionary(dictionary, vector3): if ('x' in dictionary): vector3 = getVector3IfNone(vector3) vector3.x = euclidean.getFloatFromValue(dictionary['x']) if ('y' in dictionary): vector3 = getVector3IfNone(vector3) vector3.y = euclidean.getFloatFromValue(dictionary['y']) if ('z' in dictionary): vector3 = getVector3IfNone(vector3) vector3.z = euclidean.getFloatFromValue(dictionary['z']) return vector3
null
null
null
by dictionary
codeqa
def get Vector 3 By Dictionary dictionary vector 3 if 'x' in dictionary vector 3 get Vector 3 If None vector 3 vector 3 x euclidean get Float From Value dictionary['x'] if 'y' in dictionary vector 3 get Vector 3 If None vector 3 vector 3 y euclidean get Float From Value dictionary['y'] if 'z' in dictionary vector 3 get Vector 3 If None vector 3 vector 3 z euclidean get Float From Value dictionary['z'] return vector 3
null
null
null
null
Question: How does the code get vector3 ? Code: def getVector3ByDictionary(dictionary, vector3): if ('x' in dictionary): vector3 = getVector3IfNone(vector3) vector3.x = euclidean.getFloatFromValue(dictionary['x']) if ('y' in dictionary): vector3 = getVector3IfNone(vector3) vector3.y = euclidean.getFloatFromValue(dictionary['y']) if ('z' in dictionary): vector3 = getVector3IfNone(vector3) vector3.z = euclidean.getFloatFromValue(dictionary['z']) return vector3
null
null
null
What does the code get by dictionary ?
def getVector3ByDictionary(dictionary, vector3): if ('x' in dictionary): vector3 = getVector3IfNone(vector3) vector3.x = euclidean.getFloatFromValue(dictionary['x']) if ('y' in dictionary): vector3 = getVector3IfNone(vector3) vector3.y = euclidean.getFloatFromValue(dictionary['y']) if ('z' in dictionary): vector3 = getVector3IfNone(vector3) vector3.z = euclidean.getFloatFromValue(dictionary['z']) return vector3
null
null
null
vector3
codeqa
def get Vector 3 By Dictionary dictionary vector 3 if 'x' in dictionary vector 3 get Vector 3 If None vector 3 vector 3 x euclidean get Float From Value dictionary['x'] if 'y' in dictionary vector 3 get Vector 3 If None vector 3 vector 3 y euclidean get Float From Value dictionary['y'] if 'z' in dictionary vector 3 get Vector 3 If None vector 3 vector 3 z euclidean get Float From Value dictionary['z'] return vector 3
null
null
null
null
Question: What does the code get by dictionary ? Code: def getVector3ByDictionary(dictionary, vector3): if ('x' in dictionary): vector3 = getVector3IfNone(vector3) vector3.x = euclidean.getFloatFromValue(dictionary['x']) if ('y' in dictionary): vector3 = getVector3IfNone(vector3) vector3.y = euclidean.getFloatFromValue(dictionary['y']) if ('z' in dictionary): vector3 = getVector3IfNone(vector3) vector3.z = euclidean.getFloatFromValue(dictionary['z']) return vector3
null
null
null
How is a storage backend frozen ?
@require_admin_context def is_backend_frozen(context, host, cluster_name): if cluster_name: model = models.Cluster conditions = [(model.name == cluster_name)] else: model = models.Service conditions = [(model.host == host)] conditions.extend(((~ model.deleted), model.frozen)) query = get_session().query(sql.exists().where(and_(*conditions))) frozen = query.scalar() return frozen
null
null
null
based on host and cluster_name
codeqa
@require admin contextdef is backend frozen context host cluster name if cluster name model models Clusterconditions [ model name cluster name ]else model models Serviceconditions [ model host host ]conditions extend ~ model deleted model frozen query get session query sql exists where and *conditions frozen query scalar return frozen
null
null
null
null
Question: How is a storage backend frozen ? Code: @require_admin_context def is_backend_frozen(context, host, cluster_name): if cluster_name: model = models.Cluster conditions = [(model.name == cluster_name)] else: model = models.Service conditions = [(model.host == host)] conditions.extend(((~ model.deleted), model.frozen)) query = get_session().query(sql.exists().where(and_(*conditions))) frozen = query.scalar() return frozen
null
null
null
How does the code launch ?
def preconfigure_instance(session, instance, vdi_ref, network_info): key = str(instance['key_data']) net = netutils.get_injected_network_template(network_info) metadata = instance['metadata'] mount_required = (key or net or metadata) if (not mount_required): return with vdi_attached(session, vdi_ref, read_only=False) as dev: _mounted_processing(dev, key, net, metadata)
null
null
null
as part of spawn
codeqa
def preconfigure instance session instance vdi ref network info key str instance['key data'] net netutils get injected network template network info metadata instance['metadata']mount required key or net or metadata if not mount required returnwith vdi attached session vdi ref read only False as dev mounted processing dev key net metadata
null
null
null
null
Question: How does the code launch ? Code: def preconfigure_instance(session, instance, vdi_ref, network_info): key = str(instance['key_data']) net = netutils.get_injected_network_template(network_info) metadata = instance['metadata'] mount_required = (key or net or metadata) if (not mount_required): return with vdi_attached(session, vdi_ref, read_only=False) as dev: _mounted_processing(dev, key, net, metadata)
null
null
null
When does the code make alterations to the image ?
def preconfigure_instance(session, instance, vdi_ref, network_info): key = str(instance['key_data']) net = netutils.get_injected_network_template(network_info) metadata = instance['metadata'] mount_required = (key or net or metadata) if (not mount_required): return with vdi_attached(session, vdi_ref, read_only=False) as dev: _mounted_processing(dev, key, net, metadata)
null
null
null
before launching as part of spawn
codeqa
def preconfigure instance session instance vdi ref network info key str instance['key data'] net netutils get injected network template network info metadata instance['metadata']mount required key or net or metadata if not mount required returnwith vdi attached session vdi ref read only False as dev mounted processing dev key net metadata
null
null
null
null
Question: When does the code make alterations to the image ? Code: def preconfigure_instance(session, instance, vdi_ref, network_info): key = str(instance['key_data']) net = netutils.get_injected_network_template(network_info) metadata = instance['metadata'] mount_required = (key or net or metadata) if (not mount_required): return with vdi_attached(session, vdi_ref, read_only=False) as dev: _mounted_processing(dev, key, net, metadata)
null
null
null
What does the code make before launching as part of spawn ?
def preconfigure_instance(session, instance, vdi_ref, network_info): key = str(instance['key_data']) net = netutils.get_injected_network_template(network_info) metadata = instance['metadata'] mount_required = (key or net or metadata) if (not mount_required): return with vdi_attached(session, vdi_ref, read_only=False) as dev: _mounted_processing(dev, key, net, metadata)
null
null
null
alterations to the image
codeqa
def preconfigure instance session instance vdi ref network info key str instance['key data'] net netutils get injected network template network info metadata instance['metadata']mount required key or net or metadata if not mount required returnwith vdi attached session vdi ref read only False as dev mounted processing dev key net metadata
null
null
null
null
Question: What does the code make before launching as part of spawn ? Code: def preconfigure_instance(session, instance, vdi_ref, network_info): key = str(instance['key_data']) net = netutils.get_injected_network_template(network_info) metadata = instance['metadata'] mount_required = (key or net or metadata) if (not mount_required): return with vdi_attached(session, vdi_ref, read_only=False) as dev: _mounted_processing(dev, key, net, metadata)
null
null
null
What is specifying that it is being run in an interactive environment ?
def is_interactive(): return _is_interactive
null
null
null
a script
codeqa
def is interactive return is interactive
null
null
null
null
Question: What is specifying that it is being run in an interactive environment ? Code: def is_interactive(): return _is_interactive
null
null
null
What does the code take ?
def returnConnected(server, client): cio = StringIO() sio = StringIO() client.makeConnection(FileWrapper(cio)) server.makeConnection(FileWrapper(sio)) pump = IOPump(client, server, cio, sio) pump.flush() pump.flush() return pump
null
null
null
two protocol instances
codeqa
def return Connected server client cio String IO sio String IO client make Connection File Wrapper cio server make Connection File Wrapper sio pump IO Pump client server cio sio pump flush pump flush return pump
null
null
null
null
Question: What does the code take ? Code: def returnConnected(server, client): cio = StringIO() sio = StringIO() client.makeConnection(FileWrapper(cio)) server.makeConnection(FileWrapper(sio)) pump = IOPump(client, server, cio, sio) pump.flush() pump.flush() return pump
null
null
null
What does the code get from the table ?
@require_context def virtual_interface_get(context, vif_id): vif_ref = _virtual_interface_query(context).filter_by(id=vif_id).first() return vif_ref
null
null
null
a virtual interface
codeqa
@require contextdef virtual interface get context vif id vif ref virtual interface query context filter by id vif id first return vif ref
null
null
null
null
Question: What does the code get from the table ? Code: @require_context def virtual_interface_get(context, vif_id): vif_ref = _virtual_interface_query(context).filter_by(id=vif_id).first() return vif_ref
null
null
null
What detects in the text ?
def sentiment_text(text): language_client = language.Client() document = language_client.document_from_text(text) sentiment = document.analyze_sentiment() print 'Score: {}'.format(sentiment.score) print 'Magnitude: {}'.format(sentiment.magnitude)
null
null
null
sentiment
codeqa
def sentiment text text language client language Client document language client document from text text sentiment document analyze sentiment print ' Score {}' format sentiment score print ' Magnitude {}' format sentiment magnitude
null
null
null
null
Question: What detects in the text ? Code: def sentiment_text(text): language_client = language.Client() document = language_client.document_from_text(text) sentiment = document.analyze_sentiment() print 'Score: {}'.format(sentiment.score) print 'Magnitude: {}'.format(sentiment.magnitude)
null
null
null
Where does sentiment detect ?
def sentiment_text(text): language_client = language.Client() document = language_client.document_from_text(text) sentiment = document.analyze_sentiment() print 'Score: {}'.format(sentiment.score) print 'Magnitude: {}'.format(sentiment.magnitude)
null
null
null
in the text
codeqa
def sentiment text text language client language Client document language client document from text text sentiment document analyze sentiment print ' Score {}' format sentiment score print ' Magnitude {}' format sentiment magnitude
null
null
null
null
Question: Where does sentiment detect ? Code: def sentiment_text(text): language_client = language.Client() document = language_client.document_from_text(text) sentiment = document.analyze_sentiment() print 'Score: {}'.format(sentiment.score) print 'Magnitude: {}'.format(sentiment.magnitude)
null
null
null
What do functional test validate ?
def test_import_submodule_global_unshadowed(pyi_builder): pyi_builder.test_source('\n # Assert that this submodule is unshadowed by this global variable.\n import sys\n from pyi_testmod_submodule_global_unshadowed import submodule\n assert type(submodule) == type(sys)\n ')
null
null
null
issue # 1919
codeqa
def test import submodule global unshadowed pyi builder pyi builder test source '\n# Assertthatthissubmoduleisunshadowedbythisglobalvariable \nimportsys\nfrompyi testmod submodule global unshadowedimportsubmodule\nasserttype submodule type sys \n'
null
null
null
null
Question: What do functional test validate ? Code: def test_import_submodule_global_unshadowed(pyi_builder): pyi_builder.test_source('\n # Assert that this submodule is unshadowed by this global variable.\n import sys\n from pyi_testmod_submodule_global_unshadowed import submodule\n assert type(submodule) == type(sys)\n ')
null
null
null
What is validating issue # 1919 ?
def test_import_submodule_global_unshadowed(pyi_builder): pyi_builder.test_source('\n # Assert that this submodule is unshadowed by this global variable.\n import sys\n from pyi_testmod_submodule_global_unshadowed import submodule\n assert type(submodule) == type(sys)\n ')
null
null
null
functional test
codeqa
def test import submodule global unshadowed pyi builder pyi builder test source '\n# Assertthatthissubmoduleisunshadowedbythisglobalvariable \nimportsys\nfrompyi testmod submodule global unshadowedimportsubmodule\nasserttype submodule type sys \n'
null
null
null
null
Question: What is validating issue # 1919 ? Code: def test_import_submodule_global_unshadowed(pyi_builder): pyi_builder.test_source('\n # Assert that this submodule is unshadowed by this global variable.\n import sys\n from pyi_testmod_submodule_global_unshadowed import submodule\n assert type(submodule) == type(sys)\n ')
null
null
null
What contains test cases ?
def isTestCase(obj): try: return issubclass(obj, pyunit.TestCase) except TypeError: return False
null
null
null
a class
codeqa
def is Test Case obj try return issubclass obj pyunit Test Case except Type Error return False
null
null
null
null
Question: What contains test cases ? Code: def isTestCase(obj): try: return issubclass(obj, pyunit.TestCase) except TypeError: return False
null
null
null
What does a class contain ?
def isTestCase(obj): try: return issubclass(obj, pyunit.TestCase) except TypeError: return False
null
null
null
test cases
codeqa
def is Test Case obj try return issubclass obj pyunit Test Case except Type Error return False
null
null
null
null
Question: What does a class contain ? Code: def isTestCase(obj): try: return issubclass(obj, pyunit.TestCase) except TypeError: return False
null
null
null
What does the code capitalize ?
def dashCapitalize(s): return '-'.join([x.capitalize() for x in s.split('-')])
null
null
null
a string
codeqa
def dash Capitalize s return '-' join [x capitalize for x in s split '-' ]
null
null
null
null
Question: What does the code capitalize ? Code: def dashCapitalize(s): return '-'.join([x.capitalize() for x in s.split('-')])
null
null
null
Where do approved revisions watch approved revisions ?
@require_POST @login_required def watch_approved(request, product=None): if (request.LANGUAGE_CODE not in settings.SUMO_LANGUAGES): raise Http404 kwargs = {'locale': request.LANGUAGE_CODE} if (product is not None): kwargs['product'] = product ApproveRevisionInLocaleEvent.notify(request.user, **kwargs) statsd.incr('wiki.watches.approved') return HttpResponse()
null
null
null
in a
codeqa
@require POST@login requireddef watch approved request product None if request LANGUAGE CODE not in settings SUMO LANGUAGES raise Http 404 kwargs {'locale' request LANGUAGE CODE}if product is not None kwargs['product'] product Approve Revision In Locale Event notify request user **kwargs statsd incr 'wiki watches approved' return Http Response
null
null
null
null
Question: Where do approved revisions watch approved revisions ? Code: @require_POST @login_required def watch_approved(request, product=None): if (request.LANGUAGE_CODE not in settings.SUMO_LANGUAGES): raise Http404 kwargs = {'locale': request.LANGUAGE_CODE} if (product is not None): kwargs['product'] = product ApproveRevisionInLocaleEvent.notify(request.user, **kwargs) statsd.incr('wiki.watches.approved') return HttpResponse()
null
null
null
What is watching approved revisions in a ?
@require_POST @login_required def watch_approved(request, product=None): if (request.LANGUAGE_CODE not in settings.SUMO_LANGUAGES): raise Http404 kwargs = {'locale': request.LANGUAGE_CODE} if (product is not None): kwargs['product'] = product ApproveRevisionInLocaleEvent.notify(request.user, **kwargs) statsd.incr('wiki.watches.approved') return HttpResponse()
null
null
null
approved revisions
codeqa
@require POST@login requireddef watch approved request product None if request LANGUAGE CODE not in settings SUMO LANGUAGES raise Http 404 kwargs {'locale' request LANGUAGE CODE}if product is not None kwargs['product'] product Approve Revision In Locale Event notify request user **kwargs statsd incr 'wiki watches approved' return Http Response
null
null
null
null
Question: What is watching approved revisions in a ? Code: @require_POST @login_required def watch_approved(request, product=None): if (request.LANGUAGE_CODE not in settings.SUMO_LANGUAGES): raise Http404 kwargs = {'locale': request.LANGUAGE_CODE} if (product is not None): kwargs['product'] = product ApproveRevisionInLocaleEvent.notify(request.user, **kwargs) statsd.incr('wiki.watches.approved') return HttpResponse()
null
null
null
What do approved revisions watch in a ?
@require_POST @login_required def watch_approved(request, product=None): if (request.LANGUAGE_CODE not in settings.SUMO_LANGUAGES): raise Http404 kwargs = {'locale': request.LANGUAGE_CODE} if (product is not None): kwargs['product'] = product ApproveRevisionInLocaleEvent.notify(request.user, **kwargs) statsd.incr('wiki.watches.approved') return HttpResponse()
null
null
null
approved revisions
codeqa
@require POST@login requireddef watch approved request product None if request LANGUAGE CODE not in settings SUMO LANGUAGES raise Http 404 kwargs {'locale' request LANGUAGE CODE}if product is not None kwargs['product'] product Approve Revision In Locale Event notify request user **kwargs statsd incr 'wiki watches approved' return Http Response
null
null
null
null
Question: What do approved revisions watch in a ? Code: @require_POST @login_required def watch_approved(request, product=None): if (request.LANGUAGE_CODE not in settings.SUMO_LANGUAGES): raise Http404 kwargs = {'locale': request.LANGUAGE_CODE} if (product is not None): kwargs['product'] = product ApproveRevisionInLocaleEvent.notify(request.user, **kwargs) statsd.incr('wiki.watches.approved') return HttpResponse()
null
null
null
For what purpose does the code replace contents with xxx ?
def mute_string(text): start = (text.index(text[(-1)]) + 1) end = (len(text) - 1) if (text[(-3):] in ('"""', "'''")): start += 2 end -= 2 return ((text[:start] + ('x' * (end - start))) + text[end:])
null
null
null
to prevent syntax matching
codeqa
def mute string text start text index text[ -1 ] + 1 end len text - 1 if text[ -3 ] in '"""' "'''" start + 2end - 2return text[ start] + 'x' * end - start + text[end ]
null
null
null
null
Question: For what purpose does the code replace contents with xxx ? Code: def mute_string(text): start = (text.index(text[(-1)]) + 1) end = (len(text) - 1) if (text[(-3):] in ('"""', "'''")): start += 2 end -= 2 return ((text[:start] + ('x' * (end - start))) + text[end:])
null
null
null
How does the code replace contents to prevent syntax matching ?
def mute_string(text): start = (text.index(text[(-1)]) + 1) end = (len(text) - 1) if (text[(-3):] in ('"""', "'''")): start += 2 end -= 2 return ((text[:start] + ('x' * (end - start))) + text[end:])
null
null
null
with xxx
codeqa
def mute string text start text index text[ -1 ] + 1 end len text - 1 if text[ -3 ] in '"""' "'''" start + 2end - 2return text[ start] + 'x' * end - start + text[end ]
null
null
null
null
Question: How does the code replace contents to prevent syntax matching ? Code: def mute_string(text): start = (text.index(text[(-1)]) + 1) end = (len(text) - 1) if (text[(-3):] in ('"""', "'''")): start += 2 end -= 2 return ((text[:start] + ('x' * (end - start))) + text[end:])
null
null
null
What does the code replace with xxx to prevent syntax matching ?
def mute_string(text): start = (text.index(text[(-1)]) + 1) end = (len(text) - 1) if (text[(-3):] in ('"""', "'''")): start += 2 end -= 2 return ((text[:start] + ('x' * (end - start))) + text[end:])
null
null
null
contents
codeqa
def mute string text start text index text[ -1 ] + 1 end len text - 1 if text[ -3 ] in '"""' "'''" start + 2end - 2return text[ start] + 'x' * end - start + text[end ]
null
null
null
null
Question: What does the code replace with xxx to prevent syntax matching ? Code: def mute_string(text): start = (text.index(text[(-1)]) + 1) end = (len(text) - 1) if (text[(-3):] in ('"""', "'''")): start += 2 end -= 2 return ((text[:start] + ('x' * (end - start))) + text[end:])
null
null
null
What does the code convert to a raw string ?
def long2raw(value, endian, size=None): assert (((not size) and (0 < value)) or (0 <= value)) assert (endian in (LITTLE_ENDIAN, BIG_ENDIAN)) text = [] while ((value != 0) or (text == '')): byte = (value % 256) text.append(chr(byte)) value >>= 8 if size: need = max((size - len(text)), 0) else: need = 0 if need: if (endian is BIG_ENDIAN): text = chain(repeat('\x00', need), reversed(text)) else: text = chain(text, repeat('\x00', need)) elif (endian is BIG_ENDIAN): text = reversed(text) return ''.join(text)
null
null
null
a number
codeqa
def long 2 raw value endian size None assert not size and 0 < value or 0 < value assert endian in LITTLE ENDIAN BIG ENDIAN text []while value 0 or text '' byte value % 256 text append chr byte value >> 8if size need max size - len text 0 else need 0if need if endian is BIG ENDIAN text chain repeat '\x 00 ' need reversed text else text chain text repeat '\x 00 ' need elif endian is BIG ENDIAN text reversed text return '' join text
null
null
null
null
Question: What does the code convert to a raw string ? Code: def long2raw(value, endian, size=None): assert (((not size) and (0 < value)) or (0 <= value)) assert (endian in (LITTLE_ENDIAN, BIG_ENDIAN)) text = [] while ((value != 0) or (text == '')): byte = (value % 256) text.append(chr(byte)) value >>= 8 if size: need = max((size - len(text)), 0) else: need = 0 if need: if (endian is BIG_ENDIAN): text = chain(repeat('\x00', need), reversed(text)) else: text = chain(text, repeat('\x00', need)) elif (endian is BIG_ENDIAN): text = reversed(text) return ''.join(text)
null
null
null
What does the code clear from the requestor ?
def ClearUserInfoCookie(cookie_name=COOKIE_NAME): set_cookie = Cookie.SimpleCookie() set_cookie[cookie_name] = '' set_cookie[cookie_name]['path'] = '/' set_cookie[cookie_name]['max-age'] = '0' return ('%s\r\n' % set_cookie)
null
null
null
the user info cookie
codeqa
def Clear User Info Cookie cookie name COOKIE NAME set cookie Cookie Simple Cookie set cookie[cookie name] ''set cookie[cookie name]['path'] '/'set cookie[cookie name]['max-age'] '0 'return '%s\r\n' % set cookie
null
null
null
null
Question: What does the code clear from the requestor ? Code: def ClearUserInfoCookie(cookie_name=COOKIE_NAME): set_cookie = Cookie.SimpleCookie() set_cookie[cookie_name] = '' set_cookie[cookie_name]['path'] = '/' set_cookie[cookie_name]['max-age'] = '0' return ('%s\r\n' % set_cookie)
null
null
null
What does the code consider as vectors ?
def sorensen_coefficient(X, Y): if (X is Y): X = Y = np.asanyarray(X) else: X = np.asanyarray(X) Y = np.asanyarray(Y) XY = [] i = 0 for arrayX in X: XY.append([]) for arrayY in Y: XY[i].append(((2 * np.intersect1d(arrayX, arrayY).size) / float((len(arrayX) + len(arrayY))))) XY[i] = np.array(XY[i]) i += 1 XY = np.array(XY) return XY
null
null
null
the rows of x
codeqa
def sorensen coefficient X Y if X is Y X Y np asanyarray X else X np asanyarray X Y np asanyarray Y XY []i 0for array X in X XY append [] for array Y in Y XY[i] append 2 * np intersect 1 d array X array Y size / float len array X + len array Y XY[i] np array XY[i] i + 1XY np array XY return XY
null
null
null
null
Question: What does the code consider as vectors ? Code: def sorensen_coefficient(X, Y): if (X is Y): X = Y = np.asanyarray(X) else: X = np.asanyarray(X) Y = np.asanyarray(Y) XY = [] i = 0 for arrayX in X: XY.append([]) for arrayY in Y: XY[i].append(((2 * np.intersect1d(arrayX, arrayY).size) / float((len(arrayX) + len(arrayY))))) XY[i] = np.array(XY[i]) i += 1 XY = np.array(XY) return XY
null
null
null
What does this string have in it ?
def isMultiline(s): return (string.find(s, '\n') != (-1))
null
null
null
a newline
codeqa
def is Multiline s return string find s '\n' -1
null
null
null
null
Question: What does this string have in it ? Code: def isMultiline(s): return (string.find(s, '\n') != (-1))
null
null
null
What has a newline in it ?
def isMultiline(s): return (string.find(s, '\n') != (-1))
null
null
null
this string
codeqa
def is Multiline s return string find s '\n' -1
null
null
null
null
Question: What has a newline in it ? Code: def isMultiline(s): return (string.find(s, '\n') != (-1))
null
null
null
Where does this string have a newline ?
def isMultiline(s): return (string.find(s, '\n') != (-1))
null
null
null
in it
codeqa
def is Multiline s return string find s '\n' -1
null
null
null
null
Question: Where does this string have a newline ? Code: def isMultiline(s): return (string.find(s, '\n') != (-1))
null
null
null
What does the code add to the lists ?
def addElementToListTableIfNotThere(element, key, listTable): if (key in listTable): elements = listTable[key] if (element not in elements): elements.append(element) else: listTable[key] = [element]
null
null
null
the value
codeqa
def add Element To List Table If Not There element key list Table if key in list Table elements list Table[key]if element not in elements elements append element else list Table[key] [element]
null
null
null
null
Question: What does the code add to the lists ? Code: def addElementToListTableIfNotThere(element, key, listTable): if (key in listTable): elements = listTable[key] if (element not in elements): elements.append(element) else: listTable[key] = [element]
null
null
null
In which direction is the user logged ?
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME): actual_decorator = user_passes_test((lambda u: u.is_authenticated()), redirect_field_name=redirect_field_name) if function: return actual_decorator(function) return actual_decorator
null
null
null
in
codeqa
def login required function None redirect field name REDIRECT FIELD NAME actual decorator user passes test lambda u u is authenticated redirect field name redirect field name if function return actual decorator function return actual decorator
null
null
null
null
Question: In which direction is the user logged ? Code: def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME): actual_decorator = user_passes_test((lambda u: u.is_authenticated()), redirect_field_name=redirect_field_name) if function: return actual_decorator(function) return actual_decorator
null
null
null
What does decorator for views check ?
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME): actual_decorator = user_passes_test((lambda u: u.is_authenticated()), redirect_field_name=redirect_field_name) if function: return actual_decorator(function) return actual_decorator
null
null
null
that the user is logged in
codeqa
def login required function None redirect field name REDIRECT FIELD NAME actual decorator user passes test lambda u u is authenticated redirect field name redirect field name if function return actual decorator function return actual decorator
null
null
null
null
Question: What does decorator for views check ? Code: def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME): actual_decorator = user_passes_test((lambda u: u.is_authenticated()), redirect_field_name=redirect_field_name) if function: return actual_decorator(function) return actual_decorator
null
null
null
What checks that the user is logged in ?
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME): actual_decorator = user_passes_test((lambda u: u.is_authenticated()), redirect_field_name=redirect_field_name) if function: return actual_decorator(function) return actual_decorator
null
null
null
decorator for views
codeqa
def login required function None redirect field name REDIRECT FIELD NAME actual decorator user passes test lambda u u is authenticated redirect field name redirect field name if function return actual decorator function return actual decorator
null
null
null
null
Question: What checks that the user is logged in ? Code: def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME): actual_decorator = user_passes_test((lambda u: u.is_authenticated()), redirect_field_name=redirect_field_name) if function: return actual_decorator(function) return actual_decorator
null
null
null
What does the code check against the value computed from the rest of the contents ?
def verify_signature(message, secret): old_sig = message.get('message_signature') new_sig = compute_signature(message, secret) return (new_sig == old_sig)
null
null
null
the signature in the message
codeqa
def verify signature message secret old sig message get 'message signature' new sig compute signature message secret return new sig old sig
null
null
null
null
Question: What does the code check against the value computed from the rest of the contents ? Code: def verify_signature(message, secret): old_sig = message.get('message_signature') new_sig = compute_signature(message, secret) return (new_sig == old_sig)
null
null
null
When do the same file use for rules ?
def _conf(family='ip'): if (__grains__['os_family'] == 'RedHat'): return '/etc/nftables' elif (__grains__['os_family'] == 'Arch'): return '/etc/nftables' elif (__grains__['os_family'] == 'Debian'): return '/etc/nftables' elif (__grains__['os'] == 'Gentoo'): return '/etc/nftables' else: return False
null
null
null
for now
codeqa
def conf family 'ip' if grains ['os family'] ' Red Hat' return '/etc/nftables'elif grains ['os family'] ' Arch' return '/etc/nftables'elif grains ['os family'] ' Debian' return '/etc/nftables'elif grains ['os'] ' Gentoo' return '/etc/nftables'else return False
null
null
null
null
Question: When do the same file use for rules ? Code: def _conf(family='ip'): if (__grains__['os_family'] == 'RedHat'): return '/etc/nftables' elif (__grains__['os_family'] == 'Arch'): return '/etc/nftables' elif (__grains__['os_family'] == 'Debian'): return '/etc/nftables' elif (__grains__['os'] == 'Gentoo'): return '/etc/nftables' else: return False
null
null
null
What does the code delete ?
def delete_doc(doctype=None, name=None, force=0, ignore_doctypes=None, for_reload=False, ignore_permissions=False, flags=None): import frappe.model.delete_doc frappe.model.delete_doc.delete_doc(doctype, name, force, ignore_doctypes, for_reload, ignore_permissions, flags)
null
null
null
a document
codeqa
def delete doc doctype None name None force 0 ignore doctypes None for reload False ignore permissions False flags None import frappe model delete docfrappe model delete doc delete doc doctype name force ignore doctypes for reload ignore permissions flags
null
null
null
null
Question: What does the code delete ? Code: def delete_doc(doctype=None, name=None, force=0, ignore_doctypes=None, for_reload=False, ignore_permissions=False, flags=None): import frappe.model.delete_doc frappe.model.delete_doc.delete_doc(doctype, name, force, ignore_doctypes, for_reload, ignore_permissions, flags)
null
null
null
By how much do a 10-dimensional unit vector return ?
def vectorized_result(j): e = np.zeros((10, 1)) e[j] = 1.0 return e
null
null
null
with a 1
codeqa
def vectorized result j e np zeros 10 1 e[j] 1 0return e
null
null
null
null
Question: By how much do a 10-dimensional unit vector return ? Code: def vectorized_result(j): e = np.zeros((10, 1)) e[j] = 1.0 return e
null
null
null
What does the code destroy if it does not exist ?
@_get_client def image_destroy(client, image_id): return client.image_destroy(image_id=image_id)
null
null
null
the image
codeqa
@ get clientdef image destroy client image id return client image destroy image id image id
null
null
null
null
Question: What does the code destroy if it does not exist ? Code: @_get_client def image_destroy(client, image_id): return client.image_destroy(image_id=image_id)
null
null
null
What does the code create ?
@utils.no_4byte_params def metadef_namespace_create(context, values, session=None): session = (session or get_session()) return metadef_namespace_api.create(context, values, session)
null
null
null
a namespace
codeqa
@utils no 4byte paramsdef metadef namespace create context values session None session session or get session return metadef namespace api create context values session
null
null
null
null
Question: What does the code create ? Code: @utils.no_4byte_params def metadef_namespace_create(context, values, session=None): session = (session or get_session()) return metadef_namespace_api.create(context, values, session)
null
null
null
How has setting values been converted to a dict back to a string ?
def _normalize_server_settings(**settings): ret = dict() settings = salt.utils.clean_kwargs(**settings) for setting in settings: if isinstance(settings[setting], dict): value_from_key = next(six.iterkeys(settings[setting])) ret[setting] = '{{{0}}}'.format(value_from_key) else: ret[setting] = settings[setting] return ret
null
null
null
improperly
codeqa
def normalize server settings **settings ret dict settings salt utils clean kwargs **settings for setting in settings if isinstance settings[setting] dict value from key next six iterkeys settings[setting] ret[setting] '{{{ 0 }}}' format value from key else ret[setting] settings[setting]return ret
null
null
null
null
Question: How has setting values been converted to a dict back to a string ? Code: def _normalize_server_settings(**settings): ret = dict() settings = salt.utils.clean_kwargs(**settings) for setting in settings: if isinstance(settings[setting], dict): value_from_key = next(six.iterkeys(settings[setting])) ret[setting] = '{{{0}}}'.format(value_from_key) else: ret[setting] = settings[setting] return ret
null
null
null
What does the code get ?
def getTetragridCopy(tetragrid): if (tetragrid == None): return None tetragridCopy = [] for tetragridRow in tetragrid: tetragridCopy.append(tetragridRow[:]) return tetragridCopy
null
null
null
tetragrid copy
codeqa
def get Tetragrid Copy tetragrid if tetragrid None return Nonetetragrid Copy []for tetragrid Row in tetragrid tetragrid Copy append tetragrid Row[ ] return tetragrid Copy
null
null
null
null
Question: What does the code get ? Code: def getTetragridCopy(tetragrid): if (tetragrid == None): return None tetragridCopy = [] for tetragridRow in tetragrid: tetragridCopy.append(tetragridRow[:]) return tetragridCopy
null
null
null
How do on data compute then ?
@dispatch(Head, (box(bcolz.ctable), box(bcolz.carray))) def compute_down(expr, data, **kwargs): leaf = expr._leaves()[0] if all((isinstance(e, Cheap) for e in path(expr, leaf))): val = data.value return compute(expr, {leaf: into(Iterator, val)}, return_type='native', **kwargs) else: raise MDNotImplementedError()
null
null
null
directly
codeqa
@dispatch Head box bcolz ctable box bcolz carray def compute down expr data **kwargs leaf expr leaves [0 ]if all isinstance e Cheap for e in path expr leaf val data valuereturn compute expr {leaf into Iterator val } return type 'native' **kwargs else raise MD Not Implemented Error
null
null
null
null
Question: How do on data compute then ? Code: @dispatch(Head, (box(bcolz.ctable), box(bcolz.carray))) def compute_down(expr, data, **kwargs): leaf = expr._leaves()[0] if all((isinstance(e, Cheap) for e in path(expr, leaf))): val = data.value return compute(expr, {leaf: into(Iterator, val)}, return_type='native', **kwargs) else: raise MDNotImplementedError()
null
null
null
Who d compute to a specified relative precision using random sampling ?
def iddp_aid(eps, A): A = np.asfortranarray(A) (m, n) = A.shape (n2, w) = idd_frmi(m) proj = np.empty((((n * ((2 * n2) + 1)) + n2) + 1), order='F') (k, idx, proj) = _id.iddp_aid(eps, A, w, proj) proj = proj[:(k * (n - k))].reshape((k, (n - k)), order='F') return (k, idx, proj)
null
null
null
i d of a real matrix
codeqa
def iddp aid eps A A np asfortranarray A m n A shape n2 w idd frmi m proj np empty n * 2 * n2 + 1 + n2 + 1 order 'F' k idx proj id iddp aid eps A w proj proj proj[ k * n - k ] reshape k n - k order 'F' return k idx proj
null
null
null
null
Question: Who d compute to a specified relative precision using random sampling ? Code: def iddp_aid(eps, A): A = np.asfortranarray(A) (m, n) = A.shape (n2, w) = idd_frmi(m) proj = np.empty((((n * ((2 * n2) + 1)) + n2) + 1), order='F') (k, idx, proj) = _id.iddp_aid(eps, A, w, proj) proj = proj[:(k * (n - k))].reshape((k, (n - k)), order='F') return (k, idx, proj)
null
null
null
How d i d of a real matrix compute to a specified relative precision ?
def iddp_aid(eps, A): A = np.asfortranarray(A) (m, n) = A.shape (n2, w) = idd_frmi(m) proj = np.empty((((n * ((2 * n2) + 1)) + n2) + 1), order='F') (k, idx, proj) = _id.iddp_aid(eps, A, w, proj) proj = proj[:(k * (n - k))].reshape((k, (n - k)), order='F') return (k, idx, proj)
null
null
null
using random sampling
codeqa
def iddp aid eps A A np asfortranarray A m n A shape n2 w idd frmi m proj np empty n * 2 * n2 + 1 + n2 + 1 order 'F' k idx proj id iddp aid eps A w proj proj proj[ k * n - k ] reshape k n - k order 'F' return k idx proj
null
null
null
null
Question: How d i d of a real matrix compute to a specified relative precision ? Code: def iddp_aid(eps, A): A = np.asfortranarray(A) (m, n) = A.shape (n2, w) = idd_frmi(m) proj = np.empty((((n * ((2 * n2) + 1)) + n2) + 1), order='F') (k, idx, proj) = _id.iddp_aid(eps, A, w, proj) proj = proj[:(k * (n - k))].reshape((k, (n - k)), order='F') return (k, idx, proj)
null
null
null
What d i d of a real matrix compute using random sampling ?
def iddp_aid(eps, A): A = np.asfortranarray(A) (m, n) = A.shape (n2, w) = idd_frmi(m) proj = np.empty((((n * ((2 * n2) + 1)) + n2) + 1), order='F') (k, idx, proj) = _id.iddp_aid(eps, A, w, proj) proj = proj[:(k * (n - k))].reshape((k, (n - k)), order='F') return (k, idx, proj)
null
null
null
to a specified relative precision
codeqa
def iddp aid eps A A np asfortranarray A m n A shape n2 w idd frmi m proj np empty n * 2 * n2 + 1 + n2 + 1 order 'F' k idx proj id iddp aid eps A w proj proj proj[ k * n - k ] reshape k n - k order 'F' return k idx proj
null
null
null
null
Question: What d i d of a real matrix compute using random sampling ? Code: def iddp_aid(eps, A): A = np.asfortranarray(A) (m, n) = A.shape (n2, w) = idd_frmi(m) proj = np.empty((((n * ((2 * n2) + 1)) + n2) + 1), order='F') (k, idx, proj) = _id.iddp_aid(eps, A, w, proj) proj = proj[:(k * (n - k))].reshape((k, (n - k)), order='F') return (k, idx, proj)
null
null
null
What does the code get ?
def getDescriptionCarve(lines): descriptionCarve = '' layerThicknessString = getSettingString(lines, 'carve', 'Layer Height') if (layerThicknessString != None): descriptionCarve += (layerThicknessString.replace('.', '') + 'h') edgeWidthString = getSettingString(lines, 'carve', 'Edge Width over Height') if (edgeWidthString != None): descriptionCarve += ('x%sw' % str((float(edgeWidthString) * float(layerThicknessString))).replace('.', '')) return descriptionCarve
null
null
null
the description for carve
codeqa
def get Description Carve lines description Carve ''layer Thickness String get Setting String lines 'carve' ' Layer Height' if layer Thickness String None description Carve + layer Thickness String replace ' ' '' + 'h' edge Width String get Setting String lines 'carve' ' Edge Widthover Height' if edge Width String None description Carve + 'x%sw' % str float edge Width String * float layer Thickness String replace ' ' '' return description Carve
null
null
null
null
Question: What does the code get ? Code: def getDescriptionCarve(lines): descriptionCarve = '' layerThicknessString = getSettingString(lines, 'carve', 'Layer Height') if (layerThicknessString != None): descriptionCarve += (layerThicknessString.replace('.', '') + 'h') edgeWidthString = getSettingString(lines, 'carve', 'Edge Width over Height') if (edgeWidthString != None): descriptionCarve += ('x%sw' % str((float(edgeWidthString) * float(layerThicknessString))).replace('.', '')) return descriptionCarve
null
null
null
When do we be in ?
def inspect_stack(): return {'co_name': inspect.stack()[1][3]}
null
null
null
currently
codeqa
def inspect stack return {'co name' inspect stack [1 ][ 3 ]}
null
null
null
null
Question: When do we be in ? Code: def inspect_stack(): return {'co_name': inspect.stack()[1][3]}
null
null
null
What wraps a function in a try:/except ?
def callWithLogger(logger, func, *args, **kw): try: lp = logger.logPrefix() except KeyboardInterrupt: raise except: lp = '(buggy logPrefix method)' err(system=lp) try: return callWithContext({'system': lp}, func, *args, **kw) except KeyboardInterrupt: raise except: err(system=lp)
null
null
null
utility method
codeqa
def call With Logger logger func *args **kw try lp logger log Prefix except Keyboard Interrupt raiseexcept lp ' buggylog Prefixmethod 'err system lp try return call With Context {'system' lp} func *args **kw except Keyboard Interrupt raiseexcept err system lp
null
null
null
null
Question: What wraps a function in a try:/except ? Code: def callWithLogger(logger, func, *args, **kw): try: lp = logger.logPrefix() except KeyboardInterrupt: raise except: lp = '(buggy logPrefix method)' err(system=lp) try: return callWithContext({'system': lp}, func, *args, **kw) except KeyboardInterrupt: raise except: err(system=lp)
null
null
null
What matches the default orientation ?
@cleanup def test__EventCollection__is_horizontal(): (_, coll, _) = generate_EventCollection_plot() assert_equal(True, coll.is_horizontal())
null
null
null
the input orientation
codeqa
@cleanupdef test Event Collection is horizontal coll generate Event Collection plot assert equal True coll is horizontal
null
null
null
null
Question: What matches the default orientation ? Code: @cleanup def test__EventCollection__is_horizontal(): (_, coll, _) = generate_EventCollection_plot() assert_equal(True, coll.is_horizontal())
null
null
null
What does the input orientation match ?
@cleanup def test__EventCollection__is_horizontal(): (_, coll, _) = generate_EventCollection_plot() assert_equal(True, coll.is_horizontal())
null
null
null
the default orientation
codeqa
@cleanupdef test Event Collection is horizontal coll generate Event Collection plot assert equal True coll is horizontal
null
null
null
null
Question: What does the input orientation match ? Code: @cleanup def test__EventCollection__is_horizontal(): (_, coll, _) = generate_EventCollection_plot() assert_equal(True, coll.is_horizontal())
null
null
null
What checks the ?
def file_upload_getlist_count(request): file_counts = {} for key in request.FILES.keys(): file_counts[key] = len(request.FILES.getlist(key)) return HttpResponse(json.dumps(file_counts))
null
null
null
code
codeqa
def file upload getlist count request file counts {}for key in request FILES keys file counts[key] len request FILES getlist key return Http Response json dumps file counts
null
null
null
null
Question: What checks the ? Code: def file_upload_getlist_count(request): file_counts = {} for key in request.FILES.keys(): file_counts[key] = len(request.FILES.getlist(key)) return HttpResponse(json.dumps(file_counts))
null
null
null
What do code check ?
def file_upload_getlist_count(request): file_counts = {} for key in request.FILES.keys(): file_counts[key] = len(request.FILES.getlist(key)) return HttpResponse(json.dumps(file_counts))
null
null
null
the
codeqa
def file upload getlist count request file counts {}for key in request FILES keys file counts[key] len request FILES getlist key return Http Response json dumps file counts
null
null
null
null
Question: What do code check ? Code: def file_upload_getlist_count(request): file_counts = {} for key in request.FILES.keys(): file_counts[key] = len(request.FILES.getlist(key)) return HttpResponse(json.dumps(file_counts))
null
null
null
What do generic z - test save ?
def _zstat_generic2(value, std_diff, alternative): zstat = (value / std_diff) if (alternative in ['two-sided', '2-sided', '2s']): pvalue = (stats.norm.sf(np.abs(zstat)) * 2) elif (alternative in ['larger', 'l']): pvalue = stats.norm.sf(zstat) elif (alternative in ['smaller', 's']): pvalue = stats.norm.cdf(zstat) else: raise ValueError('invalid alternative') return (zstat, pvalue)
null
null
null
typing
codeqa
def zstat generic 2 value std diff alternative zstat value / std diff if alternative in ['two-sided' '2 -sided' '2 s'] pvalue stats norm sf np abs zstat * 2 elif alternative in ['larger' 'l'] pvalue stats norm sf zstat elif alternative in ['smaller' 's'] pvalue stats norm cdf zstat else raise Value Error 'invalidalternative' return zstat pvalue
null
null
null
null
Question: What do generic z - test save ? Code: def _zstat_generic2(value, std_diff, alternative): zstat = (value / std_diff) if (alternative in ['two-sided', '2-sided', '2s']): pvalue = (stats.norm.sf(np.abs(zstat)) * 2) elif (alternative in ['larger', 'l']): pvalue = stats.norm.sf(zstat) elif (alternative in ['smaller', 's']): pvalue = stats.norm.cdf(zstat) else: raise ValueError('invalid alternative') return (zstat, pvalue)
null
null
null
What saves typing ?
def _zstat_generic2(value, std_diff, alternative): zstat = (value / std_diff) if (alternative in ['two-sided', '2-sided', '2s']): pvalue = (stats.norm.sf(np.abs(zstat)) * 2) elif (alternative in ['larger', 'l']): pvalue = stats.norm.sf(zstat) elif (alternative in ['smaller', 's']): pvalue = stats.norm.cdf(zstat) else: raise ValueError('invalid alternative') return (zstat, pvalue)
null
null
null
generic z - test
codeqa
def zstat generic 2 value std diff alternative zstat value / std diff if alternative in ['two-sided' '2 -sided' '2 s'] pvalue stats norm sf np abs zstat * 2 elif alternative in ['larger' 'l'] pvalue stats norm sf zstat elif alternative in ['smaller' 's'] pvalue stats norm cdf zstat else raise Value Error 'invalidalternative' return zstat pvalue
null
null
null
null
Question: What saves typing ? Code: def _zstat_generic2(value, std_diff, alternative): zstat = (value / std_diff) if (alternative in ['two-sided', '2-sided', '2s']): pvalue = (stats.norm.sf(np.abs(zstat)) * 2) elif (alternative in ['larger', 'l']): pvalue = stats.norm.sf(zstat) elif (alternative in ['smaller', 's']): pvalue = stats.norm.cdf(zstat) else: raise ValueError('invalid alternative') return (zstat, pvalue)
null
null
null
How do over the given iterator iterate ?
def coiterate(iterator): return _theCooperator.coiterate(iterator)
null
null
null
cooperatively
codeqa
def coiterate iterator return the Cooperator coiterate iterator
null
null
null
null
Question: How do over the given iterator iterate ? Code: def coiterate(iterator): return _theCooperator.coiterate(iterator)
null
null
null
What is setting a value ?
def set_(*args, **kwargs): raise salt.exceptions.NotImplemented()
null
null
null
code
codeqa
def set *args **kwargs raise salt exceptions Not Implemented
null
null
null
null
Question: What is setting a value ? Code: def set_(*args, **kwargs): raise salt.exceptions.NotImplemented()
null
null
null
What do code set ?
def set_(*args, **kwargs): raise salt.exceptions.NotImplemented()
null
null
null
a value
codeqa
def set *args **kwargs raise salt exceptions Not Implemented
null
null
null
null
Question: What do code set ? Code: def set_(*args, **kwargs): raise salt.exceptions.NotImplemented()
null
null
null
What did the code cast to a strictly positive integer ?
def _positive_int(integer_string, strict=False, cutoff=None): ret = int(integer_string) if ((ret < 0) or ((ret == 0) and strict)): raise ValueError() if cutoff: ret = min(ret, cutoff) return ret
null
null
null
a string
codeqa
def positive int integer string strict False cutoff None ret int integer string if ret < 0 or ret 0 and strict raise Value Error if cutoff ret min ret cutoff return ret
null
null
null
null
Question: What did the code cast to a strictly positive integer ? Code: def _positive_int(integer_string, strict=False, cutoff=None): ret = int(integer_string) if ((ret < 0) or ((ret == 0) and strict)): raise ValueError() if cutoff: ret = min(ret, cutoff) return ret
null
null
null
What does the code chown ?
def lchown(path, user, group): path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if (uid == ''): if user: err += 'User does not exist\n' else: uid = (-1) if (gid == ''): if group: err += 'Group does not exist\n' else: gid = (-1) return os.lchown(path, uid, gid)
null
null
null
a file
codeqa
def lchown path user group path os path expanduser path uid user to uid user gid group to gid group err ''if uid '' if user err + ' Userdoesnotexist\n'else uid -1 if gid '' if group err + ' Groupdoesnotexist\n'else gid -1 return os lchown path uid gid
null
null
null
null
Question: What does the code chown ? Code: def lchown(path, user, group): path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if (uid == ''): if user: err += 'User does not exist\n' else: uid = (-1) if (gid == ''): if group: err += 'Group does not exist\n' else: gid = (-1) return os.lchown(path, uid, gid)
null
null
null
What does the code get ?
def getLargestInsetLoopFromLoop(loop, radius): loops = getInsetLoopsFromLoop(radius, loop) return euclidean.getLargestLoop(loops)
null
null
null
the largest inset loop from the loop
codeqa
def get Largest Inset Loop From Loop loop radius loops get Inset Loops From Loop radius loop return euclidean get Largest Loop loops
null
null
null
null
Question: What does the code get ? Code: def getLargestInsetLoopFromLoop(loop, radius): loops = getInsetLoopsFromLoop(radius, loop) return euclidean.getLargestLoop(loops)
null
null
null
The code testing equivalent of which organization ?
def gen_test(func=None, timeout=None): if (timeout is None): timeout = get_async_test_timeout() def wrap(f): @functools.wraps(f) def pre_coroutine(self, *args, **kwargs): result = f(self, *args, **kwargs) if isinstance(result, types.GeneratorType): self._test_generator = result else: self._test_generator = None return result coro = gen.coroutine(pre_coroutine) @functools.wraps(coro) def post_coroutine(self, *args, **kwargs): try: return self.io_loop.run_sync(functools.partial(coro, self, *args, **kwargs), timeout=timeout) except TimeoutError as e: self._test_generator.throw(e) raise return post_coroutine if (func is not None): return wrap(func) else: return wrap
null
null
null
@gen
codeqa
def gen test func None timeout None if timeout is None timeout get async test timeout def wrap f @functools wraps f def pre coroutine self *args **kwargs result f self *args **kwargs if isinstance result types Generator Type self test generator resultelse self test generator Nonereturn resultcoro gen coroutine pre coroutine @functools wraps coro def post coroutine self *args **kwargs try return self io loop run sync functools partial coro self *args **kwargs timeout timeout except Timeout Error as e self test generator throw e raisereturn post coroutineif func is not None return wrap func else return wrap
null
null
null
null
Question: The code testing equivalent of which organization ? Code: def gen_test(func=None, timeout=None): if (timeout is None): timeout = get_async_test_timeout() def wrap(f): @functools.wraps(f) def pre_coroutine(self, *args, **kwargs): result = f(self, *args, **kwargs) if isinstance(result, types.GeneratorType): self._test_generator = result else: self._test_generator = None return result coro = gen.coroutine(pre_coroutine) @functools.wraps(coro) def post_coroutine(self, *args, **kwargs): try: return self.io_loop.run_sync(functools.partial(coro, self, *args, **kwargs), timeout=timeout) except TimeoutError as e: self._test_generator.throw(e) raise return post_coroutine if (func is not None): return wrap(func) else: return wrap
null
null
null
What do services use for data integrity ?
def quorum_size(n): return ((n + 1) // 2)
null
null
null
replication
codeqa
def quorum size n return n + 1 // 2
null
null
null
null
Question: What do services use for data integrity ? Code: def quorum_size(n): return ((n + 1) // 2)
null
null
null
What use replication for data integrity ?
def quorum_size(n): return ((n + 1) // 2)
null
null
null
services
codeqa
def quorum size n return n + 1 // 2
null
null
null
null
Question: What use replication for data integrity ? Code: def quorum_size(n): return ((n + 1) // 2)
null
null
null
In which direction did the code read meg ?
def read_forward_solution_meg(*args, **kwargs): fwd = read_forward_solution(*args, **kwargs) fwd = pick_types_forward(fwd, meg=True, eeg=False) return fwd
null
null
null
forward
codeqa
def read forward solution meg *args **kwargs fwd read forward solution *args **kwargs fwd pick types forward fwd meg True eeg False return fwd
null
null
null
null
Question: In which direction did the code read meg ? Code: def read_forward_solution_meg(*args, **kwargs): fwd = read_forward_solution(*args, **kwargs) fwd = pick_types_forward(fwd, meg=True, eeg=False) return fwd
null
null
null
How did the code read forward ?
def read_forward_solution_meg(*args, **kwargs): fwd = read_forward_solution(*args, **kwargs) fwd = pick_types_forward(fwd, meg=True, eeg=False) return fwd
null
null
null
meg
codeqa
def read forward solution meg *args **kwargs fwd read forward solution *args **kwargs fwd pick types forward fwd meg True eeg False return fwd
null
null
null
null
Question: How did the code read forward ? Code: def read_forward_solution_meg(*args, **kwargs): fwd = read_forward_solution(*args, **kwargs) fwd = pick_types_forward(fwd, meg=True, eeg=False) return fwd
null
null
null
How does directories create ?
def renames(old, new): (head, tail) = path.split(new) if (head and tail and (not path.exists(head))): makedirs(head) rename(old, new) (head, tail) = path.split(old) if (head and tail): try: removedirs(head) except error: pass
null
null
null
as necessary
codeqa
def renames old new head tail path split new if head and tail and not path exists head makedirs head rename old new head tail path split old if head and tail try removedirs head except error pass
null
null
null
null
Question: How does directories create ? Code: def renames(old, new): (head, tail) = path.split(new) if (head and tail and (not path.exists(head))): makedirs(head) rename(old, new) (head, tail) = path.split(old) if (head and tail): try: removedirs(head) except error: pass
null
null
null
What does the code get from this media list instance ?
def libvlc_media_list_media(p_ml): f = (_Cfunctions.get('libvlc_media_list_media', None) or _Cfunction('libvlc_media_list_media', ((1,),), class_result(Media), ctypes.c_void_p, MediaList)) return f(p_ml)
null
null
null
media instance
codeqa
def libvlc media list media p ml f Cfunctions get 'libvlc media list media' None or Cfunction 'libvlc media list media' 1 class result Media ctypes c void p Media List return f p ml
null
null
null
null
Question: What does the code get from this media list instance ? Code: def libvlc_media_list_media(p_ml): f = (_Cfunctions.get('libvlc_media_list_media', None) or _Cfunction('libvlc_media_list_media', ((1,),), class_result(Media), ctypes.c_void_p, MediaList)) return f(p_ml)
null
null
null
What do a string represent ?
def version(*names, **kwargs): if (len(names) == 1): return str(__proxy__['rest_sample.package_status'](names[0]))
null
null
null
the package version
codeqa
def version *names **kwargs if len names 1 return str proxy ['rest sample package status'] names[ 0 ]
null
null
null
null
Question: What do a string represent ? Code: def version(*names, **kwargs): if (len(names) == 1): return str(__proxy__['rest_sample.package_status'](names[0]))
null
null
null
What is representing the package version ?
def version(*names, **kwargs): if (len(names) == 1): return str(__proxy__['rest_sample.package_status'](names[0]))
null
null
null
a string
codeqa
def version *names **kwargs if len names 1 return str proxy ['rest sample package status'] names[ 0 ]
null
null
null
null
Question: What is representing the package version ? Code: def version(*names, **kwargs): if (len(names) == 1): return str(__proxy__['rest_sample.package_status'](names[0]))
null
null
null
What is describing any failures ?
def put_targets(Rule, Targets, region=None, key=None, keyid=None, profile=None): try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(Targets, string_types): Targets = json.loads(Targets) failures = conn.put_targets(Rule=Rule, Targets=Targets) if (failures and (failures.get('FailedEntryCount', 0) > 0)): return {'failures': failures.get('FailedEntries')} else: return {'failures': None} except ClientError as e: err = __utils__['boto3.get_error'](e) if (e.response.get('Error', {}).get('Code') == 'RuleNotFoundException'): return {'error': 'Rule {0} not found'.format(Rule)} return {'error': __utils__['boto3.get_error'](e)}
null
null
null
a dictionary
codeqa
def put targets Rule Targets region None key None keyid None profile None try conn get conn region region key key keyid keyid profile profile if isinstance Targets string types Targets json loads Targets failures conn put targets Rule Rule Targets Targets if failures and failures get ' Failed Entry Count' 0 > 0 return {'failures' failures get ' Failed Entries' }else return {'failures' None}except Client Error as e err utils ['boto 3 get error'] e if e response get ' Error' {} get ' Code' ' Rule Not Found Exception' return {'error' ' Rule{ 0 }notfound' format Rule }return {'error' utils ['boto 3 get error'] e }
null
null
null
null
Question: What is describing any failures ? Code: def put_targets(Rule, Targets, region=None, key=None, keyid=None, profile=None): try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(Targets, string_types): Targets = json.loads(Targets) failures = conn.put_targets(Rule=Rule, Targets=Targets) if (failures and (failures.get('FailedEntryCount', 0) > 0)): return {'failures': failures.get('FailedEntries')} else: return {'failures': None} except ClientError as e: err = __utils__['boto3.get_error'](e) if (e.response.get('Error', {}).get('Code') == 'RuleNotFoundException'): return {'error': 'Rule {0} not found'.format(Rule)} return {'error': __utils__['boto3.get_error'](e)}
null
null
null
What does the code draw to a file ?
def draw_to_file(layers, filename, **kwargs): layers = (layers.get_all_layers() if hasattr(layers, 'get_all_layers') else layers) dot = make_pydot_graph(layers, **kwargs) ext = filename[(filename.rfind('.') + 1):] with io.open(filename, 'wb') as fid: fid.write(dot.create(format=ext))
null
null
null
a network diagram
codeqa
def draw to file layers filename **kwargs layers layers get all layers if hasattr layers 'get all layers' else layers dot make pydot graph layers **kwargs ext filename[ filename rfind ' ' + 1 ]with io open filename 'wb' as fid fid write dot create format ext
null
null
null
null
Question: What does the code draw to a file ? Code: def draw_to_file(layers, filename, **kwargs): layers = (layers.get_all_layers() if hasattr(layers, 'get_all_layers') else layers) dot = make_pydot_graph(layers, **kwargs) ext = filename[(filename.rfind('.') + 1):] with io.open(filename, 'wb') as fid: fid.write(dot.create(format=ext))
null
null
null
What did the code set ?
def setprofile(func): global _profile_hook _profile_hook = func
null
null
null
a profile function for all threads started from the threading module
codeqa
def setprofile func global profile hook profile hook func
null
null
null
null
Question: What did the code set ? Code: def setprofile(func): global _profile_hook _profile_hook = func
null
null
null
What can a decorator be used ?
def deprecated(func): if callable(func): def new_func(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) warnings.warn('Call to deprecated {0}.'.format(func.__name__), category=DeprecationWarning, stacklevel=2) warnings.simplefilter('default', DeprecationWarning) return func(*args, **kwargs) new_func.__name__ = func.__name__ new_func.__doc__ = func.__doc__ new_func.__dict__.update(func.__dict__) else: raise NotImplementedError() return new_func
null
null
null
to mark functions as deprecated
codeqa
def deprecated func if callable func def new func *args **kwargs warnings simplefilter 'always' Deprecation Warning warnings warn ' Calltodeprecated{ 0 } ' format func name category Deprecation Warning stacklevel 2 warnings simplefilter 'default' Deprecation Warning return func *args **kwargs new func name func name new func doc func doc new func dict update func dict else raise Not Implemented Error return new func
null
null
null
null
Question: What can a decorator be used ? Code: def deprecated(func): if callable(func): def new_func(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) warnings.warn('Call to deprecated {0}.'.format(func.__name__), category=DeprecationWarning, stacklevel=2) warnings.simplefilter('default', DeprecationWarning) return func(*args, **kwargs) new_func.__name__ = func.__name__ new_func.__doc__ = func.__doc__ new_func.__dict__.update(func.__dict__) else: raise NotImplementedError() return new_func
null
null
null
What can be used to mark functions as deprecated ?
def deprecated(func): if callable(func): def new_func(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) warnings.warn('Call to deprecated {0}.'.format(func.__name__), category=DeprecationWarning, stacklevel=2) warnings.simplefilter('default', DeprecationWarning) return func(*args, **kwargs) new_func.__name__ = func.__name__ new_func.__doc__ = func.__doc__ new_func.__dict__.update(func.__dict__) else: raise NotImplementedError() return new_func
null
null
null
a decorator
codeqa
def deprecated func if callable func def new func *args **kwargs warnings simplefilter 'always' Deprecation Warning warnings warn ' Calltodeprecated{ 0 } ' format func name category Deprecation Warning stacklevel 2 warnings simplefilter 'default' Deprecation Warning return func *args **kwargs new func name func name new func doc func doc new func dict update func dict else raise Not Implemented Error return new func
null
null
null
null
Question: What can be used to mark functions as deprecated ? Code: def deprecated(func): if callable(func): def new_func(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) warnings.warn('Call to deprecated {0}.'.format(func.__name__), category=DeprecationWarning, stacklevel=2) warnings.simplefilter('default', DeprecationWarning) return func(*args, **kwargs) new_func.__name__ = func.__name__ new_func.__doc__ = func.__doc__ new_func.__dict__.update(func.__dict__) else: raise NotImplementedError() return new_func
null
null
null
What does the code sanitize ?
def sanitize_file_name_unicode(name, substitute='_'): if isbytestring(name): return sanitize_file_name(name, substitute=substitute, as_unicode=True) chars = [(substitute if (c in _filename_sanitize_unicode) else c) for c in name] one = u''.join(chars) one = re.sub('\\s', ' ', one).strip() (bname, ext) = os.path.splitext(one) one = re.sub('^\\.+$', '_', bname) one = one.replace('..', substitute) one += ext if (one and (one[(-1)] in ('.', ' '))): one = (one[:(-1)] + '_') if one.startswith('.'): one = ('_' + one[1:]) return one
null
null
null
the filename name
codeqa
def sanitize file name unicode name substitute ' ' if isbytestring name return sanitize file name name substitute substitute as unicode True chars [ substitute if c in filename sanitize unicode else c for c in name]one u'' join chars one re sub '\\s' '' one strip bname ext os path splitext one one re sub '^\\ +$' ' ' bname one one replace ' ' substitute one + extif one and one[ -1 ] in ' ' '' one one[ -1 ] + ' ' if one startswith ' ' one ' ' + one[ 1 ] return one
null
null
null
null
Question: What does the code sanitize ? Code: def sanitize_file_name_unicode(name, substitute='_'): if isbytestring(name): return sanitize_file_name(name, substitute=substitute, as_unicode=True) chars = [(substitute if (c in _filename_sanitize_unicode) else c) for c in name] one = u''.join(chars) one = re.sub('\\s', ' ', one).strip() (bname, ext) = os.path.splitext(one) one = re.sub('^\\.+$', '_', bname) one = one.replace('..', substitute) one += ext if (one and (one[(-1)] in ('.', ' '))): one = (one[:(-1)] + '_') if one.startswith('.'): one = ('_' + one[1:]) return one
null
null
null
How did context do ?
@require_authorized_access_to_student_data def student_view_context(request): user = get_user_from_request(request=request) if (not user): raise Http404('User not found.') context = {'facility_id': user.facility.id, 'student': user} return context
null
null
null
separately
codeqa
@require authorized access to student datadef student view context request user get user from request request request if not user raise Http 404 ' Usernotfound ' context {'facility id' user facility id 'student' user}return context
null
null
null
null
Question: How did context do ? Code: @require_authorized_access_to_student_data def student_view_context(request): user = get_user_from_request(request=request) if (not user): raise Http404('User not found.') context = {'facility_id': user.facility.id, 'student': user} return context
null
null
null
What does the code delete ?
def volume_metadata_delete(context, volume_id, key, meta_type=common.METADATA_TYPES.user): return IMPL.volume_metadata_delete(context, volume_id, key, meta_type)
null
null
null
the given metadata item
codeqa
def volume metadata delete context volume id key meta type common METADATA TYPES user return IMPL volume metadata delete context volume id key meta type
null
null
null
null
Question: What does the code delete ? Code: def volume_metadata_delete(context, volume_id, key, meta_type=common.METADATA_TYPES.user): return IMPL.volume_metadata_delete(context, volume_id, key, meta_type)
null
null
null
What is using utf-8 ?
def encode_params_utf8(params): encoded = [] for (k, v) in params: encoded.append(((k.encode('utf-8') if isinstance(k, unicode) else k), (v.encode('utf-8') if isinstance(v, unicode) else v))) return encoded
null
null
null
all parameters in a list of 2-element tuples
codeqa
def encode params utf 8 params encoded []for k v in params encoded append k encode 'utf- 8 ' if isinstance k unicode else k v encode 'utf- 8 ' if isinstance v unicode else v return encoded
null
null
null
null
Question: What is using utf-8 ? Code: def encode_params_utf8(params): encoded = [] for (k, v) in params: encoded.append(((k.encode('utf-8') if isinstance(k, unicode) else k), (v.encode('utf-8') if isinstance(v, unicode) else v))) return encoded
null
null
null
What do all parameters in a list of 2-element tuples use ?
def encode_params_utf8(params): encoded = [] for (k, v) in params: encoded.append(((k.encode('utf-8') if isinstance(k, unicode) else k), (v.encode('utf-8') if isinstance(v, unicode) else v))) return encoded
null
null
null
utf-8
codeqa
def encode params utf 8 params encoded []for k v in params encoded append k encode 'utf- 8 ' if isinstance k unicode else k v encode 'utf- 8 ' if isinstance v unicode else v return encoded
null
null
null
null
Question: What do all parameters in a list of 2-element tuples use ? Code: def encode_params_utf8(params): encoded = [] for (k, v) in params: encoded.append(((k.encode('utf-8') if isinstance(k, unicode) else k), (v.encode('utf-8') if isinstance(v, unicode) else v))) return encoded
null
null
null
In which direction is the user logged ?
def login_required(func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): def decorator(view_func): @functools.wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.user.is_authenticated(): return view_func(request, *args, **kwargs) return handle_redirect_to_login(request, redirect_field_name=redirect_field_name, login_url=login_url) return _wrapped_view if func: return decorator(func) return decorator
null
null
null
in
codeqa
def login required func None redirect field name REDIRECT FIELD NAME login url None def decorator view func @functools wraps view func assigned available attrs view func def wrapped view request *args **kwargs if request user is authenticated return view func request *args **kwargs return handle redirect to login request redirect field name redirect field name login url login url return wrapped viewif func return decorator func return decorator
null
null
null
null
Question: In which direction is the user logged ? Code: def login_required(func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): def decorator(view_func): @functools.wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.user.is_authenticated(): return view_func(request, *args, **kwargs) return handle_redirect_to_login(request, redirect_field_name=redirect_field_name, login_url=login_url) return _wrapped_view if func: return decorator(func) return decorator
null
null
null
What does decorator for views check ?
def login_required(func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): def decorator(view_func): @functools.wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.user.is_authenticated(): return view_func(request, *args, **kwargs) return handle_redirect_to_login(request, redirect_field_name=redirect_field_name, login_url=login_url) return _wrapped_view if func: return decorator(func) return decorator
null
null
null
that the user is logged in
codeqa
def login required func None redirect field name REDIRECT FIELD NAME login url None def decorator view func @functools wraps view func assigned available attrs view func def wrapped view request *args **kwargs if request user is authenticated return view func request *args **kwargs return handle redirect to login request redirect field name redirect field name login url login url return wrapped viewif func return decorator func return decorator
null
null
null
null
Question: What does decorator for views check ? Code: def login_required(func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): def decorator(view_func): @functools.wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.user.is_authenticated(): return view_func(request, *args, **kwargs) return handle_redirect_to_login(request, redirect_field_name=redirect_field_name, login_url=login_url) return _wrapped_view if func: return decorator(func) return decorator
null
null
null
What checks that the user is logged in ?
def login_required(func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): def decorator(view_func): @functools.wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.user.is_authenticated(): return view_func(request, *args, **kwargs) return handle_redirect_to_login(request, redirect_field_name=redirect_field_name, login_url=login_url) return _wrapped_view if func: return decorator(func) return decorator
null
null
null
decorator for views
codeqa
def login required func None redirect field name REDIRECT FIELD NAME login url None def decorator view func @functools wraps view func assigned available attrs view func def wrapped view request *args **kwargs if request user is authenticated return view func request *args **kwargs return handle redirect to login request redirect field name redirect field name login url login url return wrapped viewif func return decorator func return decorator
null
null
null
null
Question: What checks that the user is logged in ? Code: def login_required(func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): def decorator(view_func): @functools.wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.user.is_authenticated(): return view_func(request, *args, **kwargs) return handle_redirect_to_login(request, redirect_field_name=redirect_field_name, login_url=login_url) return _wrapped_view if func: return decorator(func) return decorator
null
null
null
How did the choices call in ?
def validate_choice(value, choices): if ((choices is not None) and (value not in choices)): names = u', '.join((repr(c) for c in choices)) raise ValueError((u'must be one of %s, not %s.' % (names, value)))
null
null
null
normally
codeqa
def validate choice value choices if choices is not None and value not in choices names u' ' join repr c for c in choices raise Value Error u'mustbeoneof%s not%s ' % names value
null
null
null
null
Question: How did the choices call in ? Code: def validate_choice(value, choices): if ((choices is not None) and (value not in choices)): names = u', '.join((repr(c) for c in choices)) raise ValueError((u'must be one of %s, not %s.' % (names, value)))
null
null
null
How does the code open a bzip2-compressed file ?
def open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None): if ('t' in mode): if ('b' in mode): raise ValueError(('Invalid mode: %r' % (mode,))) else: if (encoding is not None): raise ValueError("Argument 'encoding' not supported in binary mode") if (errors is not None): raise ValueError("Argument 'errors' not supported in binary mode") if (newline is not None): raise ValueError("Argument 'newline' not supported in binary mode") bz_mode = mode.replace('t', '') binary_file = BZ2File(filename, bz_mode, compresslevel=compresslevel) if ('t' in mode): return io.TextIOWrapper(binary_file, encoding, errors, newline) else: return binary_file
null
null
null
in binary or text mode
codeqa
def open filename mode 'rb' compresslevel 9 encoding None errors None newline None if 't' in mode if 'b' in mode raise Value Error ' Invalidmode %r' % mode else if encoding is not None raise Value Error " Argument'encoding'notsupportedinbinarymode" if errors is not None raise Value Error " Argument'errors'notsupportedinbinarymode" if newline is not None raise Value Error " Argument'newline'notsupportedinbinarymode" bz mode mode replace 't' '' binary file BZ 2 File filename bz mode compresslevel compresslevel if 't' in mode return io Text IO Wrapper binary file encoding errors newline else return binary file
null
null
null
null
Question: How does the code open a bzip2-compressed file ? Code: def open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None): if ('t' in mode): if ('b' in mode): raise ValueError(('Invalid mode: %r' % (mode,))) else: if (encoding is not None): raise ValueError("Argument 'encoding' not supported in binary mode") if (errors is not None): raise ValueError("Argument 'errors' not supported in binary mode") if (newline is not None): raise ValueError("Argument 'newline' not supported in binary mode") bz_mode = mode.replace('t', '') binary_file = BZ2File(filename, bz_mode, compresslevel=compresslevel) if ('t' in mode): return io.TextIOWrapper(binary_file, encoding, errors, newline) else: return binary_file
null
null
null
What does the code open in binary or text mode ?
def open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None): if ('t' in mode): if ('b' in mode): raise ValueError(('Invalid mode: %r' % (mode,))) else: if (encoding is not None): raise ValueError("Argument 'encoding' not supported in binary mode") if (errors is not None): raise ValueError("Argument 'errors' not supported in binary mode") if (newline is not None): raise ValueError("Argument 'newline' not supported in binary mode") bz_mode = mode.replace('t', '') binary_file = BZ2File(filename, bz_mode, compresslevel=compresslevel) if ('t' in mode): return io.TextIOWrapper(binary_file, encoding, errors, newline) else: return binary_file
null
null
null
a bzip2-compressed file
codeqa
def open filename mode 'rb' compresslevel 9 encoding None errors None newline None if 't' in mode if 'b' in mode raise Value Error ' Invalidmode %r' % mode else if encoding is not None raise Value Error " Argument'encoding'notsupportedinbinarymode" if errors is not None raise Value Error " Argument'errors'notsupportedinbinarymode" if newline is not None raise Value Error " Argument'newline'notsupportedinbinarymode" bz mode mode replace 't' '' binary file BZ 2 File filename bz mode compresslevel compresslevel if 't' in mode return io Text IO Wrapper binary file encoding errors newline else return binary file
null
null
null
null
Question: What does the code open in binary or text mode ? Code: def open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None): if ('t' in mode): if ('b' in mode): raise ValueError(('Invalid mode: %r' % (mode,))) else: if (encoding is not None): raise ValueError("Argument 'encoding' not supported in binary mode") if (errors is not None): raise ValueError("Argument 'errors' not supported in binary mode") if (newline is not None): raise ValueError("Argument 'newline' not supported in binary mode") bz_mode = mode.replace('t', '') binary_file = BZ2File(filename, bz_mode, compresslevel=compresslevel) if ('t' in mode): return io.TextIOWrapper(binary_file, encoding, errors, newline) else: return binary_file
null
null
null
What does the code associate to a node ?
@sqlalchemy_api.require_admin_context def bm_node_associate_and_update(context, node_uuid, values): if ('instance_uuid' not in values): raise exception.NovaException(_('instance_uuid must be supplied to bm_node_associate_and_update')) session = db_session.get_session() with session.begin(): query = model_query(context, models.BareMetalNode, session=session, read_deleted='no').filter_by(uuid=node_uuid) count = query.filter_by(instance_uuid=None).update(values, synchronize_session=False) if (count != 1): raise exception.NovaException((_('Failed to associate instance %(i_uuid)s to baremetal node %(n_uuid)s.') % {'i_uuid': values['instance_uuid'], 'n_uuid': node_uuid})) ref = query.first() return ref
null
null
null
an instance
codeqa
@sqlalchemy api require admin contextdef bm node associate and update context node uuid values if 'instance uuid' not in values raise exception Nova Exception 'instance uuidmustbesuppliedtobm node associate and update' session db session get session with session begin query model query context models Bare Metal Node session session read deleted 'no' filter by uuid node uuid count query filter by instance uuid None update values synchronize session False if count 1 raise exception Nova Exception ' Failedtoassociateinstance% i uuid stobaremetalnode% n uuid s ' % {'i uuid' values['instance uuid'] 'n uuid' node uuid} ref query first return ref
null
null
null
null
Question: What does the code associate to a node ? Code: @sqlalchemy_api.require_admin_context def bm_node_associate_and_update(context, node_uuid, values): if ('instance_uuid' not in values): raise exception.NovaException(_('instance_uuid must be supplied to bm_node_associate_and_update')) session = db_session.get_session() with session.begin(): query = model_query(context, models.BareMetalNode, session=session, read_deleted='no').filter_by(uuid=node_uuid) count = query.filter_by(instance_uuid=None).update(values, synchronize_session=False) if (count != 1): raise exception.NovaException((_('Failed to associate instance %(i_uuid)s to baremetal node %(n_uuid)s.') % {'i_uuid': values['instance_uuid'], 'n_uuid': node_uuid})) ref = query.first() return ref
null
null
null
What does the code create ?
def hardlinkFile(srcFile, destFile): try: ek(link, srcFile, destFile) fixSetGroupID(destFile) except Exception as error: logger.log(u'Failed to create hardlink of {0} at {1}. Error: {2}. Copying instead'.format(srcFile, destFile, error), logger.WARNING) copyFile(srcFile, destFile)
null
null
null
a hard - link between source and destination
codeqa
def hardlink File src File dest File try ek link src File dest File fix Set Group ID dest File except Exception as error logger log u' Failedtocreatehardlinkof{ 0 }at{ 1 } Error {2 } Copyinginstead' format src File dest File error logger WARNING copy File src File dest File
null
null
null
null
Question: What does the code create ? Code: def hardlinkFile(srcFile, destFile): try: ek(link, srcFile, destFile) fixSetGroupID(destFile) except Exception as error: logger.log(u'Failed to create hardlink of {0} at {1}. Error: {2}. Copying instead'.format(srcFile, destFile, error), logger.WARNING) copyFile(srcFile, destFile)
null
null
null
What set it to the default explicitly ?
def set_by_cli(var): detector = set_by_cli.detector if (detector is None): plugins = plugins_disco.PluginsRegistry.find_all() reconstructed_args = (helpful_parser.args + [helpful_parser.verb]) detector = set_by_cli.detector = prepare_and_parse_args(plugins, reconstructed_args, detect_defaults=True) (detector.authenticator, detector.installer) = plugin_selection.cli_plugin_requests(detector) logger.debug('Default Detector is %r', detector) if (not isinstance(getattr(detector, var), _Default)): return True for modifier in VAR_MODIFIERS.get(var, []): if set_by_cli(modifier): return True return False
null
null
null
the user
codeqa
def set by cli var detector set by cli detectorif detector is None plugins plugins disco Plugins Registry find all reconstructed args helpful parser args + [helpful parser verb] detector set by cli detector prepare and parse args plugins reconstructed args detect defaults True detector authenticator detector installer plugin selection cli plugin requests detector logger debug ' Default Detectoris%r' detector if not isinstance getattr detector var Default return Truefor modifier in VAR MODIFIERS get var [] if set by cli modifier return Truereturn False
null
null
null
null
Question: What set it to the default explicitly ? Code: def set_by_cli(var): detector = set_by_cli.detector if (detector is None): plugins = plugins_disco.PluginsRegistry.find_all() reconstructed_args = (helpful_parser.args + [helpful_parser.verb]) detector = set_by_cli.detector = prepare_and_parse_args(plugins, reconstructed_args, detect_defaults=True) (detector.authenticator, detector.installer) = plugin_selection.cli_plugin_requests(detector) logger.debug('Default Detector is %r', detector) if (not isinstance(getattr(detector, var), _Default)): return True for modifier in VAR_MODIFIERS.get(var, []): if set_by_cli(modifier): return True return False
null
null
null
How do the user set it to the default ?
def set_by_cli(var): detector = set_by_cli.detector if (detector is None): plugins = plugins_disco.PluginsRegistry.find_all() reconstructed_args = (helpful_parser.args + [helpful_parser.verb]) detector = set_by_cli.detector = prepare_and_parse_args(plugins, reconstructed_args, detect_defaults=True) (detector.authenticator, detector.installer) = plugin_selection.cli_plugin_requests(detector) logger.debug('Default Detector is %r', detector) if (not isinstance(getattr(detector, var), _Default)): return True for modifier in VAR_MODIFIERS.get(var, []): if set_by_cli(modifier): return True return False
null
null
null
explicitly
codeqa
def set by cli var detector set by cli detectorif detector is None plugins plugins disco Plugins Registry find all reconstructed args helpful parser args + [helpful parser verb] detector set by cli detector prepare and parse args plugins reconstructed args detect defaults True detector authenticator detector installer plugin selection cli plugin requests detector logger debug ' Default Detectoris%r' detector if not isinstance getattr detector var Default return Truefor modifier in VAR MODIFIERS get var [] if set by cli modifier return Truereturn False
null
null
null
null
Question: How do the user set it to the default ? Code: def set_by_cli(var): detector = set_by_cli.detector if (detector is None): plugins = plugins_disco.PluginsRegistry.find_all() reconstructed_args = (helpful_parser.args + [helpful_parser.verb]) detector = set_by_cli.detector = prepare_and_parse_args(plugins, reconstructed_args, detect_defaults=True) (detector.authenticator, detector.installer) = plugin_selection.cli_plugin_requests(detector) logger.debug('Default Detector is %r', detector) if (not isinstance(getattr(detector, var), _Default)): return True for modifier in VAR_MODIFIERS.get(var, []): if set_by_cli(modifier): return True return False