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 do you decorate with this ?
def login_required(func): @wraps(func) def decorated_view(*args, **kwargs): if (request.method in EXEMPT_METHODS): return func(*args, **kwargs) elif current_app.login_manager._login_disabled: return func(*args, **kwargs) elif (not current_user.is_authenticated): return current_app.login_manager.unauthorized() return func(*args, **kwargs) return decorated_view
null
null
null
a view
codeqa
def login required func @wraps func def decorated view *args **kwargs if request method in EXEMPT METHODS return func *args **kwargs elif current app login manager login disabled return func *args **kwargs elif not current user is authenticated return current app login manager unauthorized return func *args **kwargs return decorated view
null
null
null
null
Question: What do you decorate with this ? Code: def login_required(func): @wraps(func) def decorated_view(*args, **kwargs): if (request.method in EXEMPT_METHODS): return func(*args, **kwargs) elif current_app.login_manager._login_disabled: return func(*args, **kwargs) elif (not current_user.is_authenticated): return current_app.login_manager.unauthorized() return func(*args, **kwargs) return decorated_view
null
null
null
What does the code remove ?
def remove_all(path, pattern='*', keep_folder=False, recursive=False): if os.path.exists(path): files = globber_full(path, pattern) if ((pattern == '*') and (not sabnzbd.WIN32)): files.extend(globber_full(path, '.*')) for f in files: if os.path.isfile(f): try: os.remove(f) except: logging.info('Cannot remove file %s', f) elif recursive: remove_all(f, pattern, False, True) if (not keep_folder): try: os.rmdir(path) except: logging.info('Cannot remove folder %s', path)
null
null
null
folder
codeqa
def remove all path pattern '*' keep folder False recursive False if os path exists path files globber full path pattern if pattern '*' and not sabnzbd WIN 32 files extend globber full path ' *' for f in files if os path isfile f try os remove f except logging info ' Cannotremovefile%s' f elif recursive remove all f pattern False True if not keep folder try os rmdir path except logging info ' Cannotremovefolder%s' path
null
null
null
null
Question: What does the code remove ? Code: def remove_all(path, pattern='*', keep_folder=False, recursive=False): if os.path.exists(path): files = globber_full(path, pattern) if ((pattern == '*') and (not sabnzbd.WIN32)): files.extend(globber_full(path, '.*')) for f in files: if os.path.isfile(f): try: os.remove(f) except: logging.info('Cannot remove file %s', f) elif recursive: remove_all(f, pattern, False, True) if (not keep_folder): try: os.rmdir(path) except: logging.info('Cannot remove folder %s', path)
null
null
null
What does the code authorize ?
def groups_for_user(environ, username): db.reset_queries() try: try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: return [] if (not user.is_active): return [] return [force_bytes(group.name) for group in user.groups.all()] finally: db.close_old_connections()
null
null
null
a user based on groups
codeqa
def groups for user environ username db reset queries try try user User Model default manager get by natural key username except User Model Does Not Exist return []if not user is active return []return [force bytes group name for group in user groups all ]finally db close old connections
null
null
null
null
Question: What does the code authorize ? Code: def groups_for_user(environ, username): db.reset_queries() try: try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: return [] if (not user.is_active): return [] return [force_bytes(group.name) for group in user.groups.all()] finally: db.close_old_connections()
null
null
null
How do them delete optionally at the end ?
def cloudformation(registry, xml_parent, data): region_dict = cloudformation_region_dict() stacks = cloudformation_init(xml_parent, data, 'CloudFormationBuildStep') for stack in data: cloudformation_stack(xml_parent, stack, 'PostBuildStackBean', stacks, region_dict)
null
null
null
cloudformation
codeqa
def cloudformation registry xml parent data region dict cloudformation region dict stacks cloudformation init xml parent data ' Cloud Formation Build Step' for stack in data cloudformation stack xml parent stack ' Post Build Stack Bean' stacks region dict
null
null
null
null
Question: How do them delete optionally at the end ? Code: def cloudformation(registry, xml_parent, data): region_dict = cloudformation_region_dict() stacks = cloudformation_init(xml_parent, data, 'CloudFormationBuildStep') for stack in data: cloudformation_stack(xml_parent, stack, 'PostBuildStackBean', stacks, region_dict)
null
null
null
What does the code display ?
def now(parser, token): bits = token.contents.split('"') if (len(bits) != 3): raise TemplateSyntaxError("'now' statement takes one argument") format_string = bits[1] return NowNode(format_string)
null
null
null
the date
codeqa
def now parser token bits token contents split '"' if len bits 3 raise Template Syntax Error "'now'statementtakesoneargument"format string bits[ 1 ]return Now Node format string
null
null
null
null
Question: What does the code display ? Code: def now(parser, token): bits = token.contents.split('"') if (len(bits) != 3): raise TemplateSyntaxError("'now' statement takes one argument") format_string = bits[1] return NowNode(format_string)
null
null
null
What does the code discretize with different modes ?
@pytest.mark.parametrize(u'mode', modes) def test_gaussian_eval_2D(mode): model = Gaussian2D(1, 0, 0, 20, 20) x = np.arange((-100), 101) y = np.arange((-100), 101) (x, y) = np.meshgrid(x, y) values = model(x, y) disc_values = discretize_model(model, ((-100), 101), ((-100), 101), mode=mode) assert_allclose(values, disc_values, atol=0.001)
null
null
null
gaussian
codeqa
@pytest mark parametrize u'mode' modes def test gaussian eval 2D mode model Gaussian 2 D 1 0 0 20 20 x np arange -100 101 y np arange -100 101 x y np meshgrid x y values model x y disc values discretize model model -100 101 -100 101 mode mode assert allclose values disc values atol 0 001
null
null
null
null
Question: What does the code discretize with different modes ? Code: @pytest.mark.parametrize(u'mode', modes) def test_gaussian_eval_2D(mode): model = Gaussian2D(1, 0, 0, 20, 20) x = np.arange((-100), 101) y = np.arange((-100), 101) (x, y) = np.meshgrid(x, y) values = model(x, y) disc_values = discretize_model(model, ((-100), 101), ((-100), 101), mode=mode) assert_allclose(values, disc_values, atol=0.001)
null
null
null
For what purpose did revisions flag ?
@block_user_agents @require_GET def needs_review(request, tag=None): tag_obj = ((tag and get_object_or_404(ReviewTag, name=tag)) or None) docs = Document.objects.filter_for_review(locale=request.LANGUAGE_CODE, tag=tag_obj) paginated_docs = paginate(request, docs, per_page=DOCUMENTS_PER_PAGE) context = {'documents': paginated_docs, 'count': docs.count(), 'tag': tag_obj, 'tag_name': tag} return render(request, 'wiki/list/needs_review.html', context)
null
null
null
for review
codeqa
@block user agents@require GE Tdef needs review request tag None tag obj tag and get object or 404 Review Tag name tag or None docs Document objects filter for review locale request LANGUAGE CODE tag tag obj paginated docs paginate request docs per page DOCUMENTS PER PAGE context {'documents' paginated docs 'count' docs count 'tag' tag obj 'tag name' tag}return render request 'wiki/list/needs review html' context
null
null
null
null
Question: For what purpose did revisions flag ? Code: @block_user_agents @require_GET def needs_review(request, tag=None): tag_obj = ((tag and get_object_or_404(ReviewTag, name=tag)) or None) docs = Document.objects.filter_for_review(locale=request.LANGUAGE_CODE, tag=tag_obj) paginated_docs = paginate(request, docs, per_page=DOCUMENTS_PER_PAGE) context = {'documents': paginated_docs, 'count': docs.count(), 'tag': tag_obj, 'tag_name': tag} return render(request, 'wiki/list/needs_review.html', context)
null
null
null
What returns a geometry ?
def check_geom(result, func, cargs): if isinstance(result, (int, long)): result = c_void_p(result) if (not result): raise OGRException(('Invalid geometry pointer returned from "%s".' % func.__name__)) return result
null
null
null
a function
codeqa
def check geom result func cargs if isinstance result int long result c void p result if not result raise OGR Exception ' Invalidgeometrypointerreturnedfrom"%s" ' % func name return result
null
null
null
null
Question: What returns a geometry ? Code: def check_geom(result, func, cargs): if isinstance(result, (int, long)): result = c_void_p(result) if (not result): raise OGRException(('Invalid geometry pointer returned from "%s".' % func.__name__)) return result
null
null
null
What does a function return ?
def check_geom(result, func, cargs): if isinstance(result, (int, long)): result = c_void_p(result) if (not result): raise OGRException(('Invalid geometry pointer returned from "%s".' % func.__name__)) return result
null
null
null
a geometry
codeqa
def check geom result func cargs if isinstance result int long result c void p result if not result raise OGR Exception ' Invalidgeometrypointerreturnedfrom"%s" ' % func name return result
null
null
null
null
Question: What does a function return ? Code: def check_geom(result, func, cargs): if isinstance(result, (int, long)): result = c_void_p(result) if (not result): raise OGRException(('Invalid geometry pointer returned from "%s".' % func.__name__)) return result
null
null
null
What activates manual transaction control ?
def commit_manually(func): def _commit_manually(*args, **kw): try: enter_transaction_management() managed(True) return func(*args, **kw) finally: leave_transaction_management() return _commit_manually
null
null
null
decorator
codeqa
def commit manually func def commit manually *args **kw try enter transaction management managed True return func *args **kw finally leave transaction management return commit manually
null
null
null
null
Question: What activates manual transaction control ? Code: def commit_manually(func): def _commit_manually(*args, **kw): try: enter_transaction_management() managed(True) return func(*args, **kw) finally: leave_transaction_management() return _commit_manually
null
null
null
What does decorator activate ?
def commit_manually(func): def _commit_manually(*args, **kw): try: enter_transaction_management() managed(True) return func(*args, **kw) finally: leave_transaction_management() return _commit_manually
null
null
null
manual transaction control
codeqa
def commit manually func def commit manually *args **kw try enter transaction management managed True return func *args **kw finally leave transaction management return commit manually
null
null
null
null
Question: What does decorator activate ? Code: def commit_manually(func): def _commit_manually(*args, **kw): try: enter_transaction_management() managed(True) return func(*args, **kw) finally: leave_transaction_management() return _commit_manually
null
null
null
What does the code get from the contents of an exploration zip file ?
def get_exploration_components_from_zip(zip_file_contents): memfile = StringIO.StringIO() memfile.write(zip_file_contents) zf = zipfile.ZipFile(memfile, 'r') yaml_content = None assets_list = [] for filepath in zf.namelist(): if filepath.startswith('assets/'): assets_list.append('/'.join(filepath.split('/')[1:]), zf.read(filepath)) elif (yaml_content is not None): raise Exception('More than one non-asset file specified for zip file') elif (not filepath.endswith('.yaml')): raise Exception(('Found invalid non-asset file %s. There should only be a single file not in assets/, and it should have a .yaml suffix.' % filepath)) else: yaml_content = zf.read(filepath) if (yaml_content is None): raise Exception('No yaml file specified in zip file contents') return (yaml_content, assets_list)
null
null
null
the
codeqa
def get exploration components from zip zip file contents memfile String IO String IO memfile write zip file contents zf zipfile Zip File memfile 'r' yaml content Noneassets list []for filepath in zf namelist if filepath startswith 'assets/' assets list append '/' join filepath split '/' [1 ] zf read filepath elif yaml content is not None raise Exception ' Morethanonenon-assetfilespecifiedforzipfile' elif not filepath endswith ' yaml' raise Exception ' Foundinvalidnon-assetfile%s Thereshouldonlybeasinglefilenotinassets/ anditshouldhavea yamlsuffix ' % filepath else yaml content zf read filepath if yaml content is None raise Exception ' Noyamlfilespecifiedinzipfilecontents' return yaml content assets list
null
null
null
null
Question: What does the code get from the contents of an exploration zip file ? Code: def get_exploration_components_from_zip(zip_file_contents): memfile = StringIO.StringIO() memfile.write(zip_file_contents) zf = zipfile.ZipFile(memfile, 'r') yaml_content = None assets_list = [] for filepath in zf.namelist(): if filepath.startswith('assets/'): assets_list.append('/'.join(filepath.split('/')[1:]), zf.read(filepath)) elif (yaml_content is not None): raise Exception('More than one non-asset file specified for zip file') elif (not filepath.endswith('.yaml')): raise Exception(('Found invalid non-asset file %s. There should only be a single file not in assets/, and it should have a .yaml suffix.' % filepath)) else: yaml_content = zf.read(filepath) if (yaml_content is None): raise Exception('No yaml file specified in zip file contents') return (yaml_content, assets_list)
null
null
null
What does the code retrieve from a grid ?
def col_retrieve(fid, uid): url = build_url(RESOURCE, id=fid, route='col') params = make_params(uid=uid) return request('get', url, params=params)
null
null
null
a column
codeqa
def col retrieve fid uid url build url RESOURCE id fid route 'col' params make params uid uid return request 'get' url params params
null
null
null
null
Question: What does the code retrieve from a grid ? Code: def col_retrieve(fid, uid): url = build_url(RESOURCE, id=fid, route='col') params = make_params(uid=uid) return request('get', url, params=params)
null
null
null
What does the code return ?
def status(name, sig=None): if sig: return bool(__salt__['status.pid'](sig)) cmd = '{0} check {1}'.format(_cmd(), name) return (not __salt__['cmd.retcode'](cmd))
null
null
null
the status for a service
codeqa
def status name sig None if sig return bool salt ['status pid'] sig cmd '{ 0 }check{ 1 }' format cmd name return not salt ['cmd retcode'] cmd
null
null
null
null
Question: What does the code return ? Code: def status(name, sig=None): if sig: return bool(__salt__['status.pid'](sig)) cmd = '{0} check {1}'.format(_cmd(), name) return (not __salt__['cmd.retcode'](cmd))
null
null
null
What does the code make ?
def make_thumbnail(in_fname, out_fname, width, height): try: from PIL import Image except ImportError: import Image img = Image.open(in_fname) (width_in, height_in) = img.size scale_w = (width / float(width_in)) scale_h = (height / float(height_in)) if ((height_in * scale_w) <= height): scale = scale_w else: scale = scale_h width_sc = int(round((scale * width_in))) height_sc = int(round((scale * height_in))) img.thumbnail((width_sc, height_sc), Image.ANTIALIAS) thumb = Image.new('RGB', (width, height), (255, 255, 255)) pos_insert = (((width - width_sc) // 2), ((height - height_sc) // 2)) thumb.paste(img, pos_insert) thumb.save(out_fname)
null
null
null
a thumbnail with the same aspect ratio centered in an image with a given width and height
codeqa
def make thumbnail in fname out fname width height try from PIL import Imageexcept Import Error import Imageimg Image open in fname width in height in img sizescale w width / float width in scale h height / float height in if height in * scale w < height scale scale welse scale scale hwidth sc int round scale * width in height sc int round scale * height in img thumbnail width sc height sc Image ANTIALIAS thumb Image new 'RGB' width height 255 255 255 pos insert width - width sc // 2 height - height sc // 2 thumb paste img pos insert thumb save out fname
null
null
null
null
Question: What does the code make ? Code: def make_thumbnail(in_fname, out_fname, width, height): try: from PIL import Image except ImportError: import Image img = Image.open(in_fname) (width_in, height_in) = img.size scale_w = (width / float(width_in)) scale_h = (height / float(height_in)) if ((height_in * scale_w) <= height): scale = scale_w else: scale = scale_h width_sc = int(round((scale * width_in))) height_sc = int(round((scale * height_in))) img.thumbnail((width_sc, height_sc), Image.ANTIALIAS) thumb = Image.new('RGB', (width, height), (255, 255, 255)) pos_insert = (((width - width_sc) // 2), ((height - height_sc) // 2)) thumb.paste(img, pos_insert) thumb.save(out_fname)
null
null
null
What did the code set ?
def set_password(name, password): cmd = "dscl . -passwd /Users/{0} '{1}'".format(name, password) try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: if ('eDSUnknownNodeName' in exc.strerror): raise CommandExecutionError('User not found: {0}'.format(name)) raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror)) return True
null
null
null
the password for a named user
codeqa
def set password name password cmd "dscl -passwd/ Users/{ 0 }'{ 1 }'" format name password try salt utils mac utils execute return success cmd except Command Execution Error as exc if 'e DS Unknown Node Name' in exc strerror raise Command Execution Error ' Usernotfound {0 }' format name raise Command Execution Error ' Unknownerror {0 }' format exc strerror return True
null
null
null
null
Question: What did the code set ? Code: def set_password(name, password): cmd = "dscl . -passwd /Users/{0} '{1}'".format(name, password) try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: if ('eDSUnknownNodeName' in exc.strerror): raise CommandExecutionError('User not found: {0}'.format(name)) raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror)) return True
null
null
null
What does this plugin set ?
def description_setter(registry, xml_parent, data): descriptionsetter = XML.SubElement(xml_parent, 'hudson.plugins.descriptionsetter.DescriptionSetterBuilder') XML.SubElement(descriptionsetter, 'regexp').text = data.get('regexp', '') if ('description' in data): XML.SubElement(descriptionsetter, 'description').text = data['description']
null
null
null
the description for each build
codeqa
def description setter registry xml parent data descriptionsetter XML Sub Element xml parent 'hudson plugins descriptionsetter Description Setter Builder' XML Sub Element descriptionsetter 'regexp' text data get 'regexp' '' if 'description' in data XML Sub Element descriptionsetter 'description' text data['description']
null
null
null
null
Question: What does this plugin set ? Code: def description_setter(registry, xml_parent, data): descriptionsetter = XML.SubElement(xml_parent, 'hudson.plugins.descriptionsetter.DescriptionSetterBuilder') XML.SubElement(descriptionsetter, 'regexp').text = data.get('regexp', '') if ('description' in data): XML.SubElement(descriptionsetter, 'description').text = data['description']
null
null
null
What sets the description for each build ?
def description_setter(registry, xml_parent, data): descriptionsetter = XML.SubElement(xml_parent, 'hudson.plugins.descriptionsetter.DescriptionSetterBuilder') XML.SubElement(descriptionsetter, 'regexp').text = data.get('regexp', '') if ('description' in data): XML.SubElement(descriptionsetter, 'description').text = data['description']
null
null
null
this plugin
codeqa
def description setter registry xml parent data descriptionsetter XML Sub Element xml parent 'hudson plugins descriptionsetter Description Setter Builder' XML Sub Element descriptionsetter 'regexp' text data get 'regexp' '' if 'description' in data XML Sub Element descriptionsetter 'description' text data['description']
null
null
null
null
Question: What sets the description for each build ? Code: def description_setter(registry, xml_parent, data): descriptionsetter = XML.SubElement(xml_parent, 'hudson.plugins.descriptionsetter.DescriptionSetterBuilder') XML.SubElement(descriptionsetter, 'regexp').text = data.get('regexp', '') if ('description' in data): XML.SubElement(descriptionsetter, 'description').text = data['description']
null
null
null
How do a student enroll ?
def enroll_email(course_id, student_email, auto_enroll=False, email_students=False, email_params=None, language=None): previous_state = EmailEnrollmentState(course_id, student_email) enrollment_obj = None if previous_state.user: if CourseMode.is_white_label(course_id): course_mode = CourseMode.DEFAULT_SHOPPINGCART_MODE_SLUG else: course_mode = None if previous_state.enrollment: course_mode = previous_state.mode enrollment_obj = CourseEnrollment.enroll_by_email(student_email, course_id, course_mode) if email_students: email_params['message'] = 'enrolled_enroll' email_params['email_address'] = student_email email_params['full_name'] = previous_state.full_name send_mail_to_student(student_email, email_params, language=language) else: (cea, _) = CourseEnrollmentAllowed.objects.get_or_create(course_id=course_id, email=student_email) cea.auto_enroll = auto_enroll cea.save() if email_students: email_params['message'] = 'allowed_enroll' email_params['email_address'] = student_email send_mail_to_student(student_email, email_params, language=language) after_state = EmailEnrollmentState(course_id, student_email) return (previous_state, after_state, enrollment_obj)
null
null
null
by email
codeqa
def enroll email course id student email auto enroll False email students False email params None language None previous state Email Enrollment State course id student email enrollment obj Noneif previous state user if Course Mode is white label course id course mode Course Mode DEFAULT SHOPPINGCART MODE SLU Gelse course mode Noneif previous state enrollment course mode previous state modeenrollment obj Course Enrollment enroll by email student email course id course mode if email students email params['message'] 'enrolled enroll'email params['email address'] student emailemail params['full name'] previous state full namesend mail to student student email email params language language else cea Course Enrollment Allowed objects get or create course id course id email student email cea auto enroll auto enrollcea save if email students email params['message'] 'allowed enroll'email params['email address'] student emailsend mail to student student email email params language language after state Email Enrollment State course id student email return previous state after state enrollment obj
null
null
null
null
Question: How do a student enroll ? Code: def enroll_email(course_id, student_email, auto_enroll=False, email_students=False, email_params=None, language=None): previous_state = EmailEnrollmentState(course_id, student_email) enrollment_obj = None if previous_state.user: if CourseMode.is_white_label(course_id): course_mode = CourseMode.DEFAULT_SHOPPINGCART_MODE_SLUG else: course_mode = None if previous_state.enrollment: course_mode = previous_state.mode enrollment_obj = CourseEnrollment.enroll_by_email(student_email, course_id, course_mode) if email_students: email_params['message'] = 'enrolled_enroll' email_params['email_address'] = student_email email_params['full_name'] = previous_state.full_name send_mail_to_student(student_email, email_params, language=language) else: (cea, _) = CourseEnrollmentAllowed.objects.get_or_create(course_id=course_id, email=student_email) cea.auto_enroll = auto_enroll cea.save() if email_students: email_params['message'] = 'allowed_enroll' email_params['email_address'] = student_email send_mail_to_student(student_email, email_params, language=language) after_state = EmailEnrollmentState(course_id, student_email) return (previous_state, after_state, enrollment_obj)
null
null
null
What does the code get ?
def getShortestUniqueSettingName(settingName, settings): for length in xrange(3, len(settingName)): numberOfEquals = 0 shortName = settingName[:length] for setting in settings: if (setting.name[:length] == shortName): numberOfEquals += 1 if (numberOfEquals < 2): return shortName.lower() return settingName.lower()
null
null
null
the shortest unique name in the settings
codeqa
def get Shortest Unique Setting Name setting Name settings for length in xrange 3 len setting Name number Of Equals 0short Name setting Name[ length]for setting in settings if setting name[ length] short Name number Of Equals + 1if number Of Equals < 2 return short Name lower return setting Name lower
null
null
null
null
Question: What does the code get ? Code: def getShortestUniqueSettingName(settingName, settings): for length in xrange(3, len(settingName)): numberOfEquals = 0 shortName = settingName[:length] for setting in settings: if (setting.name[:length] == shortName): numberOfEquals += 1 if (numberOfEquals < 2): return shortName.lower() return settingName.lower()
null
null
null
How are characters mapped to nothing ?
def b1_mapping(char): return (u'' if stringprep.in_table_b1(char) else None)
null
null
null
commonly
codeqa
def b1 mapping char return u'' if stringprep in table b1 char else None
null
null
null
null
Question: How are characters mapped to nothing ? Code: def b1_mapping(char): return (u'' if stringprep.in_table_b1(char) else None)
null
null
null
How do a serial number return ?
def _new_serial(ca_name): hashnum = int(binascii.hexlify('{0}_{1}'.format(_microtime(), os.urandom(5))), 16) log.debug('Hashnum: {0}'.format(hashnum)) cachedir = __opts__['cachedir'] log.debug('cachedir: {0}'.format(cachedir)) serial_file = '{0}/{1}.serial'.format(cachedir, ca_name) if (not os.path.exists(cachedir)): os.makedirs(cachedir) if (not os.path.exists(serial_file)): fd = salt.utils.fopen(serial_file, 'w') else: fd = salt.utils.fopen(serial_file, 'a+') with fd as ofile: ofile.write(str(hashnum)) return hashnum
null
null
null
in hex
codeqa
def new serial ca name hashnum int binascii hexlify '{ 0 } {1 }' format microtime os urandom 5 16 log debug ' Hashnum {0 }' format hashnum cachedir opts ['cachedir']log debug 'cachedir {0 }' format cachedir serial file '{ 0 }/{ 1 } serial' format cachedir ca name if not os path exists cachedir os makedirs cachedir if not os path exists serial file fd salt utils fopen serial file 'w' else fd salt utils fopen serial file 'a+' with fd as ofile ofile write str hashnum return hashnum
null
null
null
null
Question: How do a serial number return ? Code: def _new_serial(ca_name): hashnum = int(binascii.hexlify('{0}_{1}'.format(_microtime(), os.urandom(5))), 16) log.debug('Hashnum: {0}'.format(hashnum)) cachedir = __opts__['cachedir'] log.debug('cachedir: {0}'.format(cachedir)) serial_file = '{0}/{1}.serial'.format(cachedir, ca_name) if (not os.path.exists(cachedir)): os.makedirs(cachedir) if (not os.path.exists(serial_file)): fd = salt.utils.fopen(serial_file, 'w') else: fd = salt.utils.fopen(serial_file, 'a+') with fd as ofile: ofile.write(str(hashnum)) return hashnum
null
null
null
What does the code create ?
def technical_500_response(request, exc_type, exc_value, tb): reporter = ExceptionReporter(request, exc_type, exc_value, tb) if request.is_ajax(): text = reporter.get_traceback_text() return HttpResponseServerError(text, content_type=u'text/plain') else: html = reporter.get_traceback_html() return HttpResponseServerError(html, content_type=u'text/html')
null
null
null
a technical server error response
codeqa
def technical 500 response request exc type exc value tb reporter Exception Reporter request exc type exc value tb if request is ajax text reporter get traceback text return Http Response Server Error text content type u'text/plain' else html reporter get traceback html return Http Response Server Error html content type u'text/html'
null
null
null
null
Question: What does the code create ? Code: def technical_500_response(request, exc_type, exc_value, tb): reporter = ExceptionReporter(request, exc_type, exc_value, tb) if request.is_ajax(): text = reporter.get_traceback_text() return HttpResponseServerError(text, content_type=u'text/plain') else: html = reporter.get_traceback_html() return HttpResponseServerError(html, content_type=u'text/html')
null
null
null
What does the code send expecting no reply ?
def cast(conf, *args, **kwargs): _multi_send(_cast, *args, **kwargs)
null
null
null
a message
codeqa
def cast conf *args **kwargs multi send cast *args **kwargs
null
null
null
null
Question: What does the code send expecting no reply ? Code: def cast(conf, *args, **kwargs): _multi_send(_cast, *args, **kwargs)
null
null
null
What is expecting no reply ?
def cast(conf, *args, **kwargs): _multi_send(_cast, *args, **kwargs)
null
null
null
a message
codeqa
def cast conf *args **kwargs multi send cast *args **kwargs
null
null
null
null
Question: What is expecting no reply ? Code: def cast(conf, *args, **kwargs): _multi_send(_cast, *args, **kwargs)
null
null
null
What does the code convert to hexadecimal notation ?
def ip4_hex(arg): numbers = list(map(int, arg.split('.'))) return '{:02x}{:02x}{:02x}{:02x}'.format(*numbers)
null
null
null
an ipv4 address
codeqa
def ip 4 hex arg numbers list map int arg split ' ' return '{ 02 x}{ 02 x}{ 02 x}{ 02 x}' format *numbers
null
null
null
null
Question: What does the code convert to hexadecimal notation ? Code: def ip4_hex(arg): numbers = list(map(int, arg.split('.'))) return '{:02x}{:02x}{:02x}{:02x}'.format(*numbers)
null
null
null
What does the code execute ?
def runCommand(args): process = Popen(args, stdout=PIPE, stderr=STDOUT) stdout = process.stdout.read() exitCode = process.wait() if (exitCode < 0): raise CommandFailed(None, (- exitCode), stdout) elif (exitCode > 0): raise CommandFailed(exitCode, None, stdout) return stdout
null
null
null
a vector of arguments
codeqa
def run Command args process Popen args stdout PIPE stderr STDOUT stdout process stdout read exit Code process wait if exit Code < 0 raise Command Failed None - exit Code stdout elif exit Code > 0 raise Command Failed exit Code None stdout return stdout
null
null
null
null
Question: What does the code execute ? Code: def runCommand(args): process = Popen(args, stdout=PIPE, stderr=STDOUT) stdout = process.stdout.read() exitCode = process.wait() if (exitCode < 0): raise CommandFailed(None, (- exitCode), stdout) elif (exitCode > 0): raise CommandFailed(exitCode, None, stdout) return stdout
null
null
null
What does the code get ?
def get_attribute(obj, name): try: attribute = getattr(obj, name) except AttributeError: raise unittest.SkipTest(('module %s has no attribute %s' % (obj.__name__, name))) else: return attribute
null
null
null
an attribute
codeqa
def get attribute obj name try attribute getattr obj name except Attribute Error raise unittest Skip Test 'module%shasnoattribute%s' % obj name name else return attribute
null
null
null
null
Question: What does the code get ? Code: def get_attribute(obj, name): try: attribute = getattr(obj, name) except AttributeError: raise unittest.SkipTest(('module %s has no attribute %s' % (obj.__name__, name))) else: return attribute
null
null
null
When do the current idle delay setting return code ?
def getIdleDelay(**kwargs): _gsession = _GSettings(user=kwargs.get('user'), schema='org.gnome.desktop.session', key='idle-delay') return _gsession._get()
null
null
null
in seconds
codeqa
def get Idle Delay **kwargs gsession G Settings user kwargs get 'user' schema 'org gnome desktop session' key 'idle-delay' return gsession get
null
null
null
null
Question: When do the current idle delay setting return code ? Code: def getIdleDelay(**kwargs): _gsession = _GSettings(user=kwargs.get('user'), schema='org.gnome.desktop.session', key='idle-delay') return _gsession._get()
null
null
null
What does the code ensure ?
def restarted(manager, containers, count, name): containers.refresh() for container in manager.get_differing_containers(): manager.stop_containers([container]) manager.remove_containers([container]) containers.refresh() manager.restart_containers(containers.running) started(manager, containers, count, name)
null
null
null
that exactly count matching containers exist and are running
codeqa
def restarted manager containers count name containers refresh for container in manager get differing containers manager stop containers [container] manager remove containers [container] containers refresh manager restart containers containers running started manager containers count name
null
null
null
null
Question: What does the code ensure ? Code: def restarted(manager, containers, count, name): containers.refresh() for container in manager.get_differing_containers(): manager.stop_containers([container]) manager.remove_containers([container]) containers.refresh() manager.restart_containers(containers.running) started(manager, containers, count, name)
null
null
null
What does the code validate ?
def parse_and_validate_reply_to_address(address): (recipient, sep, domain) = address.partition('@') if ((not sep) or (not recipient) or (domain != g.modmail_email_domain)): return (main, sep, remainder) = recipient.partition('+') if ((not sep) or (not main) or (main != 'zendeskreply')): return try: (email_id, email_mac) = remainder.split('-') except ValueError: return expected_mac = hmac.new(g.secrets['modmail_email_secret'], email_id, hashlib.sha256).hexdigest() if (not constant_time_compare(expected_mac, email_mac)): return message_id36 = email_id return message_id36
null
null
null
the address
codeqa
def parse and validate reply to address address recipient sep domain address partition '@' if not sep or not recipient or domain g modmail email domain return main sep remainder recipient partition '+' if not sep or not main or main 'zendeskreply' returntry email id email mac remainder split '-' except Value Error returnexpected mac hmac new g secrets['modmail email secret'] email id hashlib sha 256 hexdigest if not constant time compare expected mac email mac returnmessage id 36 email idreturn message id 36
null
null
null
null
Question: What does the code validate ? Code: def parse_and_validate_reply_to_address(address): (recipient, sep, domain) = address.partition('@') if ((not sep) or (not recipient) or (domain != g.modmail_email_domain)): return (main, sep, remainder) = recipient.partition('+') if ((not sep) or (not main) or (main != 'zendeskreply')): return try: (email_id, email_mac) = remainder.split('-') except ValueError: return expected_mac = hmac.new(g.secrets['modmail_email_secret'], email_id, hashlib.sha256).hexdigest() if (not constant_time_compare(expected_mac, email_mac)): return message_id36 = email_id return message_id36
null
null
null
What does the code return ?
def parse_and_validate_reply_to_address(address): (recipient, sep, domain) = address.partition('@') if ((not sep) or (not recipient) or (domain != g.modmail_email_domain)): return (main, sep, remainder) = recipient.partition('+') if ((not sep) or (not main) or (main != 'zendeskreply')): return try: (email_id, email_mac) = remainder.split('-') except ValueError: return expected_mac = hmac.new(g.secrets['modmail_email_secret'], email_id, hashlib.sha256).hexdigest() if (not constant_time_compare(expected_mac, email_mac)): return message_id36 = email_id return message_id36
null
null
null
the message i d
codeqa
def parse and validate reply to address address recipient sep domain address partition '@' if not sep or not recipient or domain g modmail email domain return main sep remainder recipient partition '+' if not sep or not main or main 'zendeskreply' returntry email id email mac remainder split '-' except Value Error returnexpected mac hmac new g secrets['modmail email secret'] email id hashlib sha 256 hexdigest if not constant time compare expected mac email mac returnmessage id 36 email idreturn message id 36
null
null
null
null
Question: What does the code return ? Code: def parse_and_validate_reply_to_address(address): (recipient, sep, domain) = address.partition('@') if ((not sep) or (not recipient) or (domain != g.modmail_email_domain)): return (main, sep, remainder) = recipient.partition('+') if ((not sep) or (not main) or (main != 'zendeskreply')): return try: (email_id, email_mac) = remainder.split('-') except ValueError: return expected_mac = hmac.new(g.secrets['modmail_email_secret'], email_id, hashlib.sha256).hexdigest() if (not constant_time_compare(expected_mac, email_mac)): return message_id36 = email_id return message_id36
null
null
null
What does the code open ?
def config_edit(): path = config.user_config_path() editor = util.editor_command() try: if (not os.path.isfile(path)): open(path, 'w+').close() util.interactive_open([path], editor) except OSError as exc: message = u'Could not edit configuration: {0}'.format(exc) if (not editor): message += u'. Please set the EDITOR environment variable' raise ui.UserError(message)
null
null
null
a program to edit the user configuration
codeqa
def config edit path config user config path editor util editor command try if not os path isfile path open path 'w+' close util interactive open [path] editor except OS Error as exc message u' Couldnoteditconfiguration {0 }' format exc if not editor message + u' Pleasesetthe EDITO Renvironmentvariable'raise ui User Error message
null
null
null
null
Question: What does the code open ? Code: def config_edit(): path = config.user_config_path() editor = util.editor_command() try: if (not os.path.isfile(path)): open(path, 'w+').close() util.interactive_open([path], editor) except OSError as exc: message = u'Could not edit configuration: {0}'.format(exc) if (not editor): message += u'. Please set the EDITOR environment variable' raise ui.UserError(message)
null
null
null
What edits the user configuration ?
def config_edit(): path = config.user_config_path() editor = util.editor_command() try: if (not os.path.isfile(path)): open(path, 'w+').close() util.interactive_open([path], editor) except OSError as exc: message = u'Could not edit configuration: {0}'.format(exc) if (not editor): message += u'. Please set the EDITOR environment variable' raise ui.UserError(message)
null
null
null
a
codeqa
def config edit path config user config path editor util editor command try if not os path isfile path open path 'w+' close util interactive open [path] editor except OS Error as exc message u' Couldnoteditconfiguration {0 }' format exc if not editor message + u' Pleasesetthe EDITO Renvironmentvariable'raise ui User Error message
null
null
null
null
Question: What edits the user configuration ? Code: def config_edit(): path = config.user_config_path() editor = util.editor_command() try: if (not os.path.isfile(path)): open(path, 'w+').close() util.interactive_open([path], editor) except OSError as exc: message = u'Could not edit configuration: {0}'.format(exc) if (not editor): message += u'. Please set the EDITOR environment variable' raise ui.UserError(message)
null
null
null
How are signals handled ?
def start_http_server(listen_port): _verify_environment() logging.info("HTTP server is starting, port: {}, test-UUID: '{}'".format(listen_port, os.environ[TEST_UUID_VARNAME])) test_server = ThreadingSimpleServer(('', listen_port), TestHTTPRequestHandler) def sigterm_handler(_signo, _stack_frame): test_server.server_close() logging.info('HTTP server is terminating') sys.exit(0) signal.signal(signal.SIGTERM, sigterm_handler) signal.signal(signal.SIGINT, sigterm_handler) test_server.serve_forever()
null
null
null
properly
codeqa
def start http server listen port verify environment logging info "HTT Pserverisstarting port {} test-UUID '{}'" format listen port os environ[TEST UUID VARNAME] test server Threading Simple Server '' listen port Test HTTP Request Handler def sigterm handler signo stack frame test server server close logging info 'HTT Pserveristerminating' sys exit 0 signal signal signal SIGTERM sigterm handler signal signal signal SIGINT sigterm handler test server serve forever
null
null
null
null
Question: How are signals handled ? Code: def start_http_server(listen_port): _verify_environment() logging.info("HTTP server is starting, port: {}, test-UUID: '{}'".format(listen_port, os.environ[TEST_UUID_VARNAME])) test_server = ThreadingSimpleServer(('', listen_port), TestHTTPRequestHandler) def sigterm_handler(_signo, _stack_frame): test_server.server_close() logging.info('HTTP server is terminating') sys.exit(0) signal.signal(signal.SIGTERM, sigterm_handler) signal.signal(signal.SIGINT, sigterm_handler) test_server.serve_forever()
null
null
null
What does the code return ?
def version(): return uname()[3]
null
null
null
the systems release version
codeqa
def version return uname [3 ]
null
null
null
null
Question: What does the code return ? Code: def version(): return uname()[3]
null
null
null
What does all the rules from the environment compile ?
def compile_rules(environment): e = re.escape rules = [(len(environment.comment_start_string), 'comment', e(environment.comment_start_string)), (len(environment.block_start_string), 'block', e(environment.block_start_string)), (len(environment.variable_start_string), 'variable', e(environment.variable_start_string))] if (environment.line_statement_prefix is not None): rules.append((len(environment.line_statement_prefix), 'linestatement', ('^\\s*' + e(environment.line_statement_prefix)))) if (environment.line_comment_prefix is not None): rules.append((len(environment.line_comment_prefix), 'linecomment', ('(?:^|(?<=\\S))[^\\S\\r\\n]*' + e(environment.line_comment_prefix)))) return [x[1:] for x in sorted(rules, reverse=True)]
null
null
null
into a list of rules
codeqa
def compile rules environment e re escaperules [ len environment comment start string 'comment' e environment comment start string len environment block start string 'block' e environment block start string len environment variable start string 'variable' e environment variable start string ]if environment line statement prefix is not None rules append len environment line statement prefix 'linestatement' '^\\s*' + e environment line statement prefix if environment line comment prefix is not None rules append len environment line comment prefix 'linecomment' ' ? ^ ?< \\S [^\\S\\r\\n]*' + e environment line comment prefix return [x[ 1 ] for x in sorted rules reverse True ]
null
null
null
null
Question: What does all the rules from the environment compile ? Code: def compile_rules(environment): e = re.escape rules = [(len(environment.comment_start_string), 'comment', e(environment.comment_start_string)), (len(environment.block_start_string), 'block', e(environment.block_start_string)), (len(environment.variable_start_string), 'variable', e(environment.variable_start_string))] if (environment.line_statement_prefix is not None): rules.append((len(environment.line_statement_prefix), 'linestatement', ('^\\s*' + e(environment.line_statement_prefix)))) if (environment.line_comment_prefix is not None): rules.append((len(environment.line_comment_prefix), 'linecomment', ('(?:^|(?<=\\S))[^\\S\\r\\n]*' + e(environment.line_comment_prefix)))) return [x[1:] for x in sorted(rules, reverse=True)]
null
null
null
What compiles into a list of rules ?
def compile_rules(environment): e = re.escape rules = [(len(environment.comment_start_string), 'comment', e(environment.comment_start_string)), (len(environment.block_start_string), 'block', e(environment.block_start_string)), (len(environment.variable_start_string), 'variable', e(environment.variable_start_string))] if (environment.line_statement_prefix is not None): rules.append((len(environment.line_statement_prefix), 'linestatement', ('^\\s*' + e(environment.line_statement_prefix)))) if (environment.line_comment_prefix is not None): rules.append((len(environment.line_comment_prefix), 'linecomment', ('(?:^|(?<=\\S))[^\\S\\r\\n]*' + e(environment.line_comment_prefix)))) return [x[1:] for x in sorted(rules, reverse=True)]
null
null
null
all the rules from the environment
codeqa
def compile rules environment e re escaperules [ len environment comment start string 'comment' e environment comment start string len environment block start string 'block' e environment block start string len environment variable start string 'variable' e environment variable start string ]if environment line statement prefix is not None rules append len environment line statement prefix 'linestatement' '^\\s*' + e environment line statement prefix if environment line comment prefix is not None rules append len environment line comment prefix 'linecomment' ' ? ^ ?< \\S [^\\S\\r\\n]*' + e environment line comment prefix return [x[ 1 ] for x in sorted rules reverse True ]
null
null
null
null
Question: What compiles into a list of rules ? Code: def compile_rules(environment): e = re.escape rules = [(len(environment.comment_start_string), 'comment', e(environment.comment_start_string)), (len(environment.block_start_string), 'block', e(environment.block_start_string)), (len(environment.variable_start_string), 'variable', e(environment.variable_start_string))] if (environment.line_statement_prefix is not None): rules.append((len(environment.line_statement_prefix), 'linestatement', ('^\\s*' + e(environment.line_statement_prefix)))) if (environment.line_comment_prefix is not None): rules.append((len(environment.line_comment_prefix), 'linecomment', ('(?:^|(?<=\\S))[^\\S\\r\\n]*' + e(environment.line_comment_prefix)))) return [x[1:] for x in sorted(rules, reverse=True)]
null
null
null
What does the code make ?
def blend_palette(colors, n_colors=6, as_cmap=False): name = '-'.join(map(str, colors)) pal = mpl.colors.LinearSegmentedColormap.from_list(name, colors) if (not as_cmap): pal = pal(np.linspace(0, 1, n_colors)) return pal
null
null
null
a palette that blends between a list of colors
codeqa
def blend palette colors n colors 6 as cmap False name '-' join map str colors pal mpl colors Linear Segmented Colormap from list name colors if not as cmap pal pal np linspace 0 1 n colors return pal
null
null
null
null
Question: What does the code make ? Code: def blend_palette(colors, n_colors=6, as_cmap=False): name = '-'.join(map(str, colors)) pal = mpl.colors.LinearSegmentedColormap.from_list(name, colors) if (not as_cmap): pal = pal(np.linspace(0, 1, n_colors)) return pal
null
null
null
What did the code set ?
def inject_coursetalk_keys_into_context(context, course_key): show_coursetalk_widget = models.CourseTalkWidgetConfiguration.is_enabled() if show_coursetalk_widget: context[u'show_coursetalk_widget'] = True context[u'platform_key'] = models.CourseTalkWidgetConfiguration.get_platform_key() context[u'course_review_key'] = get_coursetalk_course_key(course_key)
null
null
null
params
codeqa
def inject coursetalk keys into context context course key show coursetalk widget models Course Talk Widget Configuration is enabled if show coursetalk widget context[u'show coursetalk widget'] Truecontext[u'platform key'] models Course Talk Widget Configuration get platform key context[u'course review key'] get coursetalk course key course key
null
null
null
null
Question: What did the code set ? Code: def inject_coursetalk_keys_into_context(context, course_key): show_coursetalk_widget = models.CourseTalkWidgetConfiguration.is_enabled() if show_coursetalk_widget: context[u'show_coursetalk_widget'] = True context[u'platform_key'] = models.CourseTalkWidgetConfiguration.get_platform_key() context[u'course_review_key'] = get_coursetalk_course_key(course_key)
null
null
null
How do a module import into a package ?
def _import_module(importer, module_name, package): if (module_name in sys.modules): return sys.modules[module_name] loader = importer.find_module(module_name) if (loader is None): return None module = loader.load_module(module_name) local_name = module_name.partition((package.__name__ + '.'))[2] module_components = local_name.split('.') parent = six.moves.reduce(getattr, module_components[:(-1)], package) setattr(parent, module_components[(-1)], module) return module
null
null
null
dynamically
codeqa
def import module importer module name package if module name in sys modules return sys modules[module name]loader importer find module module name if loader is None return Nonemodule loader load module module name local name module name partition package name + ' ' [2 ]module components local name split ' ' parent six moves reduce getattr module components[ -1 ] package setattr parent module components[ -1 ] module return module
null
null
null
null
Question: How do a module import into a package ? Code: def _import_module(importer, module_name, package): if (module_name in sys.modules): return sys.modules[module_name] loader = importer.find_module(module_name) if (loader is None): return None module = loader.load_module(module_name) local_name = module_name.partition((package.__name__ + '.'))[2] module_components = local_name.split('.') parent = six.moves.reduce(getattr, module_components[:(-1)], package) setattr(parent, module_components[(-1)], module) return module
null
null
null
How should the given attribute be loaded ?
@loader_option() def joinedload(loadopt, attr, innerjoin=None): loader = loadopt.set_relationship_strategy(attr, {'lazy': 'joined'}) if (innerjoin is not None): loader.local_opts['innerjoin'] = innerjoin return loader
null
null
null
using joined eager loading
codeqa
@loader option def joinedload loadopt attr innerjoin None loader loadopt set relationship strategy attr {'lazy' 'joined'} if innerjoin is not None loader local opts['innerjoin'] innerjoinreturn loader
null
null
null
null
Question: How should the given attribute be loaded ? Code: @loader_option() def joinedload(loadopt, attr, innerjoin=None): loader = loadopt.set_relationship_strategy(attr, {'lazy': 'joined'}) if (innerjoin is not None): loader.local_opts['innerjoin'] = innerjoin return loader
null
null
null
What does the code get ?
def getVector3Path(complexPath, z=0.0): vector3Path = [] for complexPoint in complexPath: vector3Path.append(Vector3(complexPoint.real, complexPoint.imag)) return vector3Path
null
null
null
the vector3 path from the complex path
codeqa
def get Vector 3 Path complex Path z 0 0 vector 3 Path []for complex Point in complex Path vector 3 Path append Vector 3 complex Point real complex Point imag return vector 3 Path
null
null
null
null
Question: What does the code get ? Code: def getVector3Path(complexPath, z=0.0): vector3Path = [] for complexPoint in complexPath: vector3Path.append(Vector3(complexPoint.real, complexPoint.imag)) return vector3Path
null
null
null
What does the code get ?
def getNewRepository(): return ChamberRepository()
null
null
null
new repository
codeqa
def get New Repository return Chamber Repository
null
null
null
null
Question: What does the code get ? Code: def getNewRepository(): return ChamberRepository()
null
null
null
What does the code update ?
def update_item(name, id_, field=None, value=None, postdata=None): if (field and value): if postdata: raise SaltInvocationError('Either a field and a value, or a chunk of POST data, may be specified, but not both.') postdata = {name.title(): {field: value}} if (postdata is None): raise SaltInvocationError('Either a field and a value, or a chunk of POST data must be specified.') (status, result) = _query(action=name, command=id_, method='POST', data=json.dumps(postdata)) return result
null
null
null
an item
codeqa
def update item name id field None value None postdata None if field and value if postdata raise Salt Invocation Error ' Eitherafieldandavalue orachunkof POS Tdata maybespecified butnotboth ' postdata {name title {field value}}if postdata is None raise Salt Invocation Error ' Eitherafieldandavalue orachunkof POS Tdatamustbespecified ' status result query action name command id method 'POST' data json dumps postdata return result
null
null
null
null
Question: What does the code update ? Code: def update_item(name, id_, field=None, value=None, postdata=None): if (field and value): if postdata: raise SaltInvocationError('Either a field and a value, or a chunk of POST data, may be specified, but not both.') postdata = {name.title(): {field: value}} if (postdata is None): raise SaltInvocationError('Either a field and a value, or a chunk of POST data must be specified.') (status, result) = _query(action=name, command=id_, method='POST', data=json.dumps(postdata)) return result
null
null
null
What is containing the new value for variable ?
def set_makeopts(value): return set_var('MAKEOPTS', value)
null
null
null
a dict
codeqa
def set makeopts value return set var 'MAKEOPTS' value
null
null
null
null
Question: What is containing the new value for variable ? Code: def set_makeopts(value): return set_var('MAKEOPTS', value)
null
null
null
What does the code convert to a number field ?
def itn(n, digits=8, format=DEFAULT_FORMAT): if (0 <= n < (8 ** (digits - 1))): s = (('%0*o' % ((digits - 1), n)).encode('ascii') + NUL) else: if ((format != GNU_FORMAT) or (n >= (256 ** (digits - 1)))): raise ValueError('overflow in number field') if (n < 0): n = struct.unpack('L', struct.pack('l', n))[0] s = bytearray() for i in range((digits - 1)): s.insert(0, (n & 255)) n >>= 8 s.insert(0, 128) return s
null
null
null
a python number
codeqa
def itn n digits 8 format DEFAULT FORMAT if 0 < n < 8 ** digits - 1 s '% 0 *o' % digits - 1 n encode 'ascii' + NUL else if format GNU FORMAT or n > 256 ** digits - 1 raise Value Error 'overflowinnumberfield' if n < 0 n struct unpack 'L' struct pack 'l' n [0 ]s bytearray for i in range digits - 1 s insert 0 n & 255 n >> 8s insert 0 128 return s
null
null
null
null
Question: What does the code convert to a number field ? Code: def itn(n, digits=8, format=DEFAULT_FORMAT): if (0 <= n < (8 ** (digits - 1))): s = (('%0*o' % ((digits - 1), n)).encode('ascii') + NUL) else: if ((format != GNU_FORMAT) or (n >= (256 ** (digits - 1)))): raise ValueError('overflow in number field') if (n < 0): n = struct.unpack('L', struct.pack('l', n))[0] s = bytearray() for i in range((digits - 1)): s.insert(0, (n & 255)) n >>= 8 s.insert(0, 128) return s
null
null
null
Where did the tokens match ?
def matchPreviousLiteral(expr): rep = Forward() def copyTokenToRepeater(s, l, t): if t: if (len(t) == 1): (rep << t[0]) else: tflat = _flatten(t.asList()) (rep << And((Literal(tt) for tt in tflat))) else: (rep << Empty()) expr.addParseAction(copyTokenToRepeater, callDuringTry=True) rep.setName(('(prev) ' + _ustr(expr))) return rep
null
null
null
in a previous expression
codeqa
def match Previous Literal expr rep Forward def copy Token To Repeater s l t if t if len t 1 rep << t[ 0 ] else tflat flatten t as List rep << And Literal tt for tt in tflat else rep << Empty expr add Parse Action copy Token To Repeater call During Try True rep set Name ' prev ' + ustr expr return rep
null
null
null
null
Question: Where did the tokens match ? Code: def matchPreviousLiteral(expr): rep = Forward() def copyTokenToRepeater(s, l, t): if t: if (len(t) == 1): (rep << t[0]) else: tflat = _flatten(t.asList()) (rep << And((Literal(tt) for tt in tflat))) else: (rep << Empty()) expr.addParseAction(copyTokenToRepeater, callDuringTry=True) rep.setName(('(prev) ' + _ustr(expr))) return rep
null
null
null
How is an expression defined from the tokens matched in a previous expression ?
def matchPreviousLiteral(expr): rep = Forward() def copyTokenToRepeater(s, l, t): if t: if (len(t) == 1): (rep << t[0]) else: tflat = _flatten(t.asList()) (rep << And((Literal(tt) for tt in tflat))) else: (rep << Empty()) expr.addParseAction(copyTokenToRepeater, callDuringTry=True) rep.setName(('(prev) ' + _ustr(expr))) return rep
null
null
null
indirectly
codeqa
def match Previous Literal expr rep Forward def copy Token To Repeater s l t if t if len t 1 rep << t[ 0 ] else tflat flatten t as List rep << And Literal tt for tt in tflat else rep << Empty expr add Parse Action copy Token To Repeater call During Try True rep set Name ' prev ' + ustr expr return rep
null
null
null
null
Question: How is an expression defined from the tokens matched in a previous expression ? Code: def matchPreviousLiteral(expr): rep = Forward() def copyTokenToRepeater(s, l, t): if t: if (len(t) == 1): (rep << t[0]) else: tflat = _flatten(t.asList()) (rep << And((Literal(tt) for tt in tflat))) else: (rep << Empty()) expr.addParseAction(copyTokenToRepeater, callDuringTry=True) rep.setName(('(prev) ' + _ustr(expr))) return rep
null
null
null
What matched in a previous expression ?
def matchPreviousLiteral(expr): rep = Forward() def copyTokenToRepeater(s, l, t): if t: if (len(t) == 1): (rep << t[0]) else: tflat = _flatten(t.asList()) (rep << And((Literal(tt) for tt in tflat))) else: (rep << Empty()) expr.addParseAction(copyTokenToRepeater, callDuringTry=True) rep.setName(('(prev) ' + _ustr(expr))) return rep
null
null
null
the tokens
codeqa
def match Previous Literal expr rep Forward def copy Token To Repeater s l t if t if len t 1 rep << t[ 0 ] else tflat flatten t as List rep << And Literal tt for tt in tflat else rep << Empty expr add Parse Action copy Token To Repeater call During Try True rep set Name ' prev ' + ustr expr return rep
null
null
null
null
Question: What matched in a previous expression ? Code: def matchPreviousLiteral(expr): rep = Forward() def copyTokenToRepeater(s, l, t): if t: if (len(t) == 1): (rep << t[0]) else: tflat = _flatten(t.asList()) (rep << And((Literal(tt) for tt in tflat))) else: (rep << Empty()) expr.addParseAction(copyTokenToRepeater, callDuringTry=True) rep.setName(('(prev) ' + _ustr(expr))) return rep
null
null
null
Till when is an instance booting ?
def _node_is_booting(instance): try: instance.update() except EC2ResponseError as e: _check_response_error(e, u'flocker:provision:aws:node_is_booting:retry') Message.new(message_type=u'flocker:provision:aws:node_is_booting:update', instance_state=instance.state, ip_address=instance.ip_address).write() return ((instance.state == u'pending') or (instance.state == u'rebooting') or ((instance.state == u'running') and (instance.ip_address is None)))
null
null
null
still
codeqa
def node is booting instance try instance update except EC 2 Response Error as e check response error e u'flocker provision aws node is booting retry' Message new message type u'flocker provision aws node is booting update' instance state instance state ip address instance ip address write return instance state u'pending' or instance state u'rebooting' or instance state u'running' and instance ip address is None
null
null
null
null
Question: Till when is an instance booting ? Code: def _node_is_booting(instance): try: instance.update() except EC2ResponseError as e: _check_response_error(e, u'flocker:provision:aws:node_is_booting:retry') Message.new(message_type=u'flocker:provision:aws:node_is_booting:update', instance_state=instance.state, ip_address=instance.ip_address).write() return ((instance.state == u'pending') or (instance.state == u'rebooting') or ((instance.state == u'running') and (instance.ip_address is None)))
null
null
null
What does the code get from the translators in the import plugins folder ?
def getGNUTranslatorFilesUnmodified(): return archive.getFilesWithFileTypesWithoutWords(getImportPluginFileNames())
null
null
null
the file types
codeqa
def get GNU Translator Files Unmodified return archive get Files With File Types Without Words get Import Plugin File Names
null
null
null
null
Question: What does the code get from the translators in the import plugins folder ? Code: def getGNUTranslatorFilesUnmodified(): return archive.getFilesWithFileTypesWithoutWords(getImportPluginFileNames())
null
null
null
What does the code convert to an absolute coordinate string ?
def absolute_coordinate(coord_string): m = ABSOLUTE_RE.match(coord_string.upper()) if m: parts = m.groups() if all(parts[(-2):]): return ('$%s$%s:$%s$%s' % (parts[0], parts[1], parts[3], parts[4])) else: return ('$%s$%s' % (parts[0], parts[1])) else: return coord_string
null
null
null
a coordinate
codeqa
def absolute coordinate coord string m ABSOLUTE RE match coord string upper if m parts m groups if all parts[ -2 ] return '$%s$%s $%s$%s' % parts[ 0 ] parts[ 1 ] parts[ 3 ] parts[ 4 ] else return '$%s$%s' % parts[ 0 ] parts[ 1 ] else return coord string
null
null
null
null
Question: What does the code convert to an absolute coordinate string ? Code: def absolute_coordinate(coord_string): m = ABSOLUTE_RE.match(coord_string.upper()) if m: parts = m.groups() if all(parts[(-2):]): return ('$%s$%s:$%s$%s' % (parts[0], parts[1], parts[3], parts[4])) else: return ('$%s$%s' % (parts[0], parts[1])) else: return coord_string
null
null
null
How do cooperative task run ?
def cooperate(iterator): return _theCooperator.cooperate(iterator)
null
null
null
long
codeqa
def cooperate iterator return the Cooperator cooperate iterator
null
null
null
null
Question: How do cooperative task run ? Code: def cooperate(iterator): return _theCooperator.cooperate(iterator)
null
null
null
For what purpose is code executed ?
@_define_event def post_execute(): pass
null
null
null
in response to user / frontend action
codeqa
@ define eventdef post execute pass
null
null
null
null
Question: For what purpose is code executed ? Code: @_define_event def post_execute(): pass
null
null
null
What does the code take ?
def _format_for_table(plugins): return [[data[u'name'], data[u'version'], data[u'description'], data[u'authors'], data[u'home']] for data in plugins]
null
null
null
a list of plugins
codeqa
def format for table plugins return [[data[u'name'] data[u'version'] data[u'description'] data[u'authors'] data[u'home']] for data in plugins]
null
null
null
null
Question: What does the code take ? Code: def _format_for_table(plugins): return [[data[u'name'], data[u'version'], data[u'description'], data[u'authors'], data[u'home']] for data in plugins]
null
null
null
How do root_helper set in brick calls ?
def brick_get_connector_properties(multipath=False, enforce_multipath=False): root_helper = get_root_helper() return connector.get_connector_properties(root_helper, CONF.my_ip, multipath, enforce_multipath)
null
null
null
automatically
codeqa
def brick get connector properties multipath False enforce multipath False root helper get root helper return connector get connector properties root helper CONF my ip multipath enforce multipath
null
null
null
null
Question: How do root_helper set in brick calls ? Code: def brick_get_connector_properties(multipath=False, enforce_multipath=False): root_helper = get_root_helper() return connector.get_connector_properties(root_helper, CONF.my_ip, multipath, enforce_multipath)
null
null
null
How do translation write ?
def write_csv_file(path, app_messages, lang_dict): app_messages.sort((lambda x, y: cmp(x[1], y[1]))) from csv import writer with open(path, u'wb') as msgfile: w = writer(msgfile, lineterminator=u'\n') for (p, m) in app_messages: t = lang_dict.get(m, u'') t = re.sub(u'{\\s?([0-9]+)\\s?}', u'{\\g<1>}', t) w.writerow([(p.encode(u'utf-8') if p else u''), m.encode(u'utf-8'), t.encode(u'utf-8')])
null
null
null
csv file
codeqa
def write csv file path app messages lang dict app messages sort lambda x y cmp x[ 1 ] y[ 1 ] from csv import writerwith open path u'wb' as msgfile w writer msgfile lineterminator u'\n' for p m in app messages t lang dict get m u'' t re sub u'{\\s? [0 - 9 ]+ \\s?}' u'{\\g< 1 >}' t w writerow [ p encode u'utf- 8 ' if p else u'' m encode u'utf- 8 ' t encode u'utf- 8 ' ]
null
null
null
null
Question: How do translation write ? Code: def write_csv_file(path, app_messages, lang_dict): app_messages.sort((lambda x, y: cmp(x[1], y[1]))) from csv import writer with open(path, u'wb') as msgfile: w = writer(msgfile, lineterminator=u'\n') for (p, m) in app_messages: t = lang_dict.get(m, u'') t = re.sub(u'{\\s?([0-9]+)\\s?}', u'{\\g<1>}', t) w.writerow([(p.encode(u'utf-8') if p else u''), m.encode(u'utf-8'), t.encode(u'utf-8')])
null
null
null
For what purpose do relationships read ?
def read_rels(archive): xml_source = archive.read(ARC_WORKBOOK_RELS) tree = fromstring(xml_source) for element in safe_iterator(tree, ('{%s}Relationship' % PKG_REL_NS)): rId = element.get('Id') pth = element.get('Target') typ = element.get('Type') if pth.startswith('/xl'): pth = pth.replace('/xl', 'xl') elif ((not pth.startswith('xl')) and (not pth.startswith('..'))): pth = ('xl/' + pth) (yield (rId, {'path': pth, 'type': typ}))
null
null
null
for a workbook
codeqa
def read rels archive xml source archive read ARC WORKBOOK RELS tree fromstring xml source for element in safe iterator tree '{%s} Relationship' % PKG REL NS r Id element get ' Id' pth element get ' Target' typ element get ' Type' if pth startswith '/xl' pth pth replace '/xl' 'xl' elif not pth startswith 'xl' and not pth startswith ' ' pth 'xl/' + pth yield r Id {'path' pth 'type' typ}
null
null
null
null
Question: For what purpose do relationships read ? Code: def read_rels(archive): xml_source = archive.read(ARC_WORKBOOK_RELS) tree = fromstring(xml_source) for element in safe_iterator(tree, ('{%s}Relationship' % PKG_REL_NS)): rId = element.get('Id') pth = element.get('Target') typ = element.get('Type') if pth.startswith('/xl'): pth = pth.replace('/xl', 'xl') elif ((not pth.startswith('xl')) and (not pth.startswith('..'))): pth = ('xl/' + pth) (yield (rId, {'path': pth, 'type': typ}))
null
null
null
How does the code sort them ?
def sort(seq): for i in range(0, len(seq)): iMin = i for j in range((i + 1), len(seq)): if (seq[iMin] > seq[j]): iMin = j if (i != iMin): (seq[i], seq[iMin]) = (seq[iMin], seq[i]) return seq
null
null
null
in ascending order
codeqa
def sort seq for i in range 0 len seq i Min ifor j in range i + 1 len seq if seq[i Min] > seq[j] i Min jif i i Min seq[i] seq[i Min] seq[i Min] seq[i] return seq
null
null
null
null
Question: How does the code sort them ? Code: def sort(seq): for i in range(0, len(seq)): iMin = i for j in range((i + 1), len(seq)): if (seq[iMin] > seq[j]): iMin = j if (i != iMin): (seq[i], seq[iMin]) = (seq[iMin], seq[i]) return seq
null
null
null
What does the code take ?
def sort(seq): for i in range(0, len(seq)): iMin = i for j in range((i + 1), len(seq)): if (seq[iMin] > seq[j]): iMin = j if (i != iMin): (seq[i], seq[iMin]) = (seq[iMin], seq[i]) return seq
null
null
null
a list of integers
codeqa
def sort seq for i in range 0 len seq i Min ifor j in range i + 1 len seq if seq[i Min] > seq[j] i Min jif i i Min seq[i] seq[i Min] seq[i Min] seq[i] return seq
null
null
null
null
Question: What does the code take ? Code: def sort(seq): for i in range(0, len(seq)): iMin = i for j in range((i + 1), len(seq)): if (seq[iMin] > seq[j]): iMin = j if (i != iMin): (seq[i], seq[iMin]) = (seq[iMin], seq[i]) return seq
null
null
null
What does the code get ?
def description(): for desc in _description.splitlines(): print desc
null
null
null
description of brainstorm dataset
codeqa
def description for desc in description splitlines print desc
null
null
null
null
Question: What does the code get ? Code: def description(): for desc in _description.splitlines(): print desc
null
null
null
Where does implementation total_second ?
def total_seconds(td): if hasattr(td, 'total_seconds'): return td.total_seconds() else: return (((((td.days * 86400) + td.seconds) * (10 ** 6)) + td.microseconds) / (10.0 ** 6))
null
null
null
local
codeqa
def total seconds td if hasattr td 'total seconds' return td total seconds else return td days * 86400 + td seconds * 10 ** 6 + td microseconds / 10 0 ** 6
null
null
null
null
Question: Where does implementation total_second ? Code: def total_seconds(td): if hasattr(td, 'total_seconds'): return td.total_seconds() else: return (((((td.days * 86400) + td.seconds) * (10 ** 6)) + td.microseconds) / (10.0 ** 6))
null
null
null
What total_seconds local ?
def total_seconds(td): if hasattr(td, 'total_seconds'): return td.total_seconds() else: return (((((td.days * 86400) + td.seconds) * (10 ** 6)) + td.microseconds) / (10.0 ** 6))
null
null
null
implementation
codeqa
def total seconds td if hasattr td 'total seconds' return td total seconds else return td days * 86400 + td seconds * 10 ** 6 + td microseconds / 10 0 ** 6
null
null
null
null
Question: What total_seconds local ? Code: def total_seconds(td): if hasattr(td, 'total_seconds'): return td.total_seconds() else: return (((((td.days * 86400) + td.seconds) * (10 ** 6)) + td.microseconds) / (10.0 ** 6))
null
null
null
What does the code find ?
def for_name(fq_name, recursive=False): fq_name = str(fq_name) module_name = __name__ short_name = fq_name if (fq_name.rfind('.') >= 0): (module_name, short_name) = (fq_name[:fq_name.rfind('.')], fq_name[(fq_name.rfind('.') + 1):]) try: result = __import__(module_name, None, None, [short_name]) return result.__dict__[short_name] except KeyError: if recursive: raise else: raise ImportError(("Could not find '%s' on path '%s'" % (short_name, module_name))) except ImportError: try: module = for_name(module_name, recursive=True) if hasattr(module, short_name): return getattr(module, short_name) else: raise KeyError() except KeyError: raise ImportError(("Could not find '%s' on path '%s'" % (short_name, module_name))) except ImportError: pass raise
null
null
null
class / function / method specified by its fully qualified name
codeqa
def for name fq name recursive False fq name str fq name module name name short name fq nameif fq name rfind ' ' > 0 module name short name fq name[ fq name rfind ' ' ] fq name[ fq name rfind ' ' + 1 ] try result import module name None None [short name] return result dict [short name]except Key Error if recursive raiseelse raise Import Error " Couldnotfind'%s'onpath'%s'" % short name module name except Import Error try module for name module name recursive True if hasattr module short name return getattr module short name else raise Key Error except Key Error raise Import Error " Couldnotfind'%s'onpath'%s'" % short name module name except Import Error passraise
null
null
null
null
Question: What does the code find ? Code: def for_name(fq_name, recursive=False): fq_name = str(fq_name) module_name = __name__ short_name = fq_name if (fq_name.rfind('.') >= 0): (module_name, short_name) = (fq_name[:fq_name.rfind('.')], fq_name[(fq_name.rfind('.') + 1):]) try: result = __import__(module_name, None, None, [short_name]) return result.__dict__[short_name] except KeyError: if recursive: raise else: raise ImportError(("Could not find '%s' on path '%s'" % (short_name, module_name))) except ImportError: try: module = for_name(module_name, recursive=True) if hasattr(module, short_name): return getattr(module, short_name) else: raise KeyError() except KeyError: raise ImportError(("Could not find '%s' on path '%s'" % (short_name, module_name))) except ImportError: pass raise
null
null
null
What is using to combine them from right to left ?
def foldr(fn, elems, initializer=None, name=None): return tf.foldr(fn, elems, initializer=initializer, name=name)
null
null
null
fn
codeqa
def foldr fn elems initializer None name None return tf foldr fn elems initializer initializer name name
null
null
null
null
Question: What is using to combine them from right to left ? Code: def foldr(fn, elems, initializer=None, name=None): return tf.foldr(fn, elems, initializer=initializer, name=name)
null
null
null
What does the code create ?
def create_user(name, password, admin=False, **client_args): if user_exists(name, **client_args): log.info("User '{0}' already exists".format(name)) return False client = _client(**client_args) client.create_user(name, password, admin) return True
null
null
null
a user
codeqa
def create user name password admin False **client args if user exists name **client args log info " User'{ 0 }'alreadyexists" format name return Falseclient client **client args client create user name password admin return True
null
null
null
null
Question: What does the code create ? Code: def create_user(name, password, admin=False, **client_args): if user_exists(name, **client_args): log.info("User '{0}' already exists".format(name)) return False client = _client(**client_args) client.create_user(name, password, admin) return True
null
null
null
Where did all the names import ?
def traverse_imports(names): pending = [names] while pending: node = pending.pop() if (node.type == token.NAME): (yield node.value) elif (node.type == syms.dotted_name): (yield ''.join([ch.value for ch in node.children])) elif (node.type == syms.dotted_as_name): pending.append(node.children[0]) elif (node.type == syms.dotted_as_names): pending.extend(node.children[::(-2)]) else: raise AssertionError('unknown node type')
null
null
null
in a dotted_as_names node
codeqa
def traverse imports names pending [names]while pending node pending pop if node type token NAME yield node value elif node type syms dotted name yield '' join [ch value for ch in node children] elif node type syms dotted as name pending append node children[ 0 ] elif node type syms dotted as names pending extend node children[ -2 ] else raise Assertion Error 'unknownnodetype'
null
null
null
null
Question: Where did all the names import ? Code: def traverse_imports(names): pending = [names] while pending: node = pending.pop() if (node.type == token.NAME): (yield node.value) elif (node.type == syms.dotted_name): (yield ''.join([ch.value for ch in node.children])) elif (node.type == syms.dotted_as_name): pending.append(node.children[0]) elif (node.type == syms.dotted_as_names): pending.extend(node.children[::(-2)]) else: raise AssertionError('unknown node type')
null
null
null
What imported in a dotted_as_names node ?
def traverse_imports(names): pending = [names] while pending: node = pending.pop() if (node.type == token.NAME): (yield node.value) elif (node.type == syms.dotted_name): (yield ''.join([ch.value for ch in node.children])) elif (node.type == syms.dotted_as_name): pending.append(node.children[0]) elif (node.type == syms.dotted_as_names): pending.extend(node.children[::(-2)]) else: raise AssertionError('unknown node type')
null
null
null
all the names
codeqa
def traverse imports names pending [names]while pending node pending pop if node type token NAME yield node value elif node type syms dotted name yield '' join [ch value for ch in node children] elif node type syms dotted as name pending append node children[ 0 ] elif node type syms dotted as names pending extend node children[ -2 ] else raise Assertion Error 'unknownnodetype'
null
null
null
null
Question: What imported in a dotted_as_names node ? Code: def traverse_imports(names): pending = [names] while pending: node = pending.pop() if (node.type == token.NAME): (yield node.value) elif (node.type == syms.dotted_name): (yield ''.join([ch.value for ch in node.children])) elif (node.type == syms.dotted_as_name): pending.append(node.children[0]) elif (node.type == syms.dotted_as_names): pending.extend(node.children[::(-2)]) else: raise AssertionError('unknown node type')
null
null
null
Where did properties specify ?
def undeploy(jboss_config, deployment): log.debug('======================== MODULE FUNCTION: jboss7.undeploy, deployment=%s', deployment) command = 'undeploy {deployment} '.format(deployment=deployment) return __salt__['jboss7_cli.run_command'](jboss_config, command)
null
null
null
above
codeqa
def undeploy jboss config deployment log debug ' MODULEFUNCTION jboss 7 undeploy deployment %s' deployment command 'undeploy{deployment}' format deployment deployment return salt ['jboss 7 cli run command'] jboss config command
null
null
null
null
Question: Where did properties specify ? Code: def undeploy(jboss_config, deployment): log.debug('======================== MODULE FUNCTION: jboss7.undeploy, deployment=%s', deployment) command = 'undeploy {deployment} '.format(deployment=deployment) return __salt__['jboss7_cli.run_command'](jboss_config, command)
null
null
null
What specified above ?
def undeploy(jboss_config, deployment): log.debug('======================== MODULE FUNCTION: jboss7.undeploy, deployment=%s', deployment) command = 'undeploy {deployment} '.format(deployment=deployment) return __salt__['jboss7_cli.run_command'](jboss_config, command)
null
null
null
properties
codeqa
def undeploy jboss config deployment log debug ' MODULEFUNCTION jboss 7 undeploy deployment %s' deployment command 'undeploy{deployment}' format deployment deployment return salt ['jboss 7 cli run command'] jboss config command
null
null
null
null
Question: What specified above ? Code: def undeploy(jboss_config, deployment): log.debug('======================== MODULE FUNCTION: jboss7.undeploy, deployment=%s', deployment) command = 'undeploy {deployment} '.format(deployment=deployment) return __salt__['jboss7_cli.run_command'](jboss_config, command)
null
null
null
What does the code execute ?
def _python_cmd(*args): args = ((sys.executable,) + args) return (subprocess.call(args) == 0)
null
null
null
a command
codeqa
def python cmd *args args sys executable + args return subprocess call args 0
null
null
null
null
Question: What does the code execute ? Code: def _python_cmd(*args): args = ((sys.executable,) + args) return (subprocess.call(args) == 0)
null
null
null
What does the code subtract from f ?
def dup_sub_ground(f, c, K): return dup_sub_term(f, c, 0, K)
null
null
null
an element of the ground domain
codeqa
def dup sub ground f c K return dup sub term f c 0 K
null
null
null
null
Question: What does the code subtract from f ? Code: def dup_sub_ground(f, c, K): return dup_sub_term(f, c, 0, K)
null
null
null
What does the code get ?
def getTransformXMLElement(coords, transformName): transformXMLElement = coords.getFirstChildWithClassName(transformName) if (len(transformXMLElement.attributeDictionary) < 16): if ('bf:ref' in transformXMLElement.attributeDictionary): idReference = transformXMLElement.attributeDictionary['bf:ref'] return coords.getRoot().getSubChildWithID(idReference) return transformXMLElement
null
null
null
the transform attributes
codeqa
def get Transform XML Element coords transform Name transform XML Element coords get First Child With Class Name transform Name if len transform XML Element attribute Dictionary < 16 if 'bf ref' in transform XML Element attribute Dictionary id Reference transform XML Element attribute Dictionary['bf ref']return coords get Root get Sub Child With ID id Reference return transform XML Element
null
null
null
null
Question: What does the code get ? Code: def getTransformXMLElement(coords, transformName): transformXMLElement = coords.getFirstChildWithClassName(transformName) if (len(transformXMLElement.attributeDictionary) < 16): if ('bf:ref' in transformXMLElement.attributeDictionary): idReference = transformXMLElement.attributeDictionary['bf:ref'] return coords.getRoot().getSubChildWithID(idReference) return transformXMLElement
null
null
null
What does the code add to negatives and positives ?
def addNegativesPositives(derivation, negatives, paths, positives): portionDirections = getSpacedPortionDirections(derivation.interpolationDictionary) for path in paths: endMultiplier = None if (not euclidean.getIsWiddershinsByVector3(path)): endMultiplier = 1.000001 loopLists = getLoopListsByPath(derivation, endMultiplier, path, portionDirections) geometryOutput = triangle_mesh.getPillarsOutput(loopLists) if (endMultiplier == None): positives.append(geometryOutput) else: negatives.append(geometryOutput)
null
null
null
pillars output
codeqa
def add Negatives Positives derivation negatives paths positives portion Directions get Spaced Portion Directions derivation interpolation Dictionary for path in paths end Multiplier Noneif not euclidean get Is Widdershins By Vector 3 path end Multiplier 1 000001 loop Lists get Loop Lists By Path derivation end Multiplier path portion Directions geometry Output trianglemesh get Pillars Output loop Lists if end Multiplier None positives append geometry Output else negatives append geometry Output
null
null
null
null
Question: What does the code add to negatives and positives ? Code: def addNegativesPositives(derivation, negatives, paths, positives): portionDirections = getSpacedPortionDirections(derivation.interpolationDictionary) for path in paths: endMultiplier = None if (not euclidean.getIsWiddershinsByVector3(path)): endMultiplier = 1.000001 loopLists = getLoopListsByPath(derivation, endMultiplier, path, portionDirections) geometryOutput = triangle_mesh.getPillarsOutput(loopLists) if (endMultiplier == None): positives.append(geometryOutput) else: negatives.append(geometryOutput)
null
null
null
How d the code get a namespace ?
def _get(context, namespace_id, session): try: query = session.query(models.MetadefNamespace).filter_by(id=namespace_id) namespace_rec = query.one() except sa_orm.exc.NoResultFound: msg = (_('Metadata definition namespace not found for id=%s') % namespace_id) LOG.warn(msg) raise exc.MetadefNamespaceNotFound(msg) if (not _is_namespace_visible(context, namespace_rec.to_dict())): LOG.debug('Forbidding request, metadata definition namespace=%s is not visible.', namespace_rec.namespace) emsg = (_('Forbidding request, metadata definition namespace=%s is not visible.') % namespace_rec.namespace) raise exc.MetadefForbidden(emsg) return namespace_rec
null
null
null
by i d
codeqa
def get context namespace id session try query session query models Metadef Namespace filter by id namespace id namespace rec query one except sa orm exc No Result Found msg ' Metadatadefinitionnamespacenotfoundforid %s' % namespace id LOG warn msg raise exc Metadef Namespace Not Found msg if not is namespace visible context namespace rec to dict LOG debug ' Forbiddingrequest metadatadefinitionnamespace %sisnotvisible ' namespace rec namespace emsg ' Forbiddingrequest metadatadefinitionnamespace %sisnotvisible ' % namespace rec namespace raise exc Metadef Forbidden emsg return namespace rec
null
null
null
null
Question: How d the code get a namespace ? Code: def _get(context, namespace_id, session): try: query = session.query(models.MetadefNamespace).filter_by(id=namespace_id) namespace_rec = query.one() except sa_orm.exc.NoResultFound: msg = (_('Metadata definition namespace not found for id=%s') % namespace_id) LOG.warn(msg) raise exc.MetadefNamespaceNotFound(msg) if (not _is_namespace_visible(context, namespace_rec.to_dict())): LOG.debug('Forbidding request, metadata definition namespace=%s is not visible.', namespace_rec.namespace) emsg = (_('Forbidding request, metadata definition namespace=%s is not visible.') % namespace_rec.namespace) raise exc.MetadefForbidden(emsg) return namespace_rec
null
null
null
What d the code get by i d ?
def _get(context, namespace_id, session): try: query = session.query(models.MetadefNamespace).filter_by(id=namespace_id) namespace_rec = query.one() except sa_orm.exc.NoResultFound: msg = (_('Metadata definition namespace not found for id=%s') % namespace_id) LOG.warn(msg) raise exc.MetadefNamespaceNotFound(msg) if (not _is_namespace_visible(context, namespace_rec.to_dict())): LOG.debug('Forbidding request, metadata definition namespace=%s is not visible.', namespace_rec.namespace) emsg = (_('Forbidding request, metadata definition namespace=%s is not visible.') % namespace_rec.namespace) raise exc.MetadefForbidden(emsg) return namespace_rec
null
null
null
a namespace
codeqa
def get context namespace id session try query session query models Metadef Namespace filter by id namespace id namespace rec query one except sa orm exc No Result Found msg ' Metadatadefinitionnamespacenotfoundforid %s' % namespace id LOG warn msg raise exc Metadef Namespace Not Found msg if not is namespace visible context namespace rec to dict LOG debug ' Forbiddingrequest metadatadefinitionnamespace %sisnotvisible ' namespace rec namespace emsg ' Forbiddingrequest metadatadefinitionnamespace %sisnotvisible ' % namespace rec namespace raise exc Metadef Forbidden emsg return namespace rec
null
null
null
null
Question: What d the code get by i d ? Code: def _get(context, namespace_id, session): try: query = session.query(models.MetadefNamespace).filter_by(id=namespace_id) namespace_rec = query.one() except sa_orm.exc.NoResultFound: msg = (_('Metadata definition namespace not found for id=%s') % namespace_id) LOG.warn(msg) raise exc.MetadefNamespaceNotFound(msg) if (not _is_namespace_visible(context, namespace_rec.to_dict())): LOG.debug('Forbidding request, metadata definition namespace=%s is not visible.', namespace_rec.namespace) emsg = (_('Forbidding request, metadata definition namespace=%s is not visible.') % namespace_rec.namespace) raise exc.MetadefForbidden(emsg) return namespace_rec
null
null
null
What does the code convert to a python number ?
def nti(s): if (s[0] != chr(128)): try: n = int((nts(s) or '0'), 8) except ValueError: raise HeaderError('invalid header') else: n = 0L for i in xrange((len(s) - 1)): n <<= 8 n += ord(s[(i + 1)]) return n
null
null
null
a number field
codeqa
def nti s if s[ 0 ] chr 128 try n int nts s or '0 ' 8 except Value Error raise Header Error 'invalidheader' else n 0 Lfor i in xrange len s - 1 n << 8n + ord s[ i + 1 ] return n
null
null
null
null
Question: What does the code convert to a python number ? Code: def nti(s): if (s[0] != chr(128)): try: n = int((nts(s) or '0'), 8) except ValueError: raise HeaderError('invalid header') else: n = 0L for i in xrange((len(s) - 1)): n <<= 8 n += ord(s[(i + 1)]) return n
null
null
null
How is the vertex connected to one of the target vertices ?
def _is_connected_by_alternating_path(G, v, matching, targets): matched_edges = {(u, v) for (u, v) in matching.items() if (u <= v)} unmatched_edges = (set(G.edges()) - matched_edges) def _alternating_dfs(u, depth, along_matched=True): 'Returns True if and only if `u` is connected to one of the\n targets by an alternating path.\n\n `u` is a vertex in the graph `G`.\n\n `depth` specifies the maximum recursion depth of the depth-first\n search.\n\n If `along_matched` is True, this step of the depth-first search\n will continue only through edges in the given matching. Otherwise, it\n will continue only through edges *not* in the given matching.\n\n ' if (u in targets): return True if (depth < 0): return False valid_edges = (matched_edges if along_matched else unmatched_edges) for v in G[u]: if (((u, v) in valid_edges) or ((v, u) in valid_edges)): return _alternating_dfs(v, (depth - 1), (not along_matched)) return False return (_alternating_dfs(v, len(G), along_matched=True) or _alternating_dfs(v, len(G), along_matched=False))
null
null
null
by an alternating path in g
codeqa
def is connected by alternating path G v matching targets matched edges { u v for u v in matching items if u < v }unmatched edges set G edges - matched edges def alternating dfs u depth along matched True ' Returns Trueifandonlyif`u`isconnectedtooneofthe\ntargetsbyanalternatingpath \n\n`u`isavertexinthegraph`G` \n\n`depth`specifiesthemaximumrecursiondepthofthedepth-first\nsearch \n\n If`along matched`is True thisstepofthedepth-firstsearch\nwillcontinueonlythroughedgesinthegivenmatching Otherwise it\nwillcontinueonlythroughedges*not*inthegivenmatching \n\n'if u in targets return Trueif depth < 0 return Falsevalid edges matched edges if along matched else unmatched edges for v in G[u] if u v in valid edges or v u in valid edges return alternating dfs v depth - 1 not along matched return Falsereturn alternating dfs v len G along matched True or alternating dfs v len G along matched False
null
null
null
null
Question: How is the vertex connected to one of the target vertices ? Code: def _is_connected_by_alternating_path(G, v, matching, targets): matched_edges = {(u, v) for (u, v) in matching.items() if (u <= v)} unmatched_edges = (set(G.edges()) - matched_edges) def _alternating_dfs(u, depth, along_matched=True): 'Returns True if and only if `u` is connected to one of the\n targets by an alternating path.\n\n `u` is a vertex in the graph `G`.\n\n `depth` specifies the maximum recursion depth of the depth-first\n search.\n\n If `along_matched` is True, this step of the depth-first search\n will continue only through edges in the given matching. Otherwise, it\n will continue only through edges *not* in the given matching.\n\n ' if (u in targets): return True if (depth < 0): return False valid_edges = (matched_edges if along_matched else unmatched_edges) for v in G[u]: if (((u, v) in valid_edges) or ((v, u) in valid_edges)): return _alternating_dfs(v, (depth - 1), (not along_matched)) return False return (_alternating_dfs(v, len(G), along_matched=True) or _alternating_dfs(v, len(G), along_matched=False))
null
null
null
What does the code perform on the region adjacency graph ?
def _ncut_relabel(rag, thresh, num_cuts): (d, w) = _ncut.DW_matrices(rag) m = w.shape[0] if (m > 2): d2 = d.copy() d2.data = np.reciprocal(np.sqrt(d2.data, out=d2.data), out=d2.data) (vals, vectors) = linalg.eigsh(((d2 * (d - w)) * d2), which='SM', k=min(100, (m - 2))) (vals, vectors) = (np.real(vals), np.real(vectors)) index2 = _ncut_cy.argmin2(vals) ev = vectors[:, index2] (cut_mask, mcut) = get_min_ncut(ev, d, w, num_cuts) if (mcut < thresh): (sub1, sub2) = partition_by_cut(cut_mask, rag) _ncut_relabel(sub1, thresh, num_cuts) _ncut_relabel(sub2, thresh, num_cuts) return _label_all(rag, 'ncut label')
null
null
null
normalized graph cut
codeqa
def ncut relabel rag thresh num cuts d w ncut DW matrices rag m w shape[ 0 ]if m > 2 d2 d copy d2 data np reciprocal np sqrt d2 data out d2 data out d2 data vals vectors linalg eigsh d2 * d - w * d2 which 'SM' k min 100 m - 2 vals vectors np real vals np real vectors index 2 ncut cy argmin 2 vals ev vectors[ index 2 ] cut mask mcut get min ncut ev d w num cuts if mcut < thresh sub 1 sub 2 partition by cut cut mask rag ncut relabel sub 1 thresh num cuts ncut relabel sub 2 thresh num cuts return label all rag 'ncutlabel'
null
null
null
null
Question: What does the code perform on the region adjacency graph ? Code: def _ncut_relabel(rag, thresh, num_cuts): (d, w) = _ncut.DW_matrices(rag) m = w.shape[0] if (m > 2): d2 = d.copy() d2.data = np.reciprocal(np.sqrt(d2.data, out=d2.data), out=d2.data) (vals, vectors) = linalg.eigsh(((d2 * (d - w)) * d2), which='SM', k=min(100, (m - 2))) (vals, vectors) = (np.real(vals), np.real(vectors)) index2 = _ncut_cy.argmin2(vals) ev = vectors[:, index2] (cut_mask, mcut) = get_min_ncut(ev, d, w, num_cuts) if (mcut < thresh): (sub1, sub2) = partition_by_cut(cut_mask, rag) _ncut_relabel(sub1, thresh, num_cuts) _ncut_relabel(sub2, thresh, num_cuts) return _label_all(rag, 'ncut label')
null
null
null
Where does the code perform normalized graph cut ?
def _ncut_relabel(rag, thresh, num_cuts): (d, w) = _ncut.DW_matrices(rag) m = w.shape[0] if (m > 2): d2 = d.copy() d2.data = np.reciprocal(np.sqrt(d2.data, out=d2.data), out=d2.data) (vals, vectors) = linalg.eigsh(((d2 * (d - w)) * d2), which='SM', k=min(100, (m - 2))) (vals, vectors) = (np.real(vals), np.real(vectors)) index2 = _ncut_cy.argmin2(vals) ev = vectors[:, index2] (cut_mask, mcut) = get_min_ncut(ev, d, w, num_cuts) if (mcut < thresh): (sub1, sub2) = partition_by_cut(cut_mask, rag) _ncut_relabel(sub1, thresh, num_cuts) _ncut_relabel(sub2, thresh, num_cuts) return _label_all(rag, 'ncut label')
null
null
null
on the region adjacency graph
codeqa
def ncut relabel rag thresh num cuts d w ncut DW matrices rag m w shape[ 0 ]if m > 2 d2 d copy d2 data np reciprocal np sqrt d2 data out d2 data out d2 data vals vectors linalg eigsh d2 * d - w * d2 which 'SM' k min 100 m - 2 vals vectors np real vals np real vectors index 2 ncut cy argmin 2 vals ev vectors[ index 2 ] cut mask mcut get min ncut ev d w num cuts if mcut < thresh sub 1 sub 2 partition by cut cut mask rag ncut relabel sub 1 thresh num cuts ncut relabel sub 2 thresh num cuts return label all rag 'ncutlabel'
null
null
null
null
Question: Where does the code perform normalized graph cut ? Code: def _ncut_relabel(rag, thresh, num_cuts): (d, w) = _ncut.DW_matrices(rag) m = w.shape[0] if (m > 2): d2 = d.copy() d2.data = np.reciprocal(np.sqrt(d2.data, out=d2.data), out=d2.data) (vals, vectors) = linalg.eigsh(((d2 * (d - w)) * d2), which='SM', k=min(100, (m - 2))) (vals, vectors) = (np.real(vals), np.real(vectors)) index2 = _ncut_cy.argmin2(vals) ev = vectors[:, index2] (cut_mask, mcut) = get_min_ncut(ev, d, w, num_cuts) if (mcut < thresh): (sub1, sub2) = partition_by_cut(cut_mask, rag) _ncut_relabel(sub1, thresh, num_cuts) _ncut_relabel(sub2, thresh, num_cuts) return _label_all(rag, 'ncut label')
null
null
null
What do we want when ?
@pytest.yield_fixture(params=[None, tdata]) def temp_add_server(request): data = request.param s = Server(copy(data), formats=all_formats, allow_add=True) s.app.testing = True with s.app.test_client() as c: (yield c)
null
null
null
to mutate the server
codeqa
@pytest yield fixture params [ None tdata] def temp add server request data request params Server copy data formats all formats allow add True s app testing Truewith s app test client as c yield c
null
null
null
null
Question: What do we want when ? Code: @pytest.yield_fixture(params=[None, tdata]) def temp_add_server(request): data = request.param s = Server(copy(data), formats=all_formats, allow_add=True) s.app.testing = True with s.app.test_client() as c: (yield c)
null
null
null
What do we mutate ?
@pytest.yield_fixture(params=[None, tdata]) def temp_add_server(request): data = request.param s = Server(copy(data), formats=all_formats, allow_add=True) s.app.testing = True with s.app.test_client() as c: (yield c)
null
null
null
the server
codeqa
@pytest yield fixture params [ None tdata] def temp add server request data request params Server copy data formats all formats allow add True s app testing Truewith s app test client as c yield c
null
null
null
null
Question: What do we mutate ? Code: @pytest.yield_fixture(params=[None, tdata]) def temp_add_server(request): data = request.param s = Server(copy(data), formats=all_formats, allow_add=True) s.app.testing = True with s.app.test_client() as c: (yield c)
null
null
null
What does the code find ?
def get_absolute_number_from_season_and_episode(show, season, episode): absolute_number = None if (season and episode): main_db_con = db.DBConnection() sql = u'SELECT * FROM tv_episodes WHERE showid = ? and season = ? and episode = ?' sql_results = main_db_con.select(sql, [show.indexerid, season, episode]) if (len(sql_results) == 1): absolute_number = int(sql_results[0]['absolute_number']) logger.log(u'Found absolute number {absolute} for show {show} {ep}'.format(absolute=absolute_number, show=show.name, ep=episode_num(season, episode)), logger.DEBUG) else: logger.log(u'No entries for absolute number for show {show} {ep}'.format(show=show.name, ep=episode_num(season, episode)), logger.DEBUG) return absolute_number
null
null
null
the absolute number for a show episode
codeqa
def get absolute number from season and episode show season episode absolute number Noneif season and episode main db con db DB Connection sql u'SELECT*FRO Mtv episodes WHER Eshowid ?andseason ?andepisode ?'sql results main db con select sql [show indexerid season episode] if len sql results 1 absolute number int sql results[ 0 ]['absolute number'] logger log u' Foundabsolutenumber{absolute}forshow{show}{ep}' format absolute absolute number show show name ep episode num season episode logger DEBUG else logger log u' Noentriesforabsolutenumberforshow{show}{ep}' format show show name ep episode num season episode logger DEBUG return absolute number
null
null
null
null
Question: What does the code find ? Code: def get_absolute_number_from_season_and_episode(show, season, episode): absolute_number = None if (season and episode): main_db_con = db.DBConnection() sql = u'SELECT * FROM tv_episodes WHERE showid = ? and season = ? and episode = ?' sql_results = main_db_con.select(sql, [show.indexerid, season, episode]) if (len(sql_results) == 1): absolute_number = int(sql_results[0]['absolute_number']) logger.log(u'Found absolute number {absolute} for show {show} {ep}'.format(absolute=absolute_number, show=show.name, ep=episode_num(season, episode)), logger.DEBUG) else: logger.log(u'No entries for absolute number for show {show} {ep}'.format(show=show.name, ep=episode_num(season, episode)), logger.DEBUG) return absolute_number
null
null
null
What represents a boolean ?
def is_boolean(value): if isinstance(value, basestring): try: return bool_dict[value.lower()] except KeyError: raise VdtTypeError(value) if (value == False): return False elif (value == True): return True else: raise VdtTypeError(value)
null
null
null
the value
codeqa
def is boolean value if isinstance value basestring try return bool dict[value lower ]except Key Error raise Vdt Type Error value if value False return Falseelif value True return Trueelse raise Vdt Type Error value
null
null
null
null
Question: What represents a boolean ? Code: def is_boolean(value): if isinstance(value, basestring): try: return bool_dict[value.lower()] except KeyError: raise VdtTypeError(value) if (value == False): return False elif (value == True): return True else: raise VdtTypeError(value)
null
null
null
What returns a geometry ?
def check_geom(result, func, cargs): if isinstance(result, int): result = c_void_p(result) if (not result): raise GDALException(('Invalid geometry pointer returned from "%s".' % func.__name__)) return result
null
null
null
a function
codeqa
def check geom result func cargs if isinstance result int result c void p result if not result raise GDAL Exception ' Invalidgeometrypointerreturnedfrom"%s" ' % func name return result
null
null
null
null
Question: What returns a geometry ? Code: def check_geom(result, func, cargs): if isinstance(result, int): result = c_void_p(result) if (not result): raise GDALException(('Invalid geometry pointer returned from "%s".' % func.__name__)) return result
null
null
null
What does a function return ?
def check_geom(result, func, cargs): if isinstance(result, int): result = c_void_p(result) if (not result): raise GDALException(('Invalid geometry pointer returned from "%s".' % func.__name__)) return result
null
null
null
a geometry
codeqa
def check geom result func cargs if isinstance result int result c void p result if not result raise GDAL Exception ' Invalidgeometrypointerreturnedfrom"%s" ' % func name return result
null
null
null
null
Question: What does a function return ? Code: def check_geom(result, func, cargs): if isinstance(result, int): result = c_void_p(result) if (not result): raise GDALException(('Invalid geometry pointer returned from "%s".' % func.__name__)) return result
null
null
null
What used in the given module ?
def reload(module, exclude=('sys', 'os.path', 'builtins', '__main__', 'numpy', 'numpy._globals')): global found_now for i in exclude: found_now[i] = 1 try: with replace_import_hook(deep_import_hook): return deep_reload_hook(module) finally: found_now = {}
null
null
null
all modules
codeqa
def reload module exclude 'sys' 'os path' 'builtins' ' main ' 'numpy' 'numpy globals' global found nowfor i in exclude found now[i] 1try with replace import hook deep import hook return deep reload hook module finally found now {}
null
null
null
null
Question: What used in the given module ? Code: def reload(module, exclude=('sys', 'os.path', 'builtins', '__main__', 'numpy', 'numpy._globals')): global found_now for i in exclude: found_now[i] = 1 try: with replace_import_hook(deep_import_hook): return deep_reload_hook(module) finally: found_now = {}
null
null
null
Where did all modules use ?
def reload(module, exclude=('sys', 'os.path', 'builtins', '__main__', 'numpy', 'numpy._globals')): global found_now for i in exclude: found_now[i] = 1 try: with replace_import_hook(deep_import_hook): return deep_reload_hook(module) finally: found_now = {}
null
null
null
in the given module
codeqa
def reload module exclude 'sys' 'os path' 'builtins' ' main ' 'numpy' 'numpy globals' global found nowfor i in exclude found now[i] 1try with replace import hook deep import hook return deep reload hook module finally found now {}
null
null
null
null
Question: Where did all modules use ? Code: def reload(module, exclude=('sys', 'os.path', 'builtins', '__main__', 'numpy', 'numpy._globals')): global found_now for i in exclude: found_now[i] = 1 try: with replace_import_hook(deep_import_hook): return deep_reload_hook(module) finally: found_now = {}
null
null
null
How do all modules used in the given module reload ?
def reload(module, exclude=('sys', 'os.path', 'builtins', '__main__', 'numpy', 'numpy._globals')): global found_now for i in exclude: found_now[i] = 1 try: with replace_import_hook(deep_import_hook): return deep_reload_hook(module) finally: found_now = {}
null
null
null
recursively
codeqa
def reload module exclude 'sys' 'os path' 'builtins' ' main ' 'numpy' 'numpy globals' global found nowfor i in exclude found now[i] 1try with replace import hook deep import hook return deep reload hook module finally found now {}
null
null
null
null
Question: How do all modules used in the given module reload ? Code: def reload(module, exclude=('sys', 'os.path', 'builtins', '__main__', 'numpy', 'numpy._globals')): global found_now for i in exclude: found_now[i] = 1 try: with replace_import_hook(deep_import_hook): return deep_reload_hook(module) finally: found_now = {}
null
null
null
What does the code create ?
def _create_user(user_id, email): user_settings = get_user_settings(user_id, strict=False) if (user_settings is not None): raise Exception(('User %s already exists.' % user_id)) user_settings = UserSettings(user_id, email, preferred_language_codes=[feconf.DEFAULT_LANGUAGE_CODE]) _save_user_settings(user_settings) create_user_contributions(user_id, [], []) return user_settings
null
null
null
a new user
codeqa
def create user user id email user settings get user settings user id strict False if user settings is not None raise Exception ' User%salreadyexists ' % user id user settings User Settings user id email preferred language codes [feconf DEFAULT LANGUAGE CODE] save user settings user settings create user contributions user id [] [] return user settings
null
null
null
null
Question: What does the code create ? Code: def _create_user(user_id, email): user_settings = get_user_settings(user_id, strict=False) if (user_settings is not None): raise Exception(('User %s already exists.' % user_id)) user_settings = UserSettings(user_id, email, preferred_language_codes=[feconf.DEFAULT_LANGUAGE_CODE]) _save_user_settings(user_settings) create_user_contributions(user_id, [], []) return user_settings
null
null
null
What does the code get ?
def getNewDerivation(elementNode): return DisjoinDerivation(elementNode)
null
null
null
new derivation
codeqa
def get New Derivation element Node return Disjoin Derivation element Node
null
null
null
null
Question: What does the code get ? Code: def getNewDerivation(elementNode): return DisjoinDerivation(elementNode)
null
null
null
In which direction does the code move the code to corresponding shadow tables ?
def archive_deleted_rows(context, max_rows=None): return IMPL.archive_deleted_rows(context, max_rows=max_rows)
null
null
null
from production tables
codeqa
def archive deleted rows context max rows None return IMPL archive deleted rows context max rows max rows
null
null
null
null
Question: In which direction does the code move the code to corresponding shadow tables ? Code: def archive_deleted_rows(context, max_rows=None): return IMPL.archive_deleted_rows(context, max_rows=max_rows)
null
null
null
What do a header in the response have ?
def force_header(header, value): def _decorator(func): '\n Decorates the given function.\n ' @wraps(func) def _inner(*args, **kwargs): '\n Alters the response.\n ' response = func(*args, **kwargs) force_header_for_response(response, header, value) return response return _inner return _decorator
null
null
null
a specific value
codeqa
def force header header value def decorator func '\n Decoratesthegivenfunction \n'@wraps func def inner *args **kwargs '\n Alterstheresponse \n'response func *args **kwargs force header for response response header value return responsereturn innerreturn decorator
null
null
null
null
Question: What do a header in the response have ? Code: def force_header(header, value): def _decorator(func): '\n Decorates the given function.\n ' @wraps(func) def _inner(*args, **kwargs): '\n Alters the response.\n ' response = func(*args, **kwargs) force_header_for_response(response, header, value) return response return _inner return _decorator
null
null
null
What forces a header in the response to have a specific value ?
def force_header(header, value): def _decorator(func): '\n Decorates the given function.\n ' @wraps(func) def _inner(*args, **kwargs): '\n Alters the response.\n ' response = func(*args, **kwargs) force_header_for_response(response, header, value) return response return _inner return _decorator
null
null
null
decorator
codeqa
def force header header value def decorator func '\n Decoratesthegivenfunction \n'@wraps func def inner *args **kwargs '\n Alterstheresponse \n'response func *args **kwargs force header for response response header value return responsereturn innerreturn decorator
null
null
null
null
Question: What forces a header in the response to have a specific value ? Code: def force_header(header, value): def _decorator(func): '\n Decorates the given function.\n ' @wraps(func) def _inner(*args, **kwargs): '\n Alters the response.\n ' response = func(*args, **kwargs) force_header_for_response(response, header, value) return response return _inner return _decorator
null
null
null
What does decorator force to have a specific value ?
def force_header(header, value): def _decorator(func): '\n Decorates the given function.\n ' @wraps(func) def _inner(*args, **kwargs): '\n Alters the response.\n ' response = func(*args, **kwargs) force_header_for_response(response, header, value) return response return _inner return _decorator
null
null
null
a header in the response
codeqa
def force header header value def decorator func '\n Decoratesthegivenfunction \n'@wraps func def inner *args **kwargs '\n Alterstheresponse \n'response func *args **kwargs force header for response response header value return responsereturn innerreturn decorator
null
null
null
null
Question: What does decorator force to have a specific value ? Code: def force_header(header, value): def _decorator(func): '\n Decorates the given function.\n ' @wraps(func) def _inner(*args, **kwargs): '\n Alters the response.\n ' response = func(*args, **kwargs) force_header_for_response(response, header, value) return response return _inner return _decorator
null
null
null
What haves a specific value ?
def force_header(header, value): def _decorator(func): '\n Decorates the given function.\n ' @wraps(func) def _inner(*args, **kwargs): '\n Alters the response.\n ' response = func(*args, **kwargs) force_header_for_response(response, header, value) return response return _inner return _decorator
null
null
null
a header in the response
codeqa
def force header header value def decorator func '\n Decoratesthegivenfunction \n'@wraps func def inner *args **kwargs '\n Alterstheresponse \n'response func *args **kwargs force header for response response header value return responsereturn innerreturn decorator
null
null
null
null
Question: What haves a specific value ? Code: def force_header(header, value): def _decorator(func): '\n Decorates the given function.\n ' @wraps(func) def _inner(*args, **kwargs): '\n Alters the response.\n ' response = func(*args, **kwargs) force_header_for_response(response, header, value) return response return _inner return _decorator
null
null
null
What do b convert ?
def validate_bool(b): if isinstance(b, six.string_types): b = b.lower() if (b in (u't', u'y', u'yes', u'on', u'true', u'1', 1, True)): return True elif (b in (u'f', u'n', u'no', u'off', u'false', u'0', 0, False)): return False else: raise ValueError((u'Could not convert "%s" to boolean' % b))
null
null
null
to a boolean
codeqa
def validate bool b if isinstance b six string types b b lower if b in u't' u'y' u'yes' u'on' u'true' u' 1 ' 1 True return Trueelif b in u'f' u'n' u'no' u'off' u'false' u' 0 ' 0 False return Falseelse raise Value Error u' Couldnotconvert"%s"toboolean' % b
null
null
null
null
Question: What do b convert ? Code: def validate_bool(b): if isinstance(b, six.string_types): b = b.lower() if (b in (u't', u'y', u'yes', u'on', u'true', u'1', 1, True)): return True elif (b in (u'f', u'n', u'no', u'off', u'false', u'0', 0, False)): return False else: raise ValueError((u'Could not convert "%s" to boolean' % b))
null
null
null
What converts to a boolean ?
def validate_bool(b): if isinstance(b, six.string_types): b = b.lower() if (b in (u't', u'y', u'yes', u'on', u'true', u'1', 1, True)): return True elif (b in (u'f', u'n', u'no', u'off', u'false', u'0', 0, False)): return False else: raise ValueError((u'Could not convert "%s" to boolean' % b))
null
null
null
b
codeqa
def validate bool b if isinstance b six string types b b lower if b in u't' u'y' u'yes' u'on' u'true' u' 1 ' 1 True return Trueelif b in u'f' u'n' u'no' u'off' u'false' u' 0 ' 0 False return Falseelse raise Value Error u' Couldnotconvert"%s"toboolean' % b
null
null
null
null
Question: What converts to a boolean ? Code: def validate_bool(b): if isinstance(b, six.string_types): b = b.lower() if (b in (u't', u'y', u'yes', u'on', u'true', u'1', 1, True)): return True elif (b in (u'f', u'n', u'no', u'off', u'false', u'0', 0, False)): return False else: raise ValueError((u'Could not convert "%s" to boolean' % b))
null
null
null
How does the access token update in the database ?
def _update_access_token(user, graph): profile = try_get_profile(user) model_or_profile = get_instance_for_attribute(user, profile, 'access_token') if model_or_profile: new_token = (graph.access_token != model_or_profile.access_token) token_message = ('a new' if new_token else 'the same') logger.info('found %s token %s', token_message, graph.access_token[:10]) if new_token: logger.info('access token changed, updating now') model_or_profile.update_access_token(graph.access_token) model_or_profile.save() model_or_profile.extend_access_token()
null
null
null
conditionally
codeqa
def update access token user graph profile try get profile user model or profile get instance for attribute user profile 'access token' if model or profile new token graph access token model or profile access token token message 'anew' if new token else 'thesame' logger info 'found%stoken%s' token message graph access token[ 10 ] if new token logger info 'accesstokenchanged updatingnow' model or profile update access token graph access token model or profile save model or profile extend access token
null
null
null
null
Question: How does the access token update in the database ? Code: def _update_access_token(user, graph): profile = try_get_profile(user) model_or_profile = get_instance_for_attribute(user, profile, 'access_token') if model_or_profile: new_token = (graph.access_token != model_or_profile.access_token) token_message = ('a new' if new_token else 'the same') logger.info('found %s token %s', token_message, graph.access_token[:10]) if new_token: logger.info('access token changed, updating now') model_or_profile.update_access_token(graph.access_token) model_or_profile.save() model_or_profile.extend_access_token()