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 does the code get ?
def getNewDerivation(elementNode): return WriteDerivation(elementNode)
null
null
null
new derivation
codeqa
def get New Derivation element Node return Write Derivation element Node
null
null
null
null
Question: What does the code get ? Code: def getNewDerivation(elementNode): return WriteDerivation(elementNode)
null
null
null
What has specified permission ?
def assert_request_user_has_permission(request, permission_type): has_permission = request_user_has_permission(request=request, permission_type=permission_type) if (not has_permission): user_db = get_user_db_from_request(request=request) raise ResourceTypeAccessDeniedError(user_db=user_db, permission_type=permission_type)
null
null
null
currently logged - in user
codeqa
def assert request user has permission request permission type has permission request user has permission request request permission type permission type if not has permission user db get user db from request request request raise Resource Type Access Denied Error user db user db permission type permission type
null
null
null
null
Question: What has specified permission ? Code: def assert_request_user_has_permission(request, permission_type): has_permission = request_user_has_permission(request=request, permission_type=permission_type) if (not has_permission): user_db = get_user_db_from_request(request=request) raise ResourceTypeAccessDeniedError(user_db=user_db, permission_type=permission_type)
null
null
null
When did user log ?
def assert_request_user_has_permission(request, permission_type): has_permission = request_user_has_permission(request=request, permission_type=permission_type) if (not has_permission): user_db = get_user_db_from_request(request=request) raise ResourceTypeAccessDeniedError(user_db=user_db, permission_type=permission_type)
null
null
null
currently
codeqa
def assert request user has permission request permission type has permission request user has permission request request permission type permission type if not has permission user db get user db from request request request raise Resource Type Access Denied Error user db user db permission type permission type
null
null
null
null
Question: When did user log ? Code: def assert_request_user_has_permission(request, permission_type): has_permission = request_user_has_permission(request=request, permission_type=permission_type) if (not has_permission): user_db = get_user_db_from_request(request=request) raise ResourceTypeAccessDeniedError(user_db=user_db, permission_type=permission_type)
null
null
null
What does the code get ?
def getArcPath(xmlElement): begin = xmlElement.getPreviousVertex(Vector3()) end = evaluate.getVector3FromXMLElement(xmlElement) largeArcFlag = evaluate.getEvaluatedBooleanDefault(True, 'largeArcFlag', xmlElement) radius = lineation.getComplexByPrefix('radius', complex(1.0, 1.0), xmlElement) sweepFlag = evaluate.getEvaluatedBooleanDefault(True, 'sweepFlag', xmlElement) xAxisRotation = math.radians(evaluate.getEvaluatedFloatDefault(0.0, 'xAxisRotation', xmlElement)) arcComplexes = svg_reader.getArcComplexes(begin.dropAxis(), end.dropAxis(), largeArcFlag, radius, sweepFlag, xAxisRotation) path = [] if (len(arcComplexes) < 1): return [] incrementZ = ((end.z - begin.z) / float(len(arcComplexes))) z = begin.z for pointIndex in xrange(len(arcComplexes)): pointComplex = arcComplexes[pointIndex] z += incrementZ path.append(Vector3(pointComplex.real, pointComplex.imag, z)) if (len(path) > 0): path[(-1)] = end return path
null
null
null
the arc path
codeqa
def get Arc Path xml Element begin xml Element get Previous Vertex Vector 3 end evaluate get Vector 3 From XML Element xml Element large Arc Flag evaluate get Evaluated Boolean Default True 'large Arc Flag' xml Element radius lineation get Complex By Prefix 'radius' complex 1 0 1 0 xml Element sweep Flag evaluate get Evaluated Boolean Default True 'sweep Flag' xml Element x Axis Rotation math radians evaluate get Evaluated Float Default 0 0 'x Axis Rotation' xml Element arc Complexes svg reader get Arc Complexes begin drop Axis end drop Axis large Arc Flag radius sweep Flag x Axis Rotation path []if len arc Complexes < 1 return []increment Z end z - begin z / float len arc Complexes z begin zfor point Index in xrange len arc Complexes point Complex arc Complexes[point Index]z + increment Zpath append Vector 3 point Complex real point Complex imag z if len path > 0 path[ -1 ] endreturn path
null
null
null
null
Question: What does the code get ? Code: def getArcPath(xmlElement): begin = xmlElement.getPreviousVertex(Vector3()) end = evaluate.getVector3FromXMLElement(xmlElement) largeArcFlag = evaluate.getEvaluatedBooleanDefault(True, 'largeArcFlag', xmlElement) radius = lineation.getComplexByPrefix('radius', complex(1.0, 1.0), xmlElement) sweepFlag = evaluate.getEvaluatedBooleanDefault(True, 'sweepFlag', xmlElement) xAxisRotation = math.radians(evaluate.getEvaluatedFloatDefault(0.0, 'xAxisRotation', xmlElement)) arcComplexes = svg_reader.getArcComplexes(begin.dropAxis(), end.dropAxis(), largeArcFlag, radius, sweepFlag, xAxisRotation) path = [] if (len(arcComplexes) < 1): return [] incrementZ = ((end.z - begin.z) / float(len(arcComplexes))) z = begin.z for pointIndex in xrange(len(arcComplexes)): pointComplex = arcComplexes[pointIndex] z += incrementZ path.append(Vector3(pointComplex.real, pointComplex.imag, z)) if (len(path) > 0): path[(-1)] = end return path
null
null
null
What does the code return after it has exited ?
def command_output(cmd, shell=False): cmd = convert_command_args(cmd) proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=(platform.system() != 'Windows'), shell=shell) (stdout, stderr) = proc.communicate() if proc.returncode: raise subprocess.CalledProcessError(returncode=proc.returncode, cmd=' '.join(cmd), output=(stdout + stderr)) return stdout
null
null
null
its output
codeqa
def command output cmd shell False cmd convert command args cmd proc subprocess Popen cmd stdout subprocess PIPE stderr subprocess PIPE close fds platform system ' Windows' shell shell stdout stderr proc communicate if proc returncode raise subprocess Called Process Error returncode proc returncode cmd '' join cmd output stdout + stderr return stdout
null
null
null
null
Question: What does the code return after it has exited ? Code: def command_output(cmd, shell=False): cmd = convert_command_args(cmd) proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=(platform.system() != 'Windows'), shell=shell) (stdout, stderr) = proc.communicate() if proc.returncode: raise subprocess.CalledProcessError(returncode=proc.returncode, cmd=' '.join(cmd), output=(stdout + stderr)) return stdout
null
null
null
What does the code run after it has exited ?
def command_output(cmd, shell=False): cmd = convert_command_args(cmd) proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=(platform.system() != 'Windows'), shell=shell) (stdout, stderr) = proc.communicate() if proc.returncode: raise subprocess.CalledProcessError(returncode=proc.returncode, cmd=' '.join(cmd), output=(stdout + stderr)) return stdout
null
null
null
the command
codeqa
def command output cmd shell False cmd convert command args cmd proc subprocess Popen cmd stdout subprocess PIPE stderr subprocess PIPE close fds platform system ' Windows' shell shell stdout stderr proc communicate if proc returncode raise subprocess Called Process Error returncode proc returncode cmd '' join cmd output stdout + stderr return stdout
null
null
null
null
Question: What does the code run after it has exited ? Code: def command_output(cmd, shell=False): cmd = convert_command_args(cmd) proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=(platform.system() != 'Windows'), shell=shell) (stdout, stderr) = proc.communicate() if proc.returncode: raise subprocess.CalledProcessError(returncode=proc.returncode, cmd=' '.join(cmd), output=(stdout + stderr)) return stdout
null
null
null
When does the code run the command ?
def command_output(cmd, shell=False): cmd = convert_command_args(cmd) proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=(platform.system() != 'Windows'), shell=shell) (stdout, stderr) = proc.communicate() if proc.returncode: raise subprocess.CalledProcessError(returncode=proc.returncode, cmd=' '.join(cmd), output=(stdout + stderr)) return stdout
null
null
null
after it has exited
codeqa
def command output cmd shell False cmd convert command args cmd proc subprocess Popen cmd stdout subprocess PIPE stderr subprocess PIPE close fds platform system ' Windows' shell shell stdout stderr proc communicate if proc returncode raise subprocess Called Process Error returncode proc returncode cmd '' join cmd output stdout + stderr return stdout
null
null
null
null
Question: When does the code run the command ? Code: def command_output(cmd, shell=False): cmd = convert_command_args(cmd) proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=(platform.system() != 'Windows'), shell=shell) (stdout, stderr) = proc.communicate() if proc.returncode: raise subprocess.CalledProcessError(returncode=proc.returncode, cmd=' '.join(cmd), output=(stdout + stderr)) return stdout
null
null
null
When does the code return its output ?
def command_output(cmd, shell=False): cmd = convert_command_args(cmd) proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=(platform.system() != 'Windows'), shell=shell) (stdout, stderr) = proc.communicate() if proc.returncode: raise subprocess.CalledProcessError(returncode=proc.returncode, cmd=' '.join(cmd), output=(stdout + stderr)) return stdout
null
null
null
after it has exited
codeqa
def command output cmd shell False cmd convert command args cmd proc subprocess Popen cmd stdout subprocess PIPE stderr subprocess PIPE close fds platform system ' Windows' shell shell stdout stderr proc communicate if proc returncode raise subprocess Called Process Error returncode proc returncode cmd '' join cmd output stdout + stderr return stdout
null
null
null
null
Question: When does the code return its output ? Code: def command_output(cmd, shell=False): cmd = convert_command_args(cmd) proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=(platform.system() != 'Windows'), shell=shell) (stdout, stderr) = proc.communicate() if proc.returncode: raise subprocess.CalledProcessError(returncode=proc.returncode, cmd=' '.join(cmd), output=(stdout + stderr)) return stdout
null
null
null
What can we merge into one line ?
def _CanMergeLineIntoIfStatement(lines, limit): if ((len(lines[1].tokens) == 1) and lines[1].last.is_multiline_string): return True if (lines[0].lineno != lines[1].lineno): return False if (lines[1].last.total_length >= limit): return False return style.Get('JOIN_MULTIPLE_LINES')
null
null
null
a short if - then statement
codeqa
def Can Merge Line Into If Statement lines limit if len lines[ 1 ] tokens 1 and lines[ 1 ] last is multiline string return Trueif lines[ 0 ] lineno lines[ 1 ] lineno return Falseif lines[ 1 ] last total length > limit return Falsereturn style Get 'JOIN MULTIPLE LINES'
null
null
null
null
Question: What can we merge into one line ? Code: def _CanMergeLineIntoIfStatement(lines, limit): if ((len(lines[1].tokens) == 1) and lines[1].last.is_multiline_string): return True if (lines[0].lineno != lines[1].lineno): return False if (lines[1].last.total_length >= limit): return False return style.Get('JOIN_MULTIPLE_LINES')
null
null
null
What does the code convert into a range with error handling ?
def from_tuple(tup): if (len(tup) not in (2, 3)): raise ValueError(('tuple must contain 2 or 3 elements, not: %d (%r' % (len(tup), tup))) return range(*tup)
null
null
null
a tuple
codeqa
def from tuple tup if len tup not in 2 3 raise Value Error 'tuplemustcontain 2 or 3 elements not %d %r' % len tup tup return range *tup
null
null
null
null
Question: What does the code convert into a range with error handling ? Code: def from_tuple(tup): if (len(tup) not in (2, 3)): raise ValueError(('tuple must contain 2 or 3 elements, not: %d (%r' % (len(tup), tup))) return range(*tup)
null
null
null
What does the code send ?
def post(url, data=None, json=None, **kwargs): return request('post', url, data=data, json=json, **kwargs)
null
null
null
a post request
codeqa
def post url data None json None **kwargs return request 'post' url data data json json **kwargs
null
null
null
null
Question: What does the code send ? Code: def post(url, data=None, json=None, **kwargs): return request('post', url, data=data, json=json, **kwargs)
null
null
null
What contain other square roots if possible ?
def sqrtdenest(expr, max_iter=3): expr = expand_mul(sympify(expr)) for i in range(max_iter): z = _sqrtdenest0(expr) if (expr == z): return expr expr = z return expr
null
null
null
an expression
codeqa
def sqrtdenest expr max iter 3 expr expand mul sympify expr for i in range max iter z sqrtdenest 0 expr if expr z return exprexpr zreturn expr
null
null
null
null
Question: What contain other square roots if possible ? Code: def sqrtdenest(expr, max_iter=3): expr = expand_mul(sympify(expr)) for i in range(max_iter): z = _sqrtdenest0(expr) if (expr == z): return expr expr = z return expr
null
null
null
What does the code get ?
def debug_logger(name='test'): return DebugLogAdapter(DebugLogger(), name)
null
null
null
a named adapted debug logger
codeqa
def debug logger name 'test' return Debug Log Adapter Debug Logger name
null
null
null
null
Question: What does the code get ? Code: def debug_logger(name='test'): return DebugLogAdapter(DebugLogger(), name)
null
null
null
What does the code populate for the given criteria ?
@register.tag def get_admin_log(parser, token): tokens = token.contents.split() if (len(tokens) < 4): raise template.TemplateSyntaxError("'get_admin_log' statements require two arguments") if (not tokens[1].isdigit()): raise template.TemplateSyntaxError("First argument to 'get_admin_log' must be an integer") if (tokens[2] != 'as'): raise template.TemplateSyntaxError("Second argument to 'get_admin_log' must be 'as'") if (len(tokens) > 4): if (tokens[4] != 'for_user'): raise template.TemplateSyntaxError("Fourth argument to 'get_admin_log' must be 'for_user'") return AdminLogNode(limit=tokens[1], varname=tokens[3], user=(((len(tokens) > 5) and tokens[5]) or None))
null
null
null
a template variable with the admin log
codeqa
@register tagdef get admin log parser token tokens token contents split if len tokens < 4 raise template Template Syntax Error "'get admin log'statementsrequiretwoarguments" if not tokens[ 1 ] isdigit raise template Template Syntax Error " Firstargumentto'get admin log'mustbeaninteger" if tokens[ 2 ] 'as' raise template Template Syntax Error " Secondargumentto'get admin log'mustbe'as'" if len tokens > 4 if tokens[ 4 ] 'for user' raise template Template Syntax Error " Fourthargumentto'get admin log'mustbe'for user'" return Admin Log Node limit tokens[ 1 ] varname tokens[ 3 ] user len tokens > 5 and tokens[ 5 ] or None
null
null
null
null
Question: What does the code populate for the given criteria ? Code: @register.tag def get_admin_log(parser, token): tokens = token.contents.split() if (len(tokens) < 4): raise template.TemplateSyntaxError("'get_admin_log' statements require two arguments") if (not tokens[1].isdigit()): raise template.TemplateSyntaxError("First argument to 'get_admin_log' must be an integer") if (tokens[2] != 'as'): raise template.TemplateSyntaxError("Second argument to 'get_admin_log' must be 'as'") if (len(tokens) > 4): if (tokens[4] != 'for_user'): raise template.TemplateSyntaxError("Fourth argument to 'get_admin_log' must be 'for_user'") return AdminLogNode(limit=tokens[1], varname=tokens[3], user=(((len(tokens) > 5) and tokens[5]) or None))
null
null
null
What does the code compute ?
def polygon_area(pr, pc): pr = np.asarray(pr) pc = np.asarray(pc) return (0.5 * np.abs(np.sum(((pc[:(-1)] * pr[1:]) - (pc[1:] * pr[:(-1)])))))
null
null
null
the area of a polygon
codeqa
def polygon area pr pc pr np asarray pr pc np asarray pc return 0 5 * np abs np sum pc[ -1 ] * pr[ 1 ] - pc[ 1 ] * pr[ -1 ]
null
null
null
null
Question: What does the code compute ? Code: def polygon_area(pr, pc): pr = np.asarray(pr) pc = np.asarray(pc) return (0.5 * np.abs(np.sum(((pc[:(-1)] * pr[1:]) - (pc[1:] * pr[:(-1)])))))
null
null
null
What obeys over18 filtering rules ?
def set_obey_over18(): c.obey_over18 = (request.GET.get('obey_over18') == 'true')
null
null
null
api
codeqa
def set obey over 18 c obey over 18 request GET get 'obey over 18 ' 'true'
null
null
null
null
Question: What obeys over18 filtering rules ? Code: def set_obey_over18(): c.obey_over18 = (request.GET.get('obey_over18') == 'true')
null
null
null
What returns on the 1-indexed line ?
def LineTextInCurrentBuffer(line_number): return vim.current.buffer[(line_number - 1)]
null
null
null
the text
codeqa
def Line Text In Current Buffer line number return vim current buffer[ line number - 1 ]
null
null
null
null
Question: What returns on the 1-indexed line ? Code: def LineTextInCurrentBuffer(line_number): return vim.current.buffer[(line_number - 1)]
null
null
null
Where does the text return ?
def LineTextInCurrentBuffer(line_number): return vim.current.buffer[(line_number - 1)]
null
null
null
on the 1-indexed line
codeqa
def Line Text In Current Buffer line number return vim current buffer[ line number - 1 ]
null
null
null
null
Question: Where does the text return ? Code: def LineTextInCurrentBuffer(line_number): return vim.current.buffer[(line_number - 1)]
null
null
null
Where do connections and sockets send ?
def allow_connection_pickling(): from multiprocessing import reduction
null
null
null
between processes
codeqa
def allow connection pickling from multiprocessing import reduction
null
null
null
null
Question: Where do connections and sockets send ? Code: def allow_connection_pickling(): from multiprocessing import reduction
null
null
null
What is sending between processes ?
def allow_connection_pickling(): from multiprocessing import reduction
null
null
null
connections and sockets
codeqa
def allow connection pickling from multiprocessing import reduction
null
null
null
null
Question: What is sending between processes ? Code: def allow_connection_pickling(): from multiprocessing import reduction
null
null
null
What does the code get ?
def get_image_model_string(): return getattr(settings, u'WAGTAILIMAGES_IMAGE_MODEL', u'wagtailimages.Image')
null
null
null
the dotted app
codeqa
def get image model string return getattr settings u'WAGTAILIMAGES IMAGE MODEL' u'wagtailimages Image'
null
null
null
null
Question: What does the code get ? Code: def get_image_model_string(): return getattr(settings, u'WAGTAILIMAGES_IMAGE_MODEL', u'wagtailimages.Image')
null
null
null
What does the code ensure ?
def route_table_absent(name, region=None, key=None, keyid=None, profile=None): ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} r = __salt__['boto_vpc.get_resource_id']('route_table', name=name, region=region, key=key, keyid=keyid, profile=profile) if ('error' in r): ret['result'] = False ret['comment'] = r['error']['message'] return ret rtbl_id = r['id'] if (not rtbl_id): ret['comment'] = 'Route table {0} does not exist.'.format(name) return ret if __opts__['test']: ret['comment'] = 'Route table {0} is set to be removed.'.format(name) ret['result'] = None return ret r = __salt__['boto_vpc.delete_route_table'](route_table_name=name, region=region, key=key, keyid=keyid, profile=profile) if ('error' in r): ret['result'] = False ret['comment'] = 'Failed to delete route table: {0}'.format(r['error']['message']) return ret ret['changes']['old'] = {'route_table': rtbl_id} ret['changes']['new'] = {'route_table': None} ret['comment'] = 'Route table {0} deleted.'.format(name) return ret
null
null
null
the named route table is absent
codeqa
def route table absent name region None key None keyid None profile None ret {'name' name 'result' True 'comment' '' 'changes' {}}r salt ['boto vpc get resource id'] 'route table' name name region region key key keyid keyid profile profile if 'error' in r ret['result'] Falseret['comment'] r['error']['message']return retrtbl id r['id']if not rtbl id ret['comment'] ' Routetable{ 0 }doesnotexist ' format name return retif opts ['test'] ret['comment'] ' Routetable{ 0 }issettoberemoved ' format name ret['result'] Nonereturn retr salt ['boto vpc delete route table'] route table name name region region key key keyid keyid profile profile if 'error' in r ret['result'] Falseret['comment'] ' Failedtodeleteroutetable {0 }' format r['error']['message'] return retret['changes']['old'] {'route table' rtbl id}ret['changes']['new'] {'route table' None}ret['comment'] ' Routetable{ 0 }deleted ' format name return ret
null
null
null
null
Question: What does the code ensure ? Code: def route_table_absent(name, region=None, key=None, keyid=None, profile=None): ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} r = __salt__['boto_vpc.get_resource_id']('route_table', name=name, region=region, key=key, keyid=keyid, profile=profile) if ('error' in r): ret['result'] = False ret['comment'] = r['error']['message'] return ret rtbl_id = r['id'] if (not rtbl_id): ret['comment'] = 'Route table {0} does not exist.'.format(name) return ret if __opts__['test']: ret['comment'] = 'Route table {0} is set to be removed.'.format(name) ret['result'] = None return ret r = __salt__['boto_vpc.delete_route_table'](route_table_name=name, region=region, key=key, keyid=keyid, profile=profile) if ('error' in r): ret['result'] = False ret['comment'] = 'Failed to delete route table: {0}'.format(r['error']['message']) return ret ret['changes']['old'] = {'route_table': rtbl_id} ret['changes']['new'] = {'route_table': None} ret['comment'] = 'Route table {0} deleted.'.format(name) return ret
null
null
null
How does a tuple of return ?
def _connect(host=DEFAULT_HOST, port=DEFAULT_PORT): if str(port).isdigit(): return memcache.Client(['{0}:{1}'.format(host, port)], debug=0) raise SaltInvocationError('port must be an integer')
null
null
null
with config
codeqa
def connect host DEFAULT HOST port DEFAULT PORT if str port isdigit return memcache Client ['{ 0 } {1 }' format host port ] debug 0 raise Salt Invocation Error 'portmustbeaninteger'
null
null
null
null
Question: How does a tuple of return ? Code: def _connect(host=DEFAULT_HOST, port=DEFAULT_PORT): if str(port).isdigit(): return memcache.Client(['{0}:{1}'.format(host, port)], debug=0) raise SaltInvocationError('port must be an integer')
null
null
null
What does the code make ?
def bulk_update_private(context, data_dict): _check_access('bulk_update_private', context, data_dict) _bulk_update_dataset(context, data_dict, {'private': True})
null
null
null
a list of datasets private
codeqa
def bulk update private context data dict check access 'bulk update private' context data dict bulk update dataset context data dict {'private' True}
null
null
null
null
Question: What does the code make ? Code: def bulk_update_private(context, data_dict): _check_access('bulk_update_private', context, data_dict) _bulk_update_dataset(context, data_dict, {'private': True})
null
null
null
How does the code find a static file with the given path ?
def find(path, all=False): matches = [] for finder in get_finders(): result = finder.find(path, all=all) if ((not all) and result): return result if (not isinstance(result, (list, tuple))): result = [result] matches.extend(result) if matches: return matches return ((all and []) or None)
null
null
null
using all enabled finders
codeqa
def find path all False matches []for finder in get finders result finder find path all all if not all and result return resultif not isinstance result list tuple result [result]matches extend result if matches return matchesreturn all and [] or None
null
null
null
null
Question: How does the code find a static file with the given path ? Code: def find(path, all=False): matches = [] for finder in get_finders(): result = finder.find(path, all=all) if ((not all) and result): return result if (not isinstance(result, (list, tuple))): result = [result] matches.extend(result) if matches: return matches return ((all and []) or None)
null
null
null
What does the code find using all enabled finders ?
def find(path, all=False): matches = [] for finder in get_finders(): result = finder.find(path, all=all) if ((not all) and result): return result if (not isinstance(result, (list, tuple))): result = [result] matches.extend(result) if matches: return matches return ((all and []) or None)
null
null
null
a static file with the given path
codeqa
def find path all False matches []for finder in get finders result finder find path all all if not all and result return resultif not isinstance result list tuple result [result]matches extend result if matches return matchesreturn all and [] or None
null
null
null
null
Question: What does the code find using all enabled finders ? Code: def find(path, all=False): matches = [] for finder in get_finders(): result = finder.find(path, all=all) if ((not all) and result): return result if (not isinstance(result, (list, tuple))): result = [result] matches.extend(result) if matches: return matches return ((all and []) or None)
null
null
null
What reads exactly * ?
def _read_exactly(sock, amt): data = '' while (amt > 0): chunk = sock.recv(amt) data += chunk amt -= len(chunk) return data
null
null
null
exactly *
codeqa
def read exactly sock amt data ''while amt > 0 chunk sock recv amt data + chunkamt - len chunk return data
null
null
null
null
Question: What reads exactly * ? Code: def _read_exactly(sock, amt): data = '' while (amt > 0): chunk = sock.recv(amt) data += chunk amt -= len(chunk) return data
null
null
null
What do exactly * read ?
def _read_exactly(sock, amt): data = '' while (amt > 0): chunk = sock.recv(amt) data += chunk amt -= len(chunk) return data
null
null
null
exactly *
codeqa
def read exactly sock amt data ''while amt > 0 chunk sock recv amt data + chunkamt - len chunk return data
null
null
null
null
Question: What do exactly * read ? Code: def _read_exactly(sock, amt): data = '' while (amt > 0): chunk = sock.recv(amt) data += chunk amt -= len(chunk) return data
null
null
null
What is representing the default user agent ?
def default_user_agent(): _implementation = platform.python_implementation() if (_implementation == 'CPython'): _implementation_version = platform.python_version() elif (_implementation == 'PyPy'): _implementation_version = ('%s.%s.%s' % (sys.pypy_version_info.major, sys.pypy_version_info.minor, sys.pypy_version_info.micro)) if (sys.pypy_version_info.releaselevel != 'final'): _implementation_version = ''.join([_implementation_version, sys.pypy_version_info.releaselevel]) elif (_implementation == 'Jython'): _implementation_version = platform.python_version() elif (_implementation == 'IronPython'): _implementation_version = platform.python_version() else: _implementation_version = 'Unknown' try: p_system = platform.system() p_release = platform.release() except IOError: p_system = 'Unknown' p_release = 'Unknown' return ' '.join([('python-requests/%s' % __version__), ('%s/%s' % (_implementation, _implementation_version)), ('%s/%s' % (p_system, p_release))])
null
null
null
a string
codeqa
def default user agent implementation platform python implementation if implementation 'C Python' implementation version platform python version elif implementation ' Py Py' implementation version '%s %s %s' % sys pypy version info major sys pypy version info minor sys pypy version info micro if sys pypy version info releaselevel 'final' implementation version '' join [ implementation version sys pypy version info releaselevel] elif implementation ' Jython' implementation version platform python version elif implementation ' Iron Python' implementation version platform python version else implementation version ' Unknown'try p system platform system p release platform release except IO Error p system ' Unknown'p release ' Unknown'return '' join [ 'python-requests/%s' % version '%s/%s' % implementation implementation version '%s/%s' % p system p release ]
null
null
null
null
Question: What is representing the default user agent ? Code: def default_user_agent(): _implementation = platform.python_implementation() if (_implementation == 'CPython'): _implementation_version = platform.python_version() elif (_implementation == 'PyPy'): _implementation_version = ('%s.%s.%s' % (sys.pypy_version_info.major, sys.pypy_version_info.minor, sys.pypy_version_info.micro)) if (sys.pypy_version_info.releaselevel != 'final'): _implementation_version = ''.join([_implementation_version, sys.pypy_version_info.releaselevel]) elif (_implementation == 'Jython'): _implementation_version = platform.python_version() elif (_implementation == 'IronPython'): _implementation_version = platform.python_version() else: _implementation_version = 'Unknown' try: p_system = platform.system() p_release = platform.release() except IOError: p_system = 'Unknown' p_release = 'Unknown' return ' '.join([('python-requests/%s' % __version__), ('%s/%s' % (_implementation, _implementation_version)), ('%s/%s' % (p_system, p_release))])
null
null
null
What do a string represent ?
def default_user_agent(): _implementation = platform.python_implementation() if (_implementation == 'CPython'): _implementation_version = platform.python_version() elif (_implementation == 'PyPy'): _implementation_version = ('%s.%s.%s' % (sys.pypy_version_info.major, sys.pypy_version_info.minor, sys.pypy_version_info.micro)) if (sys.pypy_version_info.releaselevel != 'final'): _implementation_version = ''.join([_implementation_version, sys.pypy_version_info.releaselevel]) elif (_implementation == 'Jython'): _implementation_version = platform.python_version() elif (_implementation == 'IronPython'): _implementation_version = platform.python_version() else: _implementation_version = 'Unknown' try: p_system = platform.system() p_release = platform.release() except IOError: p_system = 'Unknown' p_release = 'Unknown' return ' '.join([('python-requests/%s' % __version__), ('%s/%s' % (_implementation, _implementation_version)), ('%s/%s' % (p_system, p_release))])
null
null
null
the default user agent
codeqa
def default user agent implementation platform python implementation if implementation 'C Python' implementation version platform python version elif implementation ' Py Py' implementation version '%s %s %s' % sys pypy version info major sys pypy version info minor sys pypy version info micro if sys pypy version info releaselevel 'final' implementation version '' join [ implementation version sys pypy version info releaselevel] elif implementation ' Jython' implementation version platform python version elif implementation ' Iron Python' implementation version platform python version else implementation version ' Unknown'try p system platform system p release platform release except IO Error p system ' Unknown'p release ' Unknown'return '' join [ 'python-requests/%s' % version '%s/%s' % implementation implementation version '%s/%s' % p system p release ]
null
null
null
null
Question: What do a string represent ? Code: def default_user_agent(): _implementation = platform.python_implementation() if (_implementation == 'CPython'): _implementation_version = platform.python_version() elif (_implementation == 'PyPy'): _implementation_version = ('%s.%s.%s' % (sys.pypy_version_info.major, sys.pypy_version_info.minor, sys.pypy_version_info.micro)) if (sys.pypy_version_info.releaselevel != 'final'): _implementation_version = ''.join([_implementation_version, sys.pypy_version_info.releaselevel]) elif (_implementation == 'Jython'): _implementation_version = platform.python_version() elif (_implementation == 'IronPython'): _implementation_version = platform.python_version() else: _implementation_version = 'Unknown' try: p_system = platform.system() p_release = platform.release() except IOError: p_system = 'Unknown' p_release = 'Unknown' return ' '.join([('python-requests/%s' % __version__), ('%s/%s' % (_implementation, _implementation_version)), ('%s/%s' % (p_system, p_release))])
null
null
null
What does the code get from the database ?
def get_category(app, id): sa_session = app.model.context.current return sa_session.query(app.model.Category).get(app.security.decode_id(id))
null
null
null
a category
codeqa
def get category app id sa session app model context currentreturn sa session query app model Category get app security decode id id
null
null
null
null
Question: What does the code get from the database ? Code: def get_category(app, id): sa_session = app.model.context.current return sa_session.query(app.model.Category).get(app.security.decode_id(id))
null
null
null
How do a queue name prefix ?
def add_queue_name_prefix(name): return (_get_queue_name_prefix() + name)
null
null
null
code
codeqa
def add queue name prefix name return get queue name prefix + name
null
null
null
null
Question: How do a queue name prefix ? Code: def add_queue_name_prefix(name): return (_get_queue_name_prefix() + name)
null
null
null
What takes arbitrary arguments ?
def data_to_lambda(data): return (lambda *args, **kwargs: copy.deepcopy(data))
null
null
null
a lambda function
codeqa
def data to lambda data return lambda *args **kwargs copy deepcopy data
null
null
null
null
Question: What takes arbitrary arguments ? Code: def data_to_lambda(data): return (lambda *args, **kwargs: copy.deepcopy(data))
null
null
null
What does a lambda function take ?
def data_to_lambda(data): return (lambda *args, **kwargs: copy.deepcopy(data))
null
null
null
arbitrary arguments
codeqa
def data to lambda data return lambda *args **kwargs copy deepcopy data
null
null
null
null
Question: What does a lambda function take ? Code: def data_to_lambda(data): return (lambda *args, **kwargs: copy.deepcopy(data))
null
null
null
What does the code remove from the dictionary ?
def removeListArtOfIllusionFromDictionary(dictionary, scrubKeys): euclidean.removeElementsFromDictionary(dictionary, ['bf:id', 'bf:type']) euclidean.removeElementsFromDictionary(dictionary, scrubKeys)
null
null
null
the list and art of illusion keys
codeqa
def remove List Art Of Illusion From Dictionary dictionary scrub Keys euclidean remove Elements From Dictionary dictionary ['bf id' 'bf type'] euclidean remove Elements From Dictionary dictionary scrub Keys
null
null
null
null
Question: What does the code remove from the dictionary ? Code: def removeListArtOfIllusionFromDictionary(dictionary, scrubKeys): euclidean.removeElementsFromDictionary(dictionary, ['bf:id', 'bf:type']) euclidean.removeElementsFromDictionary(dictionary, scrubKeys)
null
null
null
What is containing hyperbolic functions in terms of trigonometric functions ?
def hyper_as_trig(rv): from sympy.simplify.simplify import signsimp from sympy.simplify.radsimp import collect trigs = rv.atoms(TrigonometricFunction) reps = [(t, Dummy()) for t in trigs] masked = rv.xreplace(dict(reps)) reps = [(v, k) for (k, v) in reps] d = Dummy() return (_osborne(masked, d), (lambda x: collect(signsimp(_osbornei(x, d).xreplace(dict(reps))), S.ImaginaryUnit)))
null
null
null
an expression
codeqa
def hyper as trig rv from sympy simplify simplify import signsimpfrom sympy simplify radsimp import collecttrigs rv atoms Trigonometric Function reps [ t Dummy for t in trigs]masked rv xreplace dict reps reps [ v k for k v in reps]d Dummy return osborne masked d lambda x collect signsimp osbornei x d xreplace dict reps S Imaginary Unit
null
null
null
null
Question: What is containing hyperbolic functions in terms of trigonometric functions ? Code: def hyper_as_trig(rv): from sympy.simplify.simplify import signsimp from sympy.simplify.radsimp import collect trigs = rv.atoms(TrigonometricFunction) reps = [(t, Dummy()) for t in trigs] masked = rv.xreplace(dict(reps)) reps = [(v, k) for (k, v) in reps] d = Dummy() return (_osborne(masked, d), (lambda x: collect(signsimp(_osbornei(x, d).xreplace(dict(reps))), S.ImaginaryUnit)))
null
null
null
What does the code delete from the dashboard ?
@handle_response_format @treeio_login_required def dashboard_widget_delete(request, widget_id, response_format='html'): widget = get_object_or_404(Widget, pk=widget_id) if (widget.user == request.user.profile): widget.delete() return HttpResponseRedirect(reverse('core_dashboard_index'))
null
null
null
an existing widget
codeqa
@handle response format@treeio login requireddef dashboard widget delete request widget id response format 'html' widget get object or 404 Widget pk widget id if widget user request user profile widget delete return Http Response Redirect reverse 'core dashboard index'
null
null
null
null
Question: What does the code delete from the dashboard ? Code: @handle_response_format @treeio_login_required def dashboard_widget_delete(request, widget_id, response_format='html'): widget = get_object_or_404(Widget, pk=widget_id) if (widget.user == request.user.profile): widget.delete() return HttpResponseRedirect(reverse('core_dashboard_index'))
null
null
null
What does the code get ?
def getNewRepository(): return PostscriptRepository()
null
null
null
new repository
codeqa
def get New Repository return Postscript Repository
null
null
null
null
Question: What does the code get ? Code: def getNewRepository(): return PostscriptRepository()
null
null
null
What does the code write ?
def write_file(name, text, opts): fname = path.join(opts.destdir, ('%s.%s' % (name, opts.suffix))) if opts.dryrun: print ('Would create file %s.' % fname) return if ((not opts.force) and path.isfile(fname)): print ('File %s already exists, skipping.' % fname) else: print ('Creating file %s.' % fname) f = open(fname, 'w') try: f.write(text) finally: f.close()
null
null
null
the output file for module / package < name >
codeqa
def write file name text opts fname path join opts destdir '%s %s' % name opts suffix if opts dryrun print ' Wouldcreatefile%s ' % fname returnif not opts force and path isfile fname print ' File%salreadyexists skipping ' % fname else print ' Creatingfile%s ' % fname f open fname 'w' try f write text finally f close
null
null
null
null
Question: What does the code write ? Code: def write_file(name, text, opts): fname = path.join(opts.destdir, ('%s.%s' % (name, opts.suffix))) if opts.dryrun: print ('Would create file %s.' % fname) return if ((not opts.force) and path.isfile(fname)): print ('File %s already exists, skipping.' % fname) else: print ('Creating file %s.' % fname) f = open(fname, 'w') try: f.write(text) finally: f.close()
null
null
null
What does fixture return ?
@pytest.fixture def temporary_table(): bigquery_client = bigquery.Client() dataset = bigquery_client.dataset(DATASET_ID) tables = [] def factory(table_name): new_table = dataset.table(table_name) if new_table.exists(): new_table.delete() tables.append(new_table) return new_table (yield factory) for table in tables: if table.exists(): table.delete()
null
null
null
a factory
codeqa
@pytest fixturedef temporary table bigquery client bigquery Client dataset bigquery client dataset DATASET ID tables []def factory table name new table dataset table table name if new table exists new table delete tables append new table return new table yield factory for table in tables if table exists table delete
null
null
null
null
Question: What does fixture return ? Code: @pytest.fixture def temporary_table(): bigquery_client = bigquery.Client() dataset = bigquery_client.dataset(DATASET_ID) tables = [] def factory(table_name): new_table = dataset.table(table_name) if new_table.exists(): new_table.delete() tables.append(new_table) return new_table (yield factory) for table in tables: if table.exists(): table.delete()
null
null
null
How will fixture be deleted after the test ?
@pytest.fixture def temporary_table(): bigquery_client = bigquery.Client() dataset = bigquery_client.dataset(DATASET_ID) tables = [] def factory(table_name): new_table = dataset.table(table_name) if new_table.exists(): new_table.delete() tables.append(new_table) return new_table (yield factory) for table in tables: if table.exists(): table.delete()
null
null
null
automatically
codeqa
@pytest fixturedef temporary table bigquery client bigquery Client dataset bigquery client dataset DATASET ID tables []def factory table name new table dataset table table name if new table exists new table delete tables append new table return new table yield factory for table in tables if table exists table delete
null
null
null
null
Question: How will fixture be deleted after the test ? Code: @pytest.fixture def temporary_table(): bigquery_client = bigquery.Client() dataset = bigquery_client.dataset(DATASET_ID) tables = [] def factory(table_name): new_table = dataset.table(table_name) if new_table.exists(): new_table.delete() tables.append(new_table) return new_table (yield factory) for table in tables: if table.exists(): table.delete()
null
null
null
When do tables not exist ?
@pytest.fixture def temporary_table(): bigquery_client = bigquery.Client() dataset = bigquery_client.dataset(DATASET_ID) tables = [] def factory(table_name): new_table = dataset.table(table_name) if new_table.exists(): new_table.delete() tables.append(new_table) return new_table (yield factory) for table in tables: if table.exists(): table.delete()
null
null
null
yet
codeqa
@pytest fixturedef temporary table bigquery client bigquery Client dataset bigquery client dataset DATASET ID tables []def factory table name new table dataset table table name if new table exists new table delete tables append new table return new table yield factory for table in tables if table exists table delete
null
null
null
null
Question: When do tables not exist ? Code: @pytest.fixture def temporary_table(): bigquery_client = bigquery.Client() dataset = bigquery_client.dataset(DATASET_ID) tables = [] def factory(table_name): new_table = dataset.table(table_name) if new_table.exists(): new_table.delete() tables.append(new_table) return new_table (yield factory) for table in tables: if table.exists(): table.delete()
null
null
null
When will fixture be deleted automatically ?
@pytest.fixture def temporary_table(): bigquery_client = bigquery.Client() dataset = bigquery_client.dataset(DATASET_ID) tables = [] def factory(table_name): new_table = dataset.table(table_name) if new_table.exists(): new_table.delete() tables.append(new_table) return new_table (yield factory) for table in tables: if table.exists(): table.delete()
null
null
null
after the test
codeqa
@pytest fixturedef temporary table bigquery client bigquery Client dataset bigquery client dataset DATASET ID tables []def factory table name new table dataset table table name if new table exists new table delete tables append new table return new table yield factory for table in tables if table exists table delete
null
null
null
null
Question: When will fixture be deleted automatically ? Code: @pytest.fixture def temporary_table(): bigquery_client = bigquery.Client() dataset = bigquery_client.dataset(DATASET_ID) tables = [] def factory(table_name): new_table = dataset.table(table_name) if new_table.exists(): new_table.delete() tables.append(new_table) return new_table (yield factory) for table in tables: if table.exists(): table.delete()
null
null
null
What returns a factory ?
@pytest.fixture def temporary_table(): bigquery_client = bigquery.Client() dataset = bigquery_client.dataset(DATASET_ID) tables = [] def factory(table_name): new_table = dataset.table(table_name) if new_table.exists(): new_table.delete() tables.append(new_table) return new_table (yield factory) for table in tables: if table.exists(): table.delete()
null
null
null
fixture
codeqa
@pytest fixturedef temporary table bigquery client bigquery Client dataset bigquery client dataset DATASET ID tables []def factory table name new table dataset table table name if new table exists new table delete tables append new table return new table yield factory for table in tables if table exists table delete
null
null
null
null
Question: What returns a factory ? Code: @pytest.fixture def temporary_table(): bigquery_client = bigquery.Client() dataset = bigquery_client.dataset(DATASET_ID) tables = [] def factory(table_name): new_table = dataset.table(table_name) if new_table.exists(): new_table.delete() tables.append(new_table) return new_table (yield factory) for table in tables: if table.exists(): table.delete()
null
null
null
What does the code get from a container ?
def _get_md5(name, path, run_func): output = run_func(name, 'md5sum {0}'.format(pipes.quote(path)), ignore_retcode=True)['stdout'] try: return output.split()[0] except IndexError: return None
null
null
null
the md5 checksum of a file
codeqa
def get md 5 name path run func output run func name 'md 5 sum{ 0 }' format pipes quote path ignore retcode True ['stdout']try return output split [0 ]except Index Error return None
null
null
null
null
Question: What does the code get from a container ? Code: def _get_md5(name, path, run_func): output = run_func(name, 'md5sum {0}'.format(pipes.quote(path)), ignore_retcode=True)['stdout'] try: return output.split()[0] except IndexError: return None
null
null
null
How do all tables which depend on the given tables find ?
def find_dependent_tables(tables, graph=None): if (graph is None): graph = _pokedex_graph tables = list(tables) dependents = set() def add_dependents_of(table): for dependent_table in graph.get(table, []): if (dependent_table not in dependents): dependents.add(dependent_table) add_dependents_of(dependent_table) for table in tables: add_dependents_of(table) dependents -= set(tables) return dependents
null
null
null
recursively
codeqa
def find dependent tables tables graph None if graph is None graph pokedex graphtables list tables dependents set def add dependents of table for dependent table in graph get table [] if dependent table not in dependents dependents add dependent table add dependents of dependent table for table in tables add dependents of table dependents - set tables return dependents
null
null
null
null
Question: How do all tables which depend on the given tables find ? Code: def find_dependent_tables(tables, graph=None): if (graph is None): graph = _pokedex_graph tables = list(tables) dependents = set() def add_dependents_of(table): for dependent_table in graph.get(table, []): if (dependent_table not in dependents): dependents.add(dependent_table) add_dependents_of(dependent_table) for table in tables: add_dependents_of(table) dependents -= set(tables) return dependents
null
null
null
What does the code obtain ?
def run(config, plugins): try: (installer, authenticator) = plug_sel.choose_configurator_plugins(config, plugins, 'run') except errors.PluginSelectionError as e: return e.message (domains, certname) = _find_domains_or_certname(config, installer) le_client = _init_le_client(config, authenticator, installer) (action, lineage) = _auth_from_available(le_client, config, domains, certname) le_client.deploy_certificate(domains, lineage.privkey, lineage.cert, lineage.chain, lineage.fullchain) le_client.enhance_config(domains, lineage.chain) if (action in ('newcert', 'reinstall')): display_ops.success_installation(domains) else: display_ops.success_renewal(domains) _suggest_donation_if_appropriate(config, action)
null
null
null
a certificate
codeqa
def run config plugins try installer authenticator plug sel choose configurator plugins config plugins 'run' except errors Plugin Selection Error as e return e message domains certname find domains or certname config installer le client init le client config authenticator installer action lineage auth from available le client config domains certname le client deploy certificate domains lineage privkey lineage cert lineage chain lineage fullchain le client enhance config domains lineage chain if action in 'newcert' 'reinstall' display ops success installation domains else display ops success renewal domains suggest donation if appropriate config action
null
null
null
null
Question: What does the code obtain ? Code: def run(config, plugins): try: (installer, authenticator) = plug_sel.choose_configurator_plugins(config, plugins, 'run') except errors.PluginSelectionError as e: return e.message (domains, certname) = _find_domains_or_certname(config, installer) le_client = _init_le_client(config, authenticator, installer) (action, lineage) = _auth_from_available(le_client, config, domains, certname) le_client.deploy_certificate(domains, lineage.privkey, lineage.cert, lineage.chain, lineage.fullchain) le_client.enhance_config(domains, lineage.chain) if (action in ('newcert', 'reinstall')): display_ops.success_installation(domains) else: display_ops.success_renewal(domains) _suggest_donation_if_appropriate(config, action)
null
null
null
When do f evaluate ?
def sh_command_with(f, *args): args = list(args) out = [] for n in range(len(args)): args[n] = sh_string(args[n]) if hasattr(f, '__call__'): out.append(f(*args)) else: out.append((f % tuple(args))) return ';'.join(out)
null
null
null
whenever f is a function and f % otherwise
codeqa
def sh command with f *args args list args out []for n in range len args args[n] sh string args[n] if hasattr f ' call ' out append f *args else out append f % tuple args return ' ' join out
null
null
null
null
Question: When do f evaluate ? Code: def sh_command_with(f, *args): args = list(args) out = [] for n in range(len(args)): args[n] = sh_string(args[n]) if hasattr(f, '__call__'): out.append(f(*args)) else: out.append((f % tuple(args))) return ';'.join(out)
null
null
null
When is f a function ?
def sh_command_with(f, *args): args = list(args) out = [] for n in range(len(args)): args[n] = sh_string(args[n]) if hasattr(f, '__call__'): out.append(f(*args)) else: out.append((f % tuple(args))) return ';'.join(out)
null
null
null
whenever
codeqa
def sh command with f *args args list args out []for n in range len args args[n] sh string args[n] if hasattr f ' call ' out append f *args else out append f % tuple args return ' ' join out
null
null
null
null
Question: When is f a function ? Code: def sh_command_with(f, *args): args = list(args) out = [] for n in range(len(args)): args[n] = sh_string(args[n]) if hasattr(f, '__call__'): out.append(f(*args)) else: out.append((f % tuple(args))) return ';'.join(out)
null
null
null
What does command return ?
def sh_command_with(f, *args): args = list(args) out = [] for n in range(len(args)): args[n] = sh_string(args[n]) if hasattr(f, '__call__'): out.append(f(*args)) else: out.append((f % tuple(args))) return ';'.join(out)
null
null
null
a command create by evaluating f whenever f is a function and f % otherwise
codeqa
def sh command with f *args args list args out []for n in range len args args[n] sh string args[n] if hasattr f ' call ' out append f *args else out append f % tuple args return ' ' join out
null
null
null
null
Question: What does command return ? Code: def sh_command_with(f, *args): args = list(args) out = [] for n in range(len(args)): args[n] = sh_string(args[n]) if hasattr(f, '__call__'): out.append(f(*args)) else: out.append((f % tuple(args))) return ';'.join(out)
null
null
null
What returns a command create by evaluating f whenever f is a function and f % otherwise ?
def sh_command_with(f, *args): args = list(args) out = [] for n in range(len(args)): args[n] = sh_string(args[n]) if hasattr(f, '__call__'): out.append(f(*args)) else: out.append((f % tuple(args))) return ';'.join(out)
null
null
null
command
codeqa
def sh command with f *args args list args out []for n in range len args args[n] sh string args[n] if hasattr f ' call ' out append f *args else out append f % tuple args return ' ' join out
null
null
null
null
Question: What returns a command create by evaluating f whenever f is a function and f % otherwise ? Code: def sh_command_with(f, *args): args = list(args) out = [] for n in range(len(args)): args[n] = sh_string(args[n]) if hasattr(f, '__call__'): out.append(f(*args)) else: out.append((f % tuple(args))) return ';'.join(out)
null
null
null
What can specify which back - end parser to use ?
@pytest.mark.skipif('not HAS_BEAUTIFUL_SOUP') def test_backend_parsers(): for parser in ('lxml', 'xml', 'html.parser', 'html5lib'): try: table = Table.read('t/html2.html', format='ascii.html', htmldict={'parser': parser}, guess=False) except FeatureNotFound: if (parser == 'html.parser'): raise with pytest.raises(FeatureNotFound): Table.read('t/html2.html', format='ascii.html', htmldict={'parser': 'foo'}, guess=False)
null
null
null
the user
codeqa
@pytest mark skipif 'not HAS BEAUTIFUL SOUP' def test backend parsers for parser in 'lxml' 'xml' 'html parser' 'html 5 lib' try table Table read 't/html 2 html' format 'ascii html' htmldict {'parser' parser} guess False except Feature Not Found if parser 'html parser' raisewith pytest raises Feature Not Found Table read 't/html 2 html' format 'ascii html' htmldict {'parser' 'foo'} guess False
null
null
null
null
Question: What can specify which back - end parser to use ? Code: @pytest.mark.skipif('not HAS_BEAUTIFUL_SOUP') def test_backend_parsers(): for parser in ('lxml', 'xml', 'html.parser', 'html5lib'): try: table = Table.read('t/html2.html', format='ascii.html', htmldict={'parser': parser}, guess=False) except FeatureNotFound: if (parser == 'html.parser'): raise with pytest.raises(FeatureNotFound): Table.read('t/html2.html', format='ascii.html', htmldict={'parser': 'foo'}, guess=False)
null
null
null
What can the user specify ?
@pytest.mark.skipif('not HAS_BEAUTIFUL_SOUP') def test_backend_parsers(): for parser in ('lxml', 'xml', 'html.parser', 'html5lib'): try: table = Table.read('t/html2.html', format='ascii.html', htmldict={'parser': parser}, guess=False) except FeatureNotFound: if (parser == 'html.parser'): raise with pytest.raises(FeatureNotFound): Table.read('t/html2.html', format='ascii.html', htmldict={'parser': 'foo'}, guess=False)
null
null
null
which back - end parser to use
codeqa
@pytest mark skipif 'not HAS BEAUTIFUL SOUP' def test backend parsers for parser in 'lxml' 'xml' 'html parser' 'html 5 lib' try table Table read 't/html 2 html' format 'ascii html' htmldict {'parser' parser} guess False except Feature Not Found if parser 'html parser' raisewith pytest raises Feature Not Found Table read 't/html 2 html' format 'ascii html' htmldict {'parser' 'foo'} guess False
null
null
null
null
Question: What can the user specify ? Code: @pytest.mark.skipif('not HAS_BEAUTIFUL_SOUP') def test_backend_parsers(): for parser in ('lxml', 'xml', 'html.parser', 'html5lib'): try: table = Table.read('t/html2.html', format='ascii.html', htmldict={'parser': parser}, guess=False) except FeatureNotFound: if (parser == 'html.parser'): raise with pytest.raises(FeatureNotFound): Table.read('t/html2.html', format='ascii.html', htmldict={'parser': 'foo'}, guess=False)
null
null
null
For what purpose do a db cursor return ?
def _cursor(): return connections[router.db_for_read(Document)].cursor()
null
null
null
for reading
codeqa
def cursor return connections[router db for read Document ] cursor
null
null
null
null
Question: For what purpose do a db cursor return ? Code: def _cursor(): return connections[router.db_for_read(Document)].cursor()
null
null
null
What contain a given string ?
def tag_autocomplete(context, data_dict): _check_access('tag_autocomplete', context, data_dict) (matching_tags, count) = _tag_search(context, data_dict) if matching_tags: return [tag.name for tag in matching_tags] else: return []
null
null
null
tag names
codeqa
def tag autocomplete context data dict check access 'tag autocomplete' context data dict matching tags count tag search context data dict if matching tags return [tag name for tag in matching tags]else return []
null
null
null
null
Question: What contain a given string ? Code: def tag_autocomplete(context, data_dict): _check_access('tag_autocomplete', context, data_dict) (matching_tags, count) = _tag_search(context, data_dict) if matching_tags: return [tag.name for tag in matching_tags] else: return []
null
null
null
What do tag names contain ?
def tag_autocomplete(context, data_dict): _check_access('tag_autocomplete', context, data_dict) (matching_tags, count) = _tag_search(context, data_dict) if matching_tags: return [tag.name for tag in matching_tags] else: return []
null
null
null
a given string
codeqa
def tag autocomplete context data dict check access 'tag autocomplete' context data dict matching tags count tag search context data dict if matching tags return [tag name for tag in matching tags]else return []
null
null
null
null
Question: What do tag names contain ? Code: def tag_autocomplete(context, data_dict): _check_access('tag_autocomplete', context, data_dict) (matching_tags, count) = _tag_search(context, data_dict) if matching_tags: return [tag.name for tag in matching_tags] else: return []
null
null
null
What does the code start ?
def start_tomcat(): run_as_root('/etc/init.d/tomcat start')
null
null
null
the tomcat service
codeqa
def start tomcat run as root '/etc/init d/tomcatstart'
null
null
null
null
Question: What does the code start ? Code: def start_tomcat(): run_as_root('/etc/init.d/tomcat start')
null
null
null
What does decorator for views check ?
def staff_member_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='admin:login'): actual_decorator = user_passes_test((lambda u: (u.is_active and u.is_staff)), login_url=login_url, redirect_field_name=redirect_field_name) if view_func: return actual_decorator(view_func) return actual_decorator
null
null
null
that the user is logged in and is a staff member
codeqa
def staff member required view func None redirect field name REDIRECT FIELD NAME login url 'admin login' actual decorator user passes test lambda u u is active and u is staff login url login url redirect field name redirect field name if view func return actual decorator view func return actual decorator
null
null
null
null
Question: What does decorator for views check ? Code: def staff_member_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='admin:login'): actual_decorator = user_passes_test((lambda u: (u.is_active and u.is_staff)), login_url=login_url, redirect_field_name=redirect_field_name) if view_func: return actual_decorator(view_func) return actual_decorator
null
null
null
What checks that the user is logged in and is a staff member ?
def staff_member_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='admin:login'): actual_decorator = user_passes_test((lambda u: (u.is_active and u.is_staff)), login_url=login_url, redirect_field_name=redirect_field_name) if view_func: return actual_decorator(view_func) return actual_decorator
null
null
null
decorator for views
codeqa
def staff member required view func None redirect field name REDIRECT FIELD NAME login url 'admin login' actual decorator user passes test lambda u u is active and u is staff login url login url redirect field name redirect field name if view func return actual decorator view func return actual decorator
null
null
null
null
Question: What checks that the user is logged in and is a staff member ? Code: def staff_member_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='admin:login'): actual_decorator = user_passes_test((lambda u: (u.is_active and u.is_staff)), login_url=login_url, redirect_field_name=redirect_field_name) if view_func: return actual_decorator(view_func) return actual_decorator
null
null
null
For what purpose does the code call the configuration template ?
def _configure(changes): cfgred = True reasons = [] fun = 'update_config' for key in ['added', 'updated', 'removed']: _updated_changes = changes.get(key, {}) if (not _updated_changes): continue _location = _updated_changes.get('location', '') _contact = _updated_changes.get('contact', '') _community = _updated_changes.get('community', {}) _chassis_id = _updated_changes.get('chassis_id', '') if (key == 'removed'): fun = 'remove_config' _ret = __salt__['snmp.{fun}'.format(fun=fun)](location=_location, contact=_contact, community=_community, chassis_id=_chassis_id, commit=False) cfgred = (cfgred and _ret.get('result')) if ((not _ret.get('result')) and _ret.get('comment')): reasons.append(_ret.get('comment')) return {'result': cfgred, 'comment': ('\n'.join(reasons) if reasons else '')}
null
null
null
to apply the configuration changes on the device
codeqa
def configure changes cfgred Truereasons []fun 'update config'for key in ['added' 'updated' 'removed'] updated changes changes get key {} if not updated changes continue location updated changes get 'location' '' contact updated changes get 'contact' '' community updated changes get 'community' {} chassis id updated changes get 'chassis id' '' if key 'removed' fun 'remove config' ret salt ['snmp {fun}' format fun fun ] location location contact contact community community chassis id chassis id commit False cfgred cfgred and ret get 'result' if not ret get 'result' and ret get 'comment' reasons append ret get 'comment' return {'result' cfgred 'comment' '\n' join reasons if reasons else '' }
null
null
null
null
Question: For what purpose does the code call the configuration template ? Code: def _configure(changes): cfgred = True reasons = [] fun = 'update_config' for key in ['added', 'updated', 'removed']: _updated_changes = changes.get(key, {}) if (not _updated_changes): continue _location = _updated_changes.get('location', '') _contact = _updated_changes.get('contact', '') _community = _updated_changes.get('community', {}) _chassis_id = _updated_changes.get('chassis_id', '') if (key == 'removed'): fun = 'remove_config' _ret = __salt__['snmp.{fun}'.format(fun=fun)](location=_location, contact=_contact, community=_community, chassis_id=_chassis_id, commit=False) cfgred = (cfgred and _ret.get('result')) if ((not _ret.get('result')) and _ret.get('comment')): reasons.append(_ret.get('comment')) return {'result': cfgred, 'comment': ('\n'.join(reasons) if reasons else '')}
null
null
null
What does the code call to apply the configuration changes on the device ?
def _configure(changes): cfgred = True reasons = [] fun = 'update_config' for key in ['added', 'updated', 'removed']: _updated_changes = changes.get(key, {}) if (not _updated_changes): continue _location = _updated_changes.get('location', '') _contact = _updated_changes.get('contact', '') _community = _updated_changes.get('community', {}) _chassis_id = _updated_changes.get('chassis_id', '') if (key == 'removed'): fun = 'remove_config' _ret = __salt__['snmp.{fun}'.format(fun=fun)](location=_location, contact=_contact, community=_community, chassis_id=_chassis_id, commit=False) cfgred = (cfgred and _ret.get('result')) if ((not _ret.get('result')) and _ret.get('comment')): reasons.append(_ret.get('comment')) return {'result': cfgred, 'comment': ('\n'.join(reasons) if reasons else '')}
null
null
null
the configuration template
codeqa
def configure changes cfgred Truereasons []fun 'update config'for key in ['added' 'updated' 'removed'] updated changes changes get key {} if not updated changes continue location updated changes get 'location' '' contact updated changes get 'contact' '' community updated changes get 'community' {} chassis id updated changes get 'chassis id' '' if key 'removed' fun 'remove config' ret salt ['snmp {fun}' format fun fun ] location location contact contact community community chassis id chassis id commit False cfgred cfgred and ret get 'result' if not ret get 'result' and ret get 'comment' reasons append ret get 'comment' return {'result' cfgred 'comment' '\n' join reasons if reasons else '' }
null
null
null
null
Question: What does the code call to apply the configuration changes on the device ? Code: def _configure(changes): cfgred = True reasons = [] fun = 'update_config' for key in ['added', 'updated', 'removed']: _updated_changes = changes.get(key, {}) if (not _updated_changes): continue _location = _updated_changes.get('location', '') _contact = _updated_changes.get('contact', '') _community = _updated_changes.get('community', {}) _chassis_id = _updated_changes.get('chassis_id', '') if (key == 'removed'): fun = 'remove_config' _ret = __salt__['snmp.{fun}'.format(fun=fun)](location=_location, contact=_contact, community=_community, chassis_id=_chassis_id, commit=False) cfgred = (cfgred and _ret.get('result')) if ((not _ret.get('result')) and _ret.get('comment')): reasons.append(_ret.get('comment')) return {'result': cfgred, 'comment': ('\n'.join(reasons) if reasons else '')}
null
null
null
For what purpose do random content nodes return ?
@parse_data @set_database def get_random_content(kinds=None, limit=1, available=None, **kwargs): if (not kinds): kinds = ['Video', 'Audio', 'Exercise', 'Document'] items = Item.select().where(Item.kind.in_(kinds)) if (available is not None): items = items.where((Item.available == available)) return items.order_by(fn.Random()).limit(limit)
null
null
null
for use in testing
codeqa
@parse data@set databasedef get random content kinds None limit 1 available None **kwargs if not kinds kinds [' Video' ' Audio' ' Exercise' ' Document']items Item select where Item kind in kinds if available is not None items items where Item available available return items order by fn Random limit limit
null
null
null
null
Question: For what purpose do random content nodes return ? Code: @parse_data @set_database def get_random_content(kinds=None, limit=1, available=None, **kwargs): if (not kinds): kinds = ['Video', 'Audio', 'Exercise', 'Document'] items = Item.select().where(Item.kind.in_(kinds)) if (available is not None): items = items.where((Item.available == available)) return items.order_by(fn.Random()).limit(limit)
null
null
null
For what purpose does gradient boosting load this function ?
def loadGradientBoostingModel(GBModelName, isRegression=False): try: fo = open((GBModelName + 'MEANS'), 'rb') except IOError: print "Load Random Forest Model: Didn't find file" return try: MEAN = cPickle.load(fo) STD = cPickle.load(fo) if (not isRegression): classNames = cPickle.load(fo) mtWin = cPickle.load(fo) mtStep = cPickle.load(fo) stWin = cPickle.load(fo) stStep = cPickle.load(fo) computeBEAT = cPickle.load(fo) except: fo.close() fo.close() MEAN = numpy.array(MEAN) STD = numpy.array(STD) COEFF = [] with open(GBModelName, 'rb') as fid: GB = cPickle.load(fid) if isRegression: return (GB, MEAN, STD, mtWin, mtStep, stWin, stStep, computeBEAT) else: return (GB, MEAN, STD, classNames, mtWin, mtStep, stWin, stStep, computeBEAT)
null
null
null
either for classification or training
codeqa
def load Gradient Boosting Model GB Model Name is Regression False try fo open GB Model Name + 'MEANS' 'rb' except IO Error print " Load Random Forest Model Didn'tfindfile"returntry MEAN c Pickle load fo STD c Pickle load fo if not is Regression class Names c Pickle load fo mt Win c Pickle load fo mt Step c Pickle load fo st Win c Pickle load fo st Step c Pickle load fo compute BEAT c Pickle load fo except fo close fo close MEAN numpy array MEAN STD numpy array STD COEFF []with open GB Model Name 'rb' as fid GB c Pickle load fid if is Regression return GB MEAN STD mt Win mt Step st Win st Step compute BEAT else return GB MEAN STD class Names mt Win mt Step st Win st Step compute BEAT
null
null
null
null
Question: For what purpose does gradient boosting load this function ? Code: def loadGradientBoostingModel(GBModelName, isRegression=False): try: fo = open((GBModelName + 'MEANS'), 'rb') except IOError: print "Load Random Forest Model: Didn't find file" return try: MEAN = cPickle.load(fo) STD = cPickle.load(fo) if (not isRegression): classNames = cPickle.load(fo) mtWin = cPickle.load(fo) mtStep = cPickle.load(fo) stWin = cPickle.load(fo) stStep = cPickle.load(fo) computeBEAT = cPickle.load(fo) except: fo.close() fo.close() MEAN = numpy.array(MEAN) STD = numpy.array(STD) COEFF = [] with open(GBModelName, 'rb') as fid: GB = cPickle.load(fid) if isRegression: return (GB, MEAN, STD, mtWin, mtStep, stWin, stStep, computeBEAT) else: return (GB, MEAN, STD, classNames, mtWin, mtStep, stWin, stStep, computeBEAT)
null
null
null
What does the code get ?
def getRepositoryWriter(title): repositoryWriter = cStringIO.StringIO() repositoryWriter.write(('Format is tab separated %s.\n' % title)) repositoryWriter.write(('_Name %sValue\n' % globalSpreadsheetSeparator)) return repositoryWriter
null
null
null
the repository writer for the title
codeqa
def get Repository Writer title repository Writer c String IO String IO repository Writer write ' Formatistabseparated%s \n' % title repository Writer write ' Name%s Value\n' % global Spreadsheet Separator return repository Writer
null
null
null
null
Question: What does the code get ? Code: def getRepositoryWriter(title): repositoryWriter = cStringIO.StringIO() repositoryWriter.write(('Format is tab separated %s.\n' % title)) repositoryWriter.write(('_Name %sValue\n' % globalSpreadsheetSeparator)) return repositoryWriter
null
null
null
What do all the filenames in the item / filename mapping match ?
def all_matches(names, pattern): matches = {} for (item, name) in names.items(): m = re.match(pattern, name, re.IGNORECASE) if (m and m.groupdict()): matches[item] = m.groupdict() else: return None return matches
null
null
null
the pattern
codeqa
def all matches names pattern matches {}for item name in names items m re match pattern name re IGNORECASE if m and m groupdict matches[item] m groupdict else return Nonereturn matches
null
null
null
null
Question: What do all the filenames in the item / filename mapping match ? Code: def all_matches(names, pattern): matches = {} for (item, name) in names.items(): m = re.match(pattern, name, re.IGNORECASE) if (m and m.groupdict()): matches[item] = m.groupdict() else: return None return matches
null
null
null
What match the pattern ?
def all_matches(names, pattern): matches = {} for (item, name) in names.items(): m = re.match(pattern, name, re.IGNORECASE) if (m and m.groupdict()): matches[item] = m.groupdict() else: return None return matches
null
null
null
all the filenames in the item / filename mapping
codeqa
def all matches names pattern matches {}for item name in names items m re match pattern name re IGNORECASE if m and m groupdict matches[item] m groupdict else return Nonereturn matches
null
null
null
null
Question: What match the pattern ? Code: def all_matches(names, pattern): matches = {} for (item, name) in names.items(): m = re.match(pattern, name, re.IGNORECASE) if (m and m.groupdict()): matches[item] = m.groupdict() else: return None return matches
null
null
null
By how much did type define ?
def is_consistent_type(theType, name, *constructionArgs): assert (theType.__name__ == name) assert isinstance(theType, type) instance = theType(*constructionArgs) assert (type(instance) is theType) return True
null
null
null
well
codeqa
def is consistent type the Type name *construction Args assert the Type name name assert isinstance the Type type instance the Type *construction Args assert type instance is the Type return True
null
null
null
null
Question: By how much did type define ? Code: def is_consistent_type(theType, name, *constructionArgs): assert (theType.__name__ == name) assert isinstance(theType, type) instance = theType(*constructionArgs) assert (type(instance) is theType) return True
null
null
null
What does the code get ?
def _getAccessibleAttribute(attributeName, elementNode): functionName = attributeName[len('get'):].lower() if (functionName not in evaluate.globalCreationDictionary): print 'Warning, functionName not in globalCreationDictionary in _getAccessibleAttribute in creation for:' print functionName print elementNode return None pluginModule = archive.getModuleWithPath(evaluate.globalCreationDictionary[functionName]) if (pluginModule == None): print 'Warning, _getAccessibleAttribute in creation can not get a pluginModule for:' print functionName print elementNode return None return Creation(elementNode, pluginModule).getCreation
null
null
null
the accessible attribute
codeqa
def get Accessible Attribute attribute Name element Node function Name attribute Name[len 'get' ] lower if function Name not in evaluate global Creation Dictionary print ' Warning function Namenotinglobal Creation Dictionaryin get Accessible Attributeincreationfor 'print function Nameprint element Nodereturn Noneplugin Module archive get Module With Path evaluate global Creation Dictionary[function Name] if plugin Module None print ' Warning get Accessible Attributeincreationcannotgetaplugin Modulefor 'print function Nameprint element Nodereturn Nonereturn Creation element Node plugin Module get Creation
null
null
null
null
Question: What does the code get ? Code: def _getAccessibleAttribute(attributeName, elementNode): functionName = attributeName[len('get'):].lower() if (functionName not in evaluate.globalCreationDictionary): print 'Warning, functionName not in globalCreationDictionary in _getAccessibleAttribute in creation for:' print functionName print elementNode return None pluginModule = archive.getModuleWithPath(evaluate.globalCreationDictionary[functionName]) if (pluginModule == None): print 'Warning, _getAccessibleAttribute in creation can not get a pluginModule for:' print functionName print elementNode return None return Creation(elementNode, pluginModule).getCreation
null
null
null
What do one big player sequence contain ?
def combine_max_stats(games): return reduce((lambda a, b: (a + b)), [g.max_player_stats() for g in games if (g is not None)])
null
null
null
maximum statistics based on game and play level statistics
codeqa
def combine max stats games return reduce lambda a b a + b [g max player stats for g in games if g is not None ]
null
null
null
null
Question: What do one big player sequence contain ? Code: def combine_max_stats(games): return reduce((lambda a, b: (a + b)), [g.max_player_stats() for g in games if (g is not None)])
null
null
null
What is containing maximum statistics based on game and play level statistics ?
def combine_max_stats(games): return reduce((lambda a, b: (a + b)), [g.max_player_stats() for g in games if (g is not None)])
null
null
null
one big player sequence
codeqa
def combine max stats games return reduce lambda a b a + b [g max player stats for g in games if g is not None ]
null
null
null
null
Question: What is containing maximum statistics based on game and play level statistics ? Code: def combine_max_stats(games): return reduce((lambda a, b: (a + b)), [g.max_player_stats() for g in games if (g is not None)])
null
null
null
What does the code provide ?
def with_metaclass(meta, *bases): return meta('NewBase', bases, {})
null
null
null
python cross - version metaclass compatibility
codeqa
def with metaclass meta *bases return meta ' New Base' bases {}
null
null
null
null
Question: What does the code provide ? Code: def with_metaclass(meta, *bases): return meta('NewBase', bases, {})
null
null
null
What did the code set ?
@verbose def setup_proj(info, add_eeg_ref=True, activate=True, verbose=None): if (add_eeg_ref and _needs_eeg_average_ref_proj(info)): eeg_proj = make_eeg_average_ref_proj(info, activate=activate) info['projs'].append(eeg_proj) (projector, nproj) = make_projector_info(info) if (nproj == 0): if verbose: logger.info('The projection vectors do not apply to these channels') projector = None else: logger.info(('Created an SSP operator (subspace dimension = %d)' % nproj)) if activate: info['projs'] = activate_proj(info['projs'], copy=False) return (projector, info)
null
null
null
projection for raw and epochs
codeqa
@verbosedef setup proj info add eeg ref True activate True verbose None if add eeg ref and needs eeg average ref proj info eeg proj make eeg average ref proj info activate activate info['projs'] append eeg proj projector nproj make projector info info if nproj 0 if verbose logger info ' Theprojectionvectorsdonotapplytothesechannels' projector Noneelse logger info ' Createdan SS Poperator subspacedimension %d ' % nproj if activate info['projs'] activate proj info['projs'] copy False return projector info
null
null
null
null
Question: What did the code set ? Code: @verbose def setup_proj(info, add_eeg_ref=True, activate=True, verbose=None): if (add_eeg_ref and _needs_eeg_average_ref_proj(info)): eeg_proj = make_eeg_average_ref_proj(info, activate=activate) info['projs'].append(eeg_proj) (projector, nproj) = make_projector_info(info) if (nproj == 0): if verbose: logger.info('The projection vectors do not apply to these channels') projector = None else: logger.info(('Created an SSP operator (subspace dimension = %d)' % nproj)) if activate: info['projs'] = activate_proj(info['projs'], copy=False) return (projector, info)
null
null
null
How do name_or_value call on the prefix passed in ?
def sanitize_prefix(function): @functools.wraps(function) def wrapper(*args, **kwargs): args = list(args) offset = 1 if ('prefix' in kwargs): kwargs['prefix'] = name_or_value(kwargs['prefix']) elif ((len(args) - 1) >= offset): args[offset] = name_or_value(args[offset]) offset += 1 if ('key' in kwargs): kwargs['key'] = name_or_value(kwargs['key']) elif ((len(args) - 1) >= offset): args[offset] = name_or_value(args[offset]) return function(*tuple(args), **kwargs) return wrapper
null
null
null
automatically
codeqa
def sanitize prefix function @functools wraps function def wrapper *args **kwargs args list args offset 1if 'prefix' in kwargs kwargs['prefix'] name or value kwargs['prefix'] elif len args - 1 > offset args[offset] name or value args[offset] offset + 1if 'key' in kwargs kwargs['key'] name or value kwargs['key'] elif len args - 1 > offset args[offset] name or value args[offset] return function *tuple args **kwargs return wrapper
null
null
null
null
Question: How do name_or_value call on the prefix passed in ? Code: def sanitize_prefix(function): @functools.wraps(function) def wrapper(*args, **kwargs): args = list(args) offset = 1 if ('prefix' in kwargs): kwargs['prefix'] = name_or_value(kwargs['prefix']) elif ((len(args) - 1) >= offset): args[offset] = name_or_value(args[offset]) offset += 1 if ('key' in kwargs): kwargs['key'] = name_or_value(kwargs['key']) elif ((len(args) - 1) >= offset): args[offset] = name_or_value(args[offset]) return function(*tuple(args), **kwargs) return wrapper
null
null
null
In which direction do the prefix pass ?
def sanitize_prefix(function): @functools.wraps(function) def wrapper(*args, **kwargs): args = list(args) offset = 1 if ('prefix' in kwargs): kwargs['prefix'] = name_or_value(kwargs['prefix']) elif ((len(args) - 1) >= offset): args[offset] = name_or_value(args[offset]) offset += 1 if ('key' in kwargs): kwargs['key'] = name_or_value(kwargs['key']) elif ((len(args) - 1) >= offset): args[offset] = name_or_value(args[offset]) return function(*tuple(args), **kwargs) return wrapper
null
null
null
in
codeqa
def sanitize prefix function @functools wraps function def wrapper *args **kwargs args list args offset 1if 'prefix' in kwargs kwargs['prefix'] name or value kwargs['prefix'] elif len args - 1 > offset args[offset] name or value args[offset] offset + 1if 'key' in kwargs kwargs['key'] name or value kwargs['key'] elif len args - 1 > offset args[offset] name or value args[offset] return function *tuple args **kwargs return wrapper
null
null
null
null
Question: In which direction do the prefix pass ? Code: def sanitize_prefix(function): @functools.wraps(function) def wrapper(*args, **kwargs): args = list(args) offset = 1 if ('prefix' in kwargs): kwargs['prefix'] = name_or_value(kwargs['prefix']) elif ((len(args) - 1) >= offset): args[offset] = name_or_value(args[offset]) offset += 1 if ('key' in kwargs): kwargs['key'] = name_or_value(kwargs['key']) elif ((len(args) - 1) >= offset): args[offset] = name_or_value(args[offset]) return function(*tuple(args), **kwargs) return wrapper
null
null
null
How did all the drives used by the test restore to a standard ext2 format ?
def finish_fsdev(force_cleanup=False): if ((FSDEV_PREP_CNT == 1) or force_cleanup): restore_disks(job=FSDEV_JOB, restore=FSDEV_RESTORE, disk_list=FSDEV_DISKLIST)
null
null
null
optionally
codeqa
def finish fsdev force cleanup False if FSDEV PREP CNT 1 or force cleanup restore disks job FSDEV JOB restore FSDEV RESTORE disk list FSDEV DISKLIST
null
null
null
null
Question: How did all the drives used by the test restore to a standard ext2 format ? Code: def finish_fsdev(force_cleanup=False): if ((FSDEV_PREP_CNT == 1) or force_cleanup): restore_disks(job=FSDEV_JOB, restore=FSDEV_RESTORE, disk_list=FSDEV_DISKLIST)
null
null
null
How did values store ?
def _clear_context(): keep_context = ('docker.client', 'docker.exec_driver', 'dockerng._pull_status', 'docker.docker_version', 'docker.docker_py_version') for key in list(__context__): try: if (key.startswith('docker.') and (key not in keep_context)): __context__.pop(key) except AttributeError: pass
null
null
null
in context
codeqa
def clear context keep context 'docker client' 'docker exec driver' 'dockerng pull status' 'docker docker version' 'docker docker py version' for key in list context try if key startswith 'docker ' and key not in keep context context pop key except Attribute Error pass
null
null
null
null
Question: How did values store ? Code: def _clear_context(): keep_context = ('docker.client', 'docker.exec_driver', 'dockerng._pull_status', 'docker.docker_version', 'docker.docker_py_version') for key in list(__context__): try: if (key.startswith('docker.') and (key not in keep_context)): __context__.pop(key) except AttributeError: pass
null
null
null
What marks a function to be run before categorization has happened ?
def before_categorize(f): f.before = True return f
null
null
null
a decorator
codeqa
def before categorize f f before Truereturn f
null
null
null
null
Question: What marks a function to be run before categorization has happened ? Code: def before_categorize(f): f.before = True return f
null
null
null
What does the code get ?
def survey_get_series_questions_of_type(question_list, qtype): if isinstance(qtype, (list, tuple)): types = qtype else: types = qtype questions = [] for question in question_list: if (question['type'] in types): questions.append(question) elif ((question['type'] == 'Link') or (question['type'] == 'GridChild')): widget_obj = survey_getWidgetFromQuestion(question['qstn_id']) if (widget_obj.getParentType() in types): question['name'] = widget_obj.fullName() questions.append(question) return questions
null
null
null
questions of a particular question type
codeqa
def survey get series questions of type question list qtype if isinstance qtype list tuple types qtypeelse types qtypequestions []for question in question list if question['type'] in types questions append question elif question['type'] ' Link' or question['type'] ' Grid Child' widget obj survey get Widget From Question question['qstn id'] if widget obj get Parent Type in types question['name'] widget obj full Name questions append question return questions
null
null
null
null
Question: What does the code get ? Code: def survey_get_series_questions_of_type(question_list, qtype): if isinstance(qtype, (list, tuple)): types = qtype else: types = qtype questions = [] for question in question_list: if (question['type'] in types): questions.append(question) elif ((question['type'] == 'Link') or (question['type'] == 'GridChild')): widget_obj = survey_getWidgetFromQuestion(question['qstn_id']) if (widget_obj.getParentType() in types): question['name'] = widget_obj.fullName() questions.append(question) return questions
null
null
null
How is the feature structure obtained ?
def retract_bindings(fstruct, bindings, fs_class=u'default'): if (fs_class == u'default'): fs_class = _default_fs_class(fstruct) (fstruct, new_bindings) = copy.deepcopy((fstruct, bindings)) bindings.update(new_bindings) inv_bindings = dict(((id(val), var) for (var, val) in bindings.items())) _retract_bindings(fstruct, inv_bindings, fs_class, set()) return fstruct
null
null
null
by replacing each feature structure value that is bound by bindings with the variable that binds it
codeqa
def retract bindings fstruct bindings fs class u'default' if fs class u'default' fs class default fs class fstruct fstruct new bindings copy deepcopy fstruct bindings bindings update new bindings inv bindings dict id val var for var val in bindings items retract bindings fstruct inv bindings fs class set return fstruct
null
null
null
null
Question: How is the feature structure obtained ? Code: def retract_bindings(fstruct, bindings, fs_class=u'default'): if (fs_class == u'default'): fs_class = _default_fs_class(fstruct) (fstruct, new_bindings) = copy.deepcopy((fstruct, bindings)) bindings.update(new_bindings) inv_bindings = dict(((id(val), var) for (var, val) in bindings.items())) _retract_bindings(fstruct, inv_bindings, fs_class, set()) return fstruct
null
null
null
What binds it ?
def retract_bindings(fstruct, bindings, fs_class=u'default'): if (fs_class == u'default'): fs_class = _default_fs_class(fstruct) (fstruct, new_bindings) = copy.deepcopy((fstruct, bindings)) bindings.update(new_bindings) inv_bindings = dict(((id(val), var) for (var, val) in bindings.items())) _retract_bindings(fstruct, inv_bindings, fs_class, set()) return fstruct
null
null
null
the variable
codeqa
def retract bindings fstruct bindings fs class u'default' if fs class u'default' fs class default fs class fstruct fstruct new bindings copy deepcopy fstruct bindings bindings update new bindings inv bindings dict id val var for var val in bindings items retract bindings fstruct inv bindings fs class set return fstruct
null
null
null
null
Question: What binds it ? Code: def retract_bindings(fstruct, bindings, fs_class=u'default'): if (fs_class == u'default'): fs_class = _default_fs_class(fstruct) (fstruct, new_bindings) = copy.deepcopy((fstruct, bindings)) bindings.update(new_bindings) inv_bindings = dict(((id(val), var) for (var, val) in bindings.items())) _retract_bindings(fstruct, inv_bindings, fs_class, set()) return fstruct
null
null
null
How does the code replace the attribute ?
def setboolean(obj, attr, _bool=None): if (_bool is None): _bool = dict(_boolean_states) res = _bool[getattr(obj, attr).lower()] setattr(obj, attr, res) return res
null
null
null
with a boolean
codeqa
def setboolean obj attr bool None if bool is None bool dict boolean states res bool[getattr obj attr lower ]setattr obj attr res return res
null
null
null
null
Question: How does the code replace the attribute ? Code: def setboolean(obj, attr, _bool=None): if (_bool is None): _bool = dict(_boolean_states) res = _bool[getattr(obj, attr).lower()] setattr(obj, attr, res) return res
null
null
null
What does the code replace with a boolean ?
def setboolean(obj, attr, _bool=None): if (_bool is None): _bool = dict(_boolean_states) res = _bool[getattr(obj, attr).lower()] setattr(obj, attr, res) return res
null
null
null
the attribute
codeqa
def setboolean obj attr bool None if bool is None bool dict boolean states res bool[getattr obj attr lower ]setattr obj attr res return res
null
null
null
null
Question: What does the code replace with a boolean ? Code: def setboolean(obj, attr, _bool=None): if (_bool is None): _bool = dict(_boolean_states) res = _bool[getattr(obj, attr).lower()] setattr(obj, attr, res) return res
null
null
null
What does the code make ?
def _set_persistent_module(mod): conf = _get_modules_conf() if (not os.path.exists(conf)): __salt__['file.touch'](conf) mod_name = _strip_module_name(mod) if ((not mod_name) or (mod_name in mod_list(True)) or (mod_name not in available())): return set() escape_mod = re.escape(mod) if __salt__['file.search'](conf, '^#[ DCTB ]*{0}[ DCTB ]*$'.format(escape_mod), multiline=True): __salt__['file.uncomment'](conf, escape_mod) else: __salt__['file.append'](conf, mod) return set([mod_name])
null
null
null
it persistent
codeqa
def set persistent module mod conf get modules conf if not os path exists conf salt ['file touch'] conf mod name strip module name mod if not mod name or mod name in mod list True or mod name not in available return set escape mod re escape mod if salt ['file search'] conf '^#[ DCTB ]*{ 0 }[ DCTB ]*$' format escape mod multiline True salt ['file uncomment'] conf escape mod else salt ['file append'] conf mod return set [mod name]
null
null
null
null
Question: What does the code make ? Code: def _set_persistent_module(mod): conf = _get_modules_conf() if (not os.path.exists(conf)): __salt__['file.touch'](conf) mod_name = _strip_module_name(mod) if ((not mod_name) or (mod_name in mod_list(True)) or (mod_name not in available())): return set() escape_mod = re.escape(mod) if __salt__['file.search'](conf, '^#[ DCTB ]*{0}[ DCTB ]*$'.format(escape_mod), multiline=True): __salt__['file.uncomment'](conf, escape_mod) else: __salt__['file.append'](conf, mod) return set([mod_name])
null
null
null
What does the code get ?
def libvlc_media_player_event_manager(p_mi): f = (_Cfunctions.get('libvlc_media_player_event_manager', None) or _Cfunction('libvlc_media_player_event_manager', ((1,),), class_result(EventManager), ctypes.c_void_p, MediaPlayer)) return f(p_mi)
null
null
null
the event manager from which the media player send event
codeqa
def libvlc media player event manager p mi f Cfunctions get 'libvlc media player event manager' None or Cfunction 'libvlc media player event manager' 1 class result Event Manager ctypes c void p Media Player return f p mi
null
null
null
null
Question: What does the code get ? Code: def libvlc_media_player_event_manager(p_mi): f = (_Cfunctions.get('libvlc_media_player_event_manager', None) or _Cfunction('libvlc_media_player_event_manager', ((1,),), class_result(EventManager), ctypes.c_void_p, MediaPlayer)) return f(p_mi)
null
null
null
What do the media player send the event manager ?
def libvlc_media_player_event_manager(p_mi): f = (_Cfunctions.get('libvlc_media_player_event_manager', None) or _Cfunction('libvlc_media_player_event_manager', ((1,),), class_result(EventManager), ctypes.c_void_p, MediaPlayer)) return f(p_mi)
null
null
null
event
codeqa
def libvlc media player event manager p mi f Cfunctions get 'libvlc media player event manager' None or Cfunction 'libvlc media player event manager' 1 class result Event Manager ctypes c void p Media Player return f p mi
null
null
null
null
Question: What do the media player send the event manager ? Code: def libvlc_media_player_event_manager(p_mi): f = (_Cfunctions.get('libvlc_media_player_event_manager', None) or _Cfunction('libvlc_media_player_event_manager', ((1,),), class_result(EventManager), ctypes.c_void_p, MediaPlayer)) return f(p_mi)
null
null
null
What does the code remove ?
def remove_volumes(paths): errors = [] for path in paths: clear_volume(path) lvremove = ('lvremove', '-f', path) try: utils.execute(attempts=3, run_as_root=True, *lvremove) except processutils.ProcessExecutionError as exp: errors.append(six.text_type(exp)) if errors: raise exception.VolumesNotRemoved(reason=', '.join(errors))
null
null
null
one or more logical volume
codeqa
def remove volumes paths errors []for path in paths clear volume path lvremove 'lvremove' '-f' path try utils execute attempts 3 run as root True *lvremove except processutils Process Execution Error as exp errors append six text type exp if errors raise exception Volumes Not Removed reason ' ' join errors
null
null
null
null
Question: What does the code remove ? Code: def remove_volumes(paths): errors = [] for path in paths: clear_volume(path) lvremove = ('lvremove', '-f', path) try: utils.execute(attempts=3, run_as_root=True, *lvremove) except processutils.ProcessExecutionError as exp: errors.append(six.text_type(exp)) if errors: raise exception.VolumesNotRemoved(reason=', '.join(errors))
null
null
null
Ca a range generate ranges with a length of more than max_range items ?
def safe_range(*args): rng = range(*args) if (len(rng) > MAX_RANGE): raise OverflowError(('range too big, maximum size for range is %d' % MAX_RANGE)) return rng
null
null
null
No
codeqa
def safe range *args rng range *args if len rng > MAX RANGE raise Overflow Error 'rangetoobig maximumsizeforrangeis%d' % MAX RANGE return rng
null
null
null
null
Question: Ca a range generate ranges with a length of more than max_range items ? Code: def safe_range(*args): rng = range(*args) if (len(rng) > MAX_RANGE): raise OverflowError(('range too big, maximum size for range is %d' % MAX_RANGE)) return rng
null
null
null
How do primer test ?
def local_align_primer_seq(primer, sequence, sw_scorer=equality_scorer_ambigs): query_primer = primer query_sequence = str(sequence) alignment = pair_hmm_align_unaligned_seqs([query_primer, query_sequence]) primer_hit = str(alignment.Seqs[0]) target_hit = str(alignment.Seqs[1]) insertions = primer_hit.count('-') deletions = target_hit.count('-') mismatches = 0 for i in range(len(target_hit)): if ((sw_scorer(target_hit[i], primer_hit[i]) == (-1)) and (target_hit[i] != '-') and (primer_hit[i] != '-')): mismatches += 1 try: hit_start = query_sequence.index(target_hit.replace('-', '')) except ValueError: raise ValueError(('substring not found, query string %s, target_hit %s' % (query_sequence, target_hit))) mismatch_count = ((insertions + deletions) + mismatches) return (mismatch_count, hit_start)
null
null
null
against
codeqa
def local align primer seq primer sequence sw scorer equality scorer ambigs query primer primerquery sequence str sequence alignment pair hmm align unaligned seqs [query primer query sequence] primer hit str alignment Seqs[ 0 ] target hit str alignment Seqs[ 1 ] insertions primer hit count '-' deletions target hit count '-' mismatches 0for i in range len target hit if sw scorer target hit[i] primer hit[i] -1 and target hit[i] '-' and primer hit[i] '-' mismatches + 1try hit start query sequence index target hit replace '-' '' except Value Error raise Value Error 'substringnotfound querystring%s target hit%s' % query sequence target hit mismatch count insertions + deletions + mismatches return mismatch count hit start
null
null
null
null
Question: How do primer test ? Code: def local_align_primer_seq(primer, sequence, sw_scorer=equality_scorer_ambigs): query_primer = primer query_sequence = str(sequence) alignment = pair_hmm_align_unaligned_seqs([query_primer, query_sequence]) primer_hit = str(alignment.Seqs[0]) target_hit = str(alignment.Seqs[1]) insertions = primer_hit.count('-') deletions = target_hit.count('-') mismatches = 0 for i in range(len(target_hit)): if ((sw_scorer(target_hit[i], primer_hit[i]) == (-1)) and (target_hit[i] != '-') and (primer_hit[i] != '-')): mismatches += 1 try: hit_start = query_sequence.index(target_hit.replace('-', '')) except ValueError: raise ValueError(('substring not found, query string %s, target_hit %s' % (query_sequence, target_hit))) mismatch_count = ((insertions + deletions) + mismatches) return (mismatch_count, hit_start)
null
null
null
What does the code run ?
def runWithWarningsSuppressed(suppressedWarnings, f, *a, **kw): for (args, kwargs) in suppressedWarnings: warnings.filterwarnings(*args, **kwargs) addedFilters = warnings.filters[:len(suppressedWarnings)] try: result = f(*a, **kw) except: exc_info = sys.exc_info() _resetWarningFilters(None, addedFilters) raise exc_info[0], exc_info[1], exc_info[2] else: if isinstance(result, defer.Deferred): result.addBoth(_resetWarningFilters, addedFilters) else: _resetWarningFilters(None, addedFilters) return result
null
null
null
the function c{f
codeqa
def run With Warnings Suppressed suppressed Warnings f *a **kw for args kwargs in suppressed Warnings warnings filterwarnings *args **kwargs added Filters warnings filters[ len suppressed Warnings ]try result f *a **kw except exc info sys exc info reset Warning Filters None added Filters raise exc info[ 0 ] exc info[ 1 ] exc info[ 2 ]else if isinstance result defer Deferred result add Both reset Warning Filters added Filters else reset Warning Filters None added Filters return result
null
null
null
null
Question: What does the code run ? Code: def runWithWarningsSuppressed(suppressedWarnings, f, *a, **kw): for (args, kwargs) in suppressedWarnings: warnings.filterwarnings(*args, **kwargs) addedFilters = warnings.filters[:len(suppressedWarnings)] try: result = f(*a, **kw) except: exc_info = sys.exc_info() _resetWarningFilters(None, addedFilters) raise exc_info[0], exc_info[1], exc_info[2] else: if isinstance(result, defer.Deferred): result.addBoth(_resetWarningFilters, addedFilters) else: _resetWarningFilters(None, addedFilters) return result
null
null
null
Where does a named character parse ?
def parse_repl_named_char(source): saved_pos = source.pos if source.match('{'): name = source.get_while((ALPHA | set(' '))) if source.match('}'): try: value = unicodedata.lookup(name) return ord(value) except KeyError: raise error('undefined character name', source.string, source.pos) source.pos = saved_pos return None
null
null
null
in a replacement string
codeqa
def parse repl named char source saved pos source posif source match '{' name source get while ALPHA set '' if source match '}' try value unicodedata lookup name return ord value except Key Error raise error 'undefinedcharactername' source string source pos source pos saved posreturn None
null
null
null
null
Question: Where does a named character parse ? Code: def parse_repl_named_char(source): saved_pos = source.pos if source.match('{'): name = source.get_while((ALPHA | set(' '))) if source.match('}'): try: value = unicodedata.lookup(name) return ord(value) except KeyError: raise error('undefined character name', source.string, source.pos) source.pos = saved_pos return None
null
null
null
What parses in a replacement string ?
def parse_repl_named_char(source): saved_pos = source.pos if source.match('{'): name = source.get_while((ALPHA | set(' '))) if source.match('}'): try: value = unicodedata.lookup(name) return ord(value) except KeyError: raise error('undefined character name', source.string, source.pos) source.pos = saved_pos return None
null
null
null
a named character
codeqa
def parse repl named char source saved pos source posif source match '{' name source get while ALPHA set '' if source match '}' try value unicodedata lookup name return ord value except Key Error raise error 'undefinedcharactername' source string source pos source pos saved posreturn None
null
null
null
null
Question: What parses in a replacement string ? Code: def parse_repl_named_char(source): saved_pos = source.pos if source.match('{'): name = source.get_while((ALPHA | set(' '))) if source.match('}'): try: value = unicodedata.lookup(name) return ord(value) except KeyError: raise error('undefined character name', source.string, source.pos) source.pos = saved_pos return None
null
null
null
What does the code send ?
def post(url, data=None, json=None, **kwargs): return request('post', url, data=data, json=json, **kwargs)
null
null
null
a post request
codeqa
def post url data None json None **kwargs return request 'post' url data data json json **kwargs
null
null
null
null
Question: What does the code send ? Code: def post(url, data=None, json=None, **kwargs): return request('post', url, data=data, json=json, **kwargs)
null
null
null
What does the code raise ?
def _get_pass_exec(): pass_exec = salt.utils.which('pass') if pass_exec: return pass_exec else: raise SaltRenderError('pass unavailable')
null
null
null
an error
codeqa
def get pass exec pass exec salt utils which 'pass' if pass exec return pass execelse raise Salt Render Error 'passunavailable'
null
null
null
null
Question: What does the code raise ? Code: def _get_pass_exec(): pass_exec = salt.utils.which('pass') if pass_exec: return pass_exec else: raise SaltRenderError('pass unavailable')
null
null
null
What does the code build ?
@nottest def parse_tests(tool, tests_source): default_interactor = os.environ.get('GALAXY_TEST_DEFAULT_INTERACTOR', DEFAULT_INTERACTOR) tests_dict = tests_source.parse_tests_to_dict() tests_default_interactor = tests_dict.get('interactor', default_interactor) tests = [] for (i, test_dict) in enumerate(tests_dict.get('tests', [])): test = ToolTestBuilder(tool, test_dict, i, default_interactor=tests_default_interactor) tests.append(test) return tests
null
null
null
tooltestbuilder objects
codeqa
@nottestdef parse tests tool tests source default interactor os environ get 'GALAXY TEST DEFAULT INTERACTOR' DEFAULT INTERACTOR tests dict tests source parse tests to dict tests default interactor tests dict get 'interactor' default interactor tests []for i test dict in enumerate tests dict get 'tests' [] test Tool Test Builder tool test dict i default interactor tests default interactor tests append test return tests
null
null
null
null
Question: What does the code build ? Code: @nottest def parse_tests(tool, tests_source): default_interactor = os.environ.get('GALAXY_TEST_DEFAULT_INTERACTOR', DEFAULT_INTERACTOR) tests_dict = tests_source.parse_tests_to_dict() tests_default_interactor = tests_dict.get('interactor', default_interactor) tests = [] for (i, test_dict) in enumerate(tests_dict.get('tests', [])): test = ToolTestBuilder(tool, test_dict, i, default_interactor=tests_default_interactor) tests.append(test) return tests
null
null
null
When does the code get seconds ?
def generate_timestamp(): return unicode(int(time.time()))
null
null
null
since epoch
codeqa
def generate timestamp return unicode int time time
null
null
null
null
Question: When does the code get seconds ? Code: def generate_timestamp(): return unicode(int(time.time()))
null
null
null
What does the code get since epoch ?
def generate_timestamp(): return unicode(int(time.time()))
null
null
null
seconds
codeqa
def generate timestamp return unicode int time time
null
null
null
null
Question: What does the code get since epoch ? Code: def generate_timestamp(): return unicode(int(time.time()))
null
null
null
What does the code run ?
def crop_hint(photo_file): service = get_service() with open(photo_file, 'rb') as image: image_content = base64.b64encode(image.read()) service_request = service.images().annotate(body={'requests': [{'image': {'content': image_content.decode('UTF-8')}, 'features': [{'type': 'CROP_HINTS'}]}]}) response = service_request.execute() print json.dumps(response, indent=2)
null
null
null
a crop hint request on the image
codeqa
def crop hint photo file service get service with open photo file 'rb' as image image content base 64 b64 encode image read service request service images annotate body {'requests' [{'image' {'content' image content decode 'UTF- 8 ' } 'features' [{'type' 'CROP HINTS'}]}]} response service request execute print json dumps response indent 2
null
null
null
null
Question: What does the code run ? Code: def crop_hint(photo_file): service = get_service() with open(photo_file, 'rb') as image: image_content = base64.b64encode(image.read()) service_request = service.images().annotate(body={'requests': [{'image': {'content': image_content.decode('UTF-8')}, 'features': [{'type': 'CROP_HINTS'}]}]}) response = service_request.execute() print json.dumps(response, indent=2)
null
null
null
How do a figure create ?
@requires_application() def test_figure_creation(): with vp.Fig(show=False) as fig: fig[0, 0:2] fig[1:3, 0:2] ax_right = fig[1:3, 2] assert (fig[1:3, 2] is ax_right) assert_raises(ValueError, fig.__getitem__, (slice(1, 3), 1))
null
null
null
test
codeqa
@requires application def test figure creation with vp Fig show False as fig fig[ 0 0 2]fig[ 1 3 0 2]ax right fig[ 1 3 2]assert fig[ 1 3 2] is ax right assert raises Value Error fig getitem slice 1 3 1
null
null
null
null
Question: How do a figure create ? Code: @requires_application() def test_figure_creation(): with vp.Fig(show=False) as fig: fig[0, 0:2] fig[1:3, 0:2] ax_right = fig[1:3, 2] assert (fig[1:3, 2] is ax_right) assert_raises(ValueError, fig.__getitem__, (slice(1, 3), 1))
null
null
null
What does the code check ?
def check_cs_get(result, func, cargs): check_cs_op(result, func, cargs) return last_arg_byref(cargs)
null
null
null
the coordinate sequence retrieval
codeqa
def check cs get result func cargs check cs op result func cargs return last arg byref cargs
null
null
null
null
Question: What does the code check ? Code: def check_cs_get(result, func, cargs): check_cs_op(result, func, cargs) return last_arg_byref(cargs)
null
null
null
What does the code ensure ?
def makedirs(path, owner=None, grant_perms=None, deny_perms=None, inheritance=True): path = os.path.expanduser(path) dirname = os.path.normpath(os.path.dirname(path)) if os.path.isdir(dirname): msg = "Directory '{0}' already exists".format(dirname) log.debug(msg) return msg if os.path.exists(dirname): msg = "The path '{0}' already exists and is not a directory".format(dirname) log.debug(msg) return msg directories_to_create = [] while True: if os.path.isdir(dirname): break directories_to_create.append(dirname) current_dirname = dirname dirname = os.path.dirname(dirname) if (current_dirname == dirname): raise SaltInvocationError("Recursive creation for path '{0}' would result in an infinite loop. Please use an absolute path.".format(dirname)) directories_to_create.reverse() for directory_to_create in directories_to_create: log.debug('Creating directory: %s', directory_to_create) mkdir(path, owner, grant_perms, deny_perms, inheritance)
null
null
null
that the parent directory containing this path is available
codeqa
def makedirs path owner None grant perms None deny perms None inheritance True path os path expanduser path dirname os path normpath os path dirname path if os path isdir dirname msg " Directory'{ 0 }'alreadyexists" format dirname log debug msg return msgif os path exists dirname msg " Thepath'{ 0 }'alreadyexistsandisnotadirectory" format dirname log debug msg return msgdirectories to create []while True if os path isdir dirname breakdirectories to create append dirname current dirname dirnamedirname os path dirname dirname if current dirname dirname raise Salt Invocation Error " Recursivecreationforpath'{ 0 }'wouldresultinaninfiniteloop Pleaseuseanabsolutepath " format dirname directories to create reverse for directory to create in directories to create log debug ' Creatingdirectory %s' directory to create mkdir path owner grant perms deny perms inheritance
null
null
null
null
Question: What does the code ensure ? Code: def makedirs(path, owner=None, grant_perms=None, deny_perms=None, inheritance=True): path = os.path.expanduser(path) dirname = os.path.normpath(os.path.dirname(path)) if os.path.isdir(dirname): msg = "Directory '{0}' already exists".format(dirname) log.debug(msg) return msg if os.path.exists(dirname): msg = "The path '{0}' already exists and is not a directory".format(dirname) log.debug(msg) return msg directories_to_create = [] while True: if os.path.isdir(dirname): break directories_to_create.append(dirname) current_dirname = dirname dirname = os.path.dirname(dirname) if (current_dirname == dirname): raise SaltInvocationError("Recursive creation for path '{0}' would result in an infinite loop. Please use an absolute path.".format(dirname)) directories_to_create.reverse() for directory_to_create in directories_to_create: log.debug('Creating directory: %s', directory_to_create) mkdir(path, owner, grant_perms, deny_perms, inheritance)