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
How does valid positions in string s extract ?
def get_masked_string(s, p): return fromstring(s, dtype=uint8)[p].tostring()
null
null
null
using index array p
codeqa
def get masked string s p return fromstring s dtype uint 8 [p] tostring
null
null
null
null
Question: How does valid positions in string s extract ? Code: def get_masked_string(s, p): return fromstring(s, dtype=uint8)[p].tostring()
null
null
null
What does the code insert into a path ?
def getWithLeastLength(path, point): if (len(path) < 1): return 0 shortestPointIndex = None shortestAdditionalLength = 9.999999999876543e+17 for pointIndex in xrange((len(path) + 1)): additionalLength = getAdditionalLength(path, point, pointIndex) if (additionalLength < shortestAdditionalLength): shortestAdditionalLength = additionalLength shortestPointIndex = pointIndex return shortestPointIndex
null
null
null
a point
codeqa
def get With Least Length path point if len path < 1 return 0shortest Point Index Noneshortest Additional Length 9 999999999876543 e+ 17 for point Index in xrange len path + 1 additional Length get Additional Length path point point Index if additional Length < shortest Additional Length shortest Additional Length additional Lengthshortest Point Index point Indexreturn shortest Point Index
null
null
null
null
Question: What does the code insert into a path ? Code: def getWithLeastLength(path, point): if (len(path) < 1): return 0 shortestPointIndex = None shortestAdditionalLength = 9.999999999876543e+17 for pointIndex in xrange((len(path) + 1)): additionalLength = getAdditionalLength(path, point, pointIndex) if (additionalLength < shortestAdditionalLength): shortestAdditionalLength = additionalLength shortestPointIndex = pointIndex return shortestPointIndex
null
null
null
What does the code delete if it currently exists at path f ?
def unlink(f): try: os.unlink(f) except OSError as e: if (e.errno != errno.ENOENT): raise
null
null
null
a file
codeqa
def unlink f try os unlink f except OS Error as e if e errno errno ENOENT raise
null
null
null
null
Question: What does the code delete if it currently exists at path f ? Code: def unlink(f): try: os.unlink(f) except OSError as e: if (e.errno != errno.ENOENT): raise
null
null
null
How does the code delete a file if it currently exists ?
def unlink(f): try: os.unlink(f) except OSError as e: if (e.errno != errno.ENOENT): raise
null
null
null
at path f
codeqa
def unlink f try os unlink f except OS Error as e if e errno errno ENOENT raise
null
null
null
null
Question: How does the code delete a file if it currently exists ? Code: def unlink(f): try: os.unlink(f) except OSError as e: if (e.errno != errno.ENOENT): raise
null
null
null
How did step represent ?
def test_defined_step_represent_string(): feature_file = ojoin('runner_features', 'first.feature') feature_dir = ojoin('runner_features') loader = FeatureLoader(feature_dir) world._output = StringIO() world._is_colored = False loader.find_and_load_step_definitions() feature = Feature.from_file(feature_file) step = feature.scenarios[0].steps[0] step.run(True) assert_equals(step.represent_string(step.sentence), ' Given I do nothing # tests/functional/output_features/runner_features/dumb_steps.py:6\n')
null
null
null
without colors
codeqa
def test defined step represent string feature file ojoin 'runner features' 'first feature' feature dir ojoin 'runner features' loader Feature Loader feature dir world output String IO world is colored Falseloader find and load step definitions feature Feature from file feature file step feature scenarios[ 0 ] steps[ 0 ]step run True assert equals step represent string step sentence ' Given Idonothing#tests/functional/output features/runner features/dumb steps py 6\n'
null
null
null
null
Question: How did step represent ? Code: def test_defined_step_represent_string(): feature_file = ojoin('runner_features', 'first.feature') feature_dir = ojoin('runner_features') loader = FeatureLoader(feature_dir) world._output = StringIO() world._is_colored = False loader.find_and_load_step_definitions() feature = Feature.from_file(feature_file) step = feature.scenarios[0].steps[0] step.run(True) assert_equals(step.represent_string(step.sentence), ' Given I do nothing # tests/functional/output_features/runner_features/dumb_steps.py:6\n')
null
null
null
What does the code get from item or default ?
def get_valuation_method(item_code): val_method = frappe.db.get_value(u'Item', item_code, u'valuation_method') if (not val_method): val_method = (frappe.db.get_value(u'Stock Settings', None, u'valuation_method') or u'FIFO') return val_method
null
null
null
valuation method
codeqa
def get valuation method item code val method frappe db get value u' Item' item code u'valuation method' if not val method val method frappe db get value u' Stock Settings' None u'valuation method' or u'FIFO' return val method
null
null
null
null
Question: What does the code get from item or default ? Code: def get_valuation_method(item_code): val_method = frappe.db.get_value(u'Item', item_code, u'valuation_method') if (not val_method): val_method = (frappe.db.get_value(u'Stock Settings', None, u'valuation_method') or u'FIFO') return val_method
null
null
null
Where does the code get all the backups ?
def backup_get_all_active_by_window(context, begin, end=None, project_id=None): return IMPL.backup_get_all_active_by_window(context, begin, end, project_id)
null
null
null
inside the window
codeqa
def backup get all active by window context begin end None project id None return IMPL backup get all active by window context begin end project id
null
null
null
null
Question: Where does the code get all the backups ? Code: def backup_get_all_active_by_window(context, begin, end=None, project_id=None): return IMPL.backup_get_all_active_by_window(context, begin, end, project_id)
null
null
null
What does the code get inside the window ?
def backup_get_all_active_by_window(context, begin, end=None, project_id=None): return IMPL.backup_get_all_active_by_window(context, begin, end, project_id)
null
null
null
all the backups
codeqa
def backup get all active by window context begin end None project id None return IMPL backup get all active by window context begin end project id
null
null
null
null
Question: What does the code get inside the window ? Code: def backup_get_all_active_by_window(context, begin, end=None, project_id=None): return IMPL.backup_get_all_active_by_window(context, begin, end, project_id)
null
null
null
When d the code get a monitor snapshot ?
def _find_monitor_snapshot(cs, snapshot): return utils.find_resource(cs.monitor_snapshots, snapshot)
null
null
null
by i d
codeqa
def find monitor snapshot cs snapshot return utils find resource cs monitor snapshots snapshot
null
null
null
null
Question: When d the code get a monitor snapshot ? Code: def _find_monitor_snapshot(cs, snapshot): return utils.find_resource(cs.monitor_snapshots, snapshot)
null
null
null
What d the code get by i d ?
def _find_monitor_snapshot(cs, snapshot): return utils.find_resource(cs.monitor_snapshots, snapshot)
null
null
null
a monitor snapshot
codeqa
def find monitor snapshot cs snapshot return utils find resource cs monitor snapshots snapshot
null
null
null
null
Question: What d the code get by i d ? Code: def _find_monitor_snapshot(cs, snapshot): return utils.find_resource(cs.monitor_snapshots, snapshot)
null
null
null
What does the code create from optional arguments ?
def worker_create(context, **values): return IMPL.worker_create(context, **values)
null
null
null
a worker entry
codeqa
def worker create context **values return IMPL worker create context **values
null
null
null
null
Question: What does the code create from optional arguments ? Code: def worker_create(context, **values): return IMPL.worker_create(context, **values)
null
null
null
What did the code set ?
def publish_parts(source, source_path=None, source_class=io.StringInput, destination_path=None, reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', writer=None, writer_name='pseudoxml', settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=False): (output, pub) = publish_programmatically(source=source, source_path=source_path, source_class=source_class, destination_class=io.StringOutput, destination=None, destination_path=destination_path, reader=reader, reader_name=reader_name, parser=parser, parser_name=parser_name, writer=writer, writer_name=writer_name, settings=settings, settings_spec=settings_spec, settings_overrides=settings_overrides, config_section=config_section, enable_exit_status=enable_exit_status) return pub.writer.parts
null
null
null
a publisher
codeqa
def publish parts source source path None source class io String Input destination path None reader None reader name 'standalone' parser None parser name 'restructuredtext' writer None writer name 'pseudoxml' settings None settings spec None settings overrides None config section None enable exit status False output pub publish programmatically source source source path source path source class source class destination class io String Output destination None destination path destination path reader reader reader name reader name parser parser parser name parser name writer writer writer name writer name settings settings settings spec settings spec settings overrides settings overrides config section config section enable exit status enable exit status return pub writer parts
null
null
null
null
Question: What did the code set ? Code: def publish_parts(source, source_path=None, source_class=io.StringInput, destination_path=None, reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', writer=None, writer_name='pseudoxml', settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=False): (output, pub) = publish_programmatically(source=source, source_path=source_path, source_class=source_class, destination_class=io.StringOutput, destination=None, destination_path=destination_path, reader=reader, reader_name=reader_name, parser=parser, parser_name=parser_name, writer=writer, writer_name=writer_name, settings=settings, settings_spec=settings_spec, settings_overrides=settings_overrides, config_section=config_section, enable_exit_status=enable_exit_status) return pub.writer.parts
null
null
null
How does the code find child nodes ?
def _get_children_as(parent, tag, construct): return [construct(child) for child in parent.findall(_ns(tag))]
null
null
null
by tag
codeqa
def get children as parent tag construct return [construct child for child in parent findall ns tag ]
null
null
null
null
Question: How does the code find child nodes ? Code: def _get_children_as(parent, tag, construct): return [construct(child) for child in parent.findall(_ns(tag))]
null
null
null
In which direction do each pass ?
def _get_children_as(parent, tag, construct): return [construct(child) for child in parent.findall(_ns(tag))]
null
null
null
through a constructor
codeqa
def get children as parent tag construct return [construct child for child in parent findall ns tag ]
null
null
null
null
Question: In which direction do each pass ? Code: def _get_children_as(parent, tag, construct): return [construct(child) for child in parent.findall(_ns(tag))]
null
null
null
What does the code find by tag ?
def _get_children_as(parent, tag, construct): return [construct(child) for child in parent.findall(_ns(tag))]
null
null
null
child nodes
codeqa
def get children as parent tag construct return [construct child for child in parent findall ns tag ]
null
null
null
null
Question: What does the code find by tag ? Code: def _get_children_as(parent, tag, construct): return [construct(child) for child in parent.findall(_ns(tag))]
null
null
null
How does the code get packed geometry output ?
def getPackedGeometryOutputByLoop(elementNode, sideLoop): sideLoop.rotate(elementNode) return getGeometryOutputByManipulation(elementNode, sideLoop)
null
null
null
by side loop
codeqa
def get Packed Geometry Output By Loop element Node side Loop side Loop rotate element Node return get Geometry Output By Manipulation element Node side Loop
null
null
null
null
Question: How does the code get packed geometry output ? Code: def getPackedGeometryOutputByLoop(elementNode, sideLoop): sideLoop.rotate(elementNode) return getGeometryOutputByManipulation(elementNode, sideLoop)
null
null
null
What does the code get by side loop ?
def getPackedGeometryOutputByLoop(elementNode, sideLoop): sideLoop.rotate(elementNode) return getGeometryOutputByManipulation(elementNode, sideLoop)
null
null
null
packed geometry output
codeqa
def get Packed Geometry Output By Loop element Node side Loop side Loop rotate element Node return get Geometry Output By Manipulation element Node side Loop
null
null
null
null
Question: What does the code get by side loop ? Code: def getPackedGeometryOutputByLoop(elementNode, sideLoop): sideLoop.rotate(elementNode) return getGeometryOutputByManipulation(elementNode, sideLoop)
null
null
null
How do the sequence reshape ?
def reshape(seq, how): m = sum(flatten(how)) (n, rem) = divmod(len(seq), m) if ((m < 0) or rem): raise ValueError('template must sum to positive number that divides the length of the sequence') i = 0 container = type(how) rv = ([None] * n) for k in range(len(rv)): rv[k] = [] for hi in how: if (type(hi) is int): rv[k].extend(seq[i:(i + hi)]) i += hi else: n = sum(flatten(hi)) hi_type = type(hi) rv[k].append(hi_type(reshape(seq[i:(i + n)], hi)[0])) i += n rv[k] = container(rv[k]) return type(seq)(rv)
null
null
null
according to the template in how
codeqa
def reshape seq how m sum flatten how n rem divmod len seq m if m < 0 or rem raise Value Error 'templatemustsumtopositivenumberthatdividesthelengthofthesequence' i 0container type how rv [ None] * n for k in range len rv rv[k] []for hi in how if type hi is int rv[k] extend seq[i i + hi ] i + hielse n sum flatten hi hi type type hi rv[k] append hi type reshape seq[i i + n ] hi [0 ] i + nrv[k] container rv[k] return type seq rv
null
null
null
null
Question: How do the sequence reshape ? Code: def reshape(seq, how): m = sum(flatten(how)) (n, rem) = divmod(len(seq), m) if ((m < 0) or rem): raise ValueError('template must sum to positive number that divides the length of the sequence') i = 0 container = type(how) rv = ([None] * n) for k in range(len(rv)): rv[k] = [] for hi in how: if (type(hi) is int): rv[k].extend(seq[i:(i + hi)]) i += hi else: n = sum(flatten(hi)) hi_type = type(hi) rv[k].append(hi_type(reshape(seq[i:(i + n)], hi)[0])) i += n rv[k] = container(rv[k]) return type(seq)(rv)
null
null
null
What does the code check ?
def checkPath(filename, reporter=None): if (reporter is None): reporter = modReporter._makeDefaultReporter() try: if (sys.version_info < (2, 7)): mode = 'rU' else: mode = 'rb' with open(filename, mode) as f: codestr = f.read() if (sys.version_info < (2, 7)): codestr += '\n' except UnicodeError: reporter.unexpectedError(filename, 'problem decoding source') return 1 except IOError: msg = sys.exc_info()[1] reporter.unexpectedError(filename, msg.args[1]) return 1 return check(codestr, filename, reporter)
null
null
null
the given path
codeqa
def check Path filename reporter None if reporter is None reporter mod Reporter make Default Reporter try if sys version info < 2 7 mode 'r U'else mode 'rb'with open filename mode as f codestr f read if sys version info < 2 7 codestr + '\n'except Unicode Error reporter unexpected Error filename 'problemdecodingsource' return 1except IO Error msg sys exc info [1 ]reporter unexpected Error filename msg args[ 1 ] return 1return check codestr filename reporter
null
null
null
null
Question: What does the code check ? Code: def checkPath(filename, reporter=None): if (reporter is None): reporter = modReporter._makeDefaultReporter() try: if (sys.version_info < (2, 7)): mode = 'rU' else: mode = 'rb' with open(filename, mode) as f: codestr = f.read() if (sys.version_info < (2, 7)): codestr += '\n' except UnicodeError: reporter.unexpectedError(filename, 'problem decoding source') return 1 except IOError: msg = sys.exc_info()[1] reporter.unexpectedError(filename, msg.args[1]) return 1 return check(codestr, filename, reporter)
null
null
null
What does the code find ?
def FindPackagePath(packageName, knownFileName, searchPaths): import regutil, os pathLook = regutil.GetRegisteredNamedPath(packageName) if (pathLook and IsPackageDir(pathLook, packageName, knownFileName)): return (pathLook, None) for pathLook in searchPaths: if IsPackageDir(pathLook, packageName, knownFileName): ret = os.path.abspath(pathLook) return (ret, ret) raise error, ('The package %s can not be located' % packageName)
null
null
null
a package
codeqa
def Find Package Path package Name known File Name search Paths import regutil ospath Look regutil Get Registered Named Path package Name if path Look and Is Package Dir path Look package Name known File Name return path Look None for path Look in search Paths if Is Package Dir path Look package Name known File Name ret os path abspath path Look return ret ret raise error ' Thepackage%scannotbelocated' % package Name
null
null
null
null
Question: What does the code find ? Code: def FindPackagePath(packageName, knownFileName, searchPaths): import regutil, os pathLook = regutil.GetRegisteredNamedPath(packageName) if (pathLook and IsPackageDir(pathLook, packageName, knownFileName)): return (pathLook, None) for pathLook in searchPaths: if IsPackageDir(pathLook, packageName, knownFileName): ret = os.path.abspath(pathLook) return (ret, ret) raise error, ('The package %s can not be located' % packageName)
null
null
null
What does the code enable ?
def enable_microsites(log): if is_feature_enabled(): BACKEND.enable_microsites(log)
null
null
null
the use of microsites during the startup script
codeqa
def enable microsites log if is feature enabled BACKEND enable microsites log
null
null
null
null
Question: What does the code enable ? Code: def enable_microsites(log): if is_feature_enabled(): BACKEND.enable_microsites(log)
null
null
null
How can the argument be serialized ?
def _is_numeric(x): try: float(str(x)) return True except ValueError: return False
null
null
null
as a number
codeqa
def is numeric x try float str x return Trueexcept Value Error return False
null
null
null
null
Question: How can the argument be serialized ? Code: def _is_numeric(x): try: float(str(x)) return True except ValueError: return False
null
null
null
What does the code get ?
def addValueToEvaluatedDictionary(elementNode, evaluatedDictionary, key): value = getEvaluatedValueObliviously(elementNode, key) if (value == None): valueString = str(elementNode.attributes[key]) print 'Warning, addValueToEvaluatedDictionary in evaluate can not get a value for:' print valueString evaluatedDictionary[(key + '__Warning__')] = ('Can not evaluate: ' + valueString.replace('"', ' ').replace("'", ' ')) else: evaluatedDictionary[key] = value
null
null
null
the evaluated dictionary
codeqa
def add Value To Evaluated Dictionary element Node evaluated Dictionary key value get Evaluated Value Obliviously element Node key if value None value String str element Node attributes[key] print ' Warning add Value To Evaluated Dictionaryinevaluatecannotgetavaluefor 'print value Stringevaluated Dictionary[ key + ' Warning ' ] ' Cannotevaluate ' + value String replace '"' '' replace "'" '' else evaluated Dictionary[key] value
null
null
null
null
Question: What does the code get ? Code: def addValueToEvaluatedDictionary(elementNode, evaluatedDictionary, key): value = getEvaluatedValueObliviously(elementNode, key) if (value == None): valueString = str(elementNode.attributes[key]) print 'Warning, addValueToEvaluatedDictionary in evaluate can not get a value for:' print valueString evaluatedDictionary[(key + '__Warning__')] = ('Can not evaluate: ' + valueString.replace('"', ' ').replace("'", ' ')) else: evaluatedDictionary[key] = value
null
null
null
What does the code create ?
def new_figure_manager(num, *args, **kwargs): if _debug: print ('backend_gtkcairo.%s()' % fn_name()) FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) canvas = FigureCanvasGTKCairo(thisFig) return FigureManagerGTK(canvas, num)
null
null
null
a new figure manager instance
codeqa
def new figure manager num *args **kwargs if debug print 'backend gtkcairo %s ' % fn name Figure Class kwargs pop ' Figure Class' Figure this Fig Figure Class *args **kwargs canvas Figure Canvas GTK Cairo this Fig return Figure Manager GTK canvas num
null
null
null
null
Question: What does the code create ? Code: def new_figure_manager(num, *args, **kwargs): if _debug: print ('backend_gtkcairo.%s()' % fn_name()) FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) canvas = FigureCanvasGTKCairo(thisFig) return FigureManagerGTK(canvas, num)
null
null
null
What do the minute line markers and timestamps parameters start ?
def draw_lines(start, total_duration, minute_scale, scale): result = u'' next_line = 220 next_time = start num_lines = (((total_duration // 60) // minute_scale) + 2) for line in range(num_lines): new_line = (u"<hr class='line' width='98%%' style='top:%dpx;'>" % next_line) result += new_line time = (u"<p class='time' style='top:%dpx;'> %02d:%02d </p>" % ((next_line - 20), next_time.hour, next_time.minute)) result += time next_line += (minute_scale * scale) next_time += datetime.timedelta(minutes=minute_scale) return result
null
null
null
datetime
codeqa
def draw lines start total duration minute scale scale result u''next line 220 next time startnum lines total duration // 60 // minute scale + 2 for line in range num lines new line u"<hrclass 'line'width '98 %%'style 'top %dpx '>" % next line result + new linetime u"<pclass 'time'style 'top %dpx '>% 02 d %02 d</p>" % next line - 20 next time hour next time minute result + timenext line + minute scale * scale next time + datetime timedelta minutes minute scale return result
null
null
null
null
Question: What do the minute line markers and timestamps parameters start ? Code: def draw_lines(start, total_duration, minute_scale, scale): result = u'' next_line = 220 next_time = start num_lines = (((total_duration // 60) // minute_scale) + 2) for line in range(num_lines): new_line = (u"<hr class='line' width='98%%' style='top:%dpx;'>" % next_line) result += new_line time = (u"<p class='time' style='top:%dpx;'> %02d:%02d </p>" % ((next_line - 20), next_time.hour, next_time.minute)) result += time next_line += (minute_scale * scale) next_time += datetime.timedelta(minutes=minute_scale) return result
null
null
null
which organization view ?
@staff_member_required def update_issue(request, pk, mode=None, action=None): issue = Issue.obj.get(pk=pk) if (mode == 'delete'): issue.delete() return redir('admin:issues_issue_changelist') else: if (mode == 'progress'): val = int(action) else: val = bool((action == 'on')) setattr(issue, mode, val) issue.save() return HttpResponse('')
null
null
null
ajax
codeqa
@staff member requireddef update issue request pk mode None action None issue Issue obj get pk pk if mode 'delete' issue delete return redir 'admin issues issue changelist' else if mode 'progress' val int action else val bool action 'on' setattr issue mode val issue save return Http Response ''
null
null
null
null
Question: which organization view ? Code: @staff_member_required def update_issue(request, pk, mode=None, action=None): issue = Issue.obj.get(pk=pk) if (mode == 'delete'): issue.delete() return redir('admin:issues_issue_changelist') else: if (mode == 'progress'): val = int(action) else: val = bool((action == 'on')) setattr(issue, mode, val) issue.save() return HttpResponse('')
null
null
null
What has parents ?
def key_kind_n(index): @empty_if_none def transform_function(key): path = key.to_path() path_index = (index * 2) return unicode(path[path_index]) return transform_function
null
null
null
a key
codeqa
def key kind n index @empty if nonedef transform function key path key to path path index index * 2 return unicode path[path index] return transform function
null
null
null
null
Question: What has parents ? Code: def key_kind_n(index): @empty_if_none def transform_function(key): path = key.to_path() path_index = (index * 2) return unicode(path[path_index]) return transform_function
null
null
null
What does a key have ?
def key_kind_n(index): @empty_if_none def transform_function(key): path = key.to_path() path_index = (index * 2) return unicode(path[path_index]) return transform_function
null
null
null
parents
codeqa
def key kind n index @empty if nonedef transform function key path key to path path index index * 2 return unicode path[path index] return transform function
null
null
null
null
Question: What does a key have ? Code: def key_kind_n(index): @empty_if_none def transform_function(key): path = key.to_path() path_index = (index * 2) return unicode(path[path_index]) return transform_function
null
null
null
What does the code expand ?
def expand_user(path): tilde_expand = False tilde_val = '' newpath = path if path.startswith('~'): tilde_expand = True rest = (len(path) - 1) newpath = os.path.expanduser(path) if rest: tilde_val = newpath[:(- rest)] else: tilde_val = newpath return (newpath, tilde_expand, tilde_val)
null
null
null
~-style usernames in strings
codeqa
def expand user path tilde expand Falsetilde val ''newpath pathif path startswith '~' tilde expand Truerest len path - 1 newpath os path expanduser path if rest tilde val newpath[ - rest ]else tilde val newpathreturn newpath tilde expand tilde val
null
null
null
null
Question: What does the code expand ? Code: def expand_user(path): tilde_expand = False tilde_val = '' newpath = path if path.startswith('~'): tilde_expand = True rest = (len(path) - 1) newpath = os.path.expanduser(path) if rest: tilde_val = newpath[:(- rest)] else: tilde_val = newpath return (newpath, tilde_expand, tilde_val)
null
null
null
What does the code return ?
def run_scenario(application='', feature='', scenario='', **opts): if application: application = ' {0}/features/'.format(application) if feature: feature = '{0}.feature'.format(feature) if scenario: scenario = ' -s {0:d}'.format(scenario) opts_string = '' for (opt, val) in opts.iteritems(): if (not val): val = '' opts_string = ' '.join((opts_string, opt, val)) cmd = 'python manage.py harvest -v 3 -T {0}{1}{2}{3}'.format(opts_string, application, feature, scenario) return commands.getstatusoutput(cmd)
null
null
null
its output vars
codeqa
def run scenario application '' feature '' scenario '' **opts if application application '{ 0 }/features/' format application if feature feature '{ 0 } feature' format feature if scenario scenario '-s{ 0 d}' format scenario opts string ''for opt val in opts iteritems if not val val ''opts string '' join opts string opt val cmd 'pythonmanage pyharvest-v 3 -T{ 0 }{ 1 }{ 2 }{ 3 }' format opts string application feature scenario return commands getstatusoutput cmd
null
null
null
null
Question: What does the code return ? Code: def run_scenario(application='', feature='', scenario='', **opts): if application: application = ' {0}/features/'.format(application) if feature: feature = '{0}.feature'.format(feature) if scenario: scenario = ' -s {0:d}'.format(scenario) opts_string = '' for (opt, val) in opts.iteritems(): if (not val): val = '' opts_string = ' '.join((opts_string, opt, val)) cmd = 'python manage.py harvest -v 3 -T {0}{1}{2}{3}'.format(opts_string, application, feature, scenario) return commands.getstatusoutput(cmd)
null
null
null
What is applied before exclude_names ?
@pytest.mark.parametrize('parallel', [True, False]) def test_include_exclude_names(parallel, read_basic): text = '\nA B C D E F G H\n1 2 3 4 5 6 7 8\n9 10 11 12 13 14 15 16\n' table = read_basic(text, include_names=['A', 'B', 'D', 'F', 'H'], exclude_names=['B', 'F'], parallel=parallel) expected = Table([[1, 9], [4, 12], [8, 16]], names=('A', 'D', 'H')) assert_table_equal(table, expected)
null
null
null
include_names
codeqa
@pytest mark parametrize 'parallel' [ True False] def test include exclude names parallel read basic text '\n ABCDEFGH\n 12345678 \n 910111213141516 \n'table read basic text include names ['A' 'B' 'D' 'F' 'H'] exclude names ['B' 'F'] parallel parallel expected Table [[ 1 9] [4 12 ] [8 16 ]] names 'A' 'D' 'H' assert table equal table expected
null
null
null
null
Question: What is applied before exclude_names ? Code: @pytest.mark.parametrize('parallel', [True, False]) def test_include_exclude_names(parallel, read_basic): text = '\nA B C D E F G H\n1 2 3 4 5 6 7 8\n9 10 11 12 13 14 15 16\n' table = read_basic(text, include_names=['A', 'B', 'D', 'F', 'H'], exclude_names=['B', 'F'], parallel=parallel) expected = Table([[1, 9], [4, 12], [8, 16]], names=('A', 'D', 'H')) assert_table_equal(table, expected)
null
null
null
What did the code set in minutes for the given power scheme ?
def set_disk_timeout(timeout, power='ac', scheme=None): return _set_powercfg_value(scheme, 'SUB_DISK', 'DISKIDLE', power, timeout)
null
null
null
the disk timeout
codeqa
def set disk timeout timeout power 'ac' scheme None return set powercfg value scheme 'SUB DISK' 'DISKIDLE' power timeout
null
null
null
null
Question: What did the code set in minutes for the given power scheme ? Code: def set_disk_timeout(timeout, power='ac', scheme=None): return _set_powercfg_value(scheme, 'SUB_DISK', 'DISKIDLE', power, timeout)
null
null
null
By how much did the code set the disk timeout for the given power scheme ?
def set_disk_timeout(timeout, power='ac', scheme=None): return _set_powercfg_value(scheme, 'SUB_DISK', 'DISKIDLE', power, timeout)
null
null
null
in minutes
codeqa
def set disk timeout timeout power 'ac' scheme None return set powercfg value scheme 'SUB DISK' 'DISKIDLE' power timeout
null
null
null
null
Question: By how much did the code set the disk timeout for the given power scheme ? Code: def set_disk_timeout(timeout, power='ac', scheme=None): return _set_powercfg_value(scheme, 'SUB_DISK', 'DISKIDLE', power, timeout)
null
null
null
For what purpose did the code set the disk timeout in minutes ?
def set_disk_timeout(timeout, power='ac', scheme=None): return _set_powercfg_value(scheme, 'SUB_DISK', 'DISKIDLE', power, timeout)
null
null
null
for the given power scheme
codeqa
def set disk timeout timeout power 'ac' scheme None return set powercfg value scheme 'SUB DISK' 'DISKIDLE' power timeout
null
null
null
null
Question: For what purpose did the code set the disk timeout in minutes ? Code: def set_disk_timeout(timeout, power='ac', scheme=None): return _set_powercfg_value(scheme, 'SUB_DISK', 'DISKIDLE', power, timeout)
null
null
null
When does the code validate ?
@pytest.mark.skipif(u'not HAS_PATHLIB') def test_validate_path_object(): test_validate(test_path_object=True)
null
null
null
when source is passed as path object
codeqa
@pytest mark skipif u'not HAS PATHLIB' def test validate path object test validate test path object True
null
null
null
null
Question: When does the code validate ? Code: @pytest.mark.skipif(u'not HAS_PATHLIB') def test_validate_path_object(): test_validate(test_path_object=True)
null
null
null
What does the code remove ?
def filter_samples_from_distance_matrix(dm, samples_to_discard, negate=False): try: (sample_ids, dm_data) = dm except ValueError: (sample_ids, dm_data) = parse_distmat(dm) sample_lookup = {}.fromkeys([e.split()[0] for e in samples_to_discard]) temp_dm_data = [] new_dm_data = [] new_sample_ids = [] if negate: def keep_sample(s): return (s in sample_lookup) else: def keep_sample(s): return (s not in sample_lookup) for (row, sample_id) in zip(dm_data, sample_ids): if keep_sample(sample_id): temp_dm_data.append(row) new_sample_ids.append(sample_id) temp_dm_data = array(temp_dm_data).transpose() for (col, sample_id) in zip(temp_dm_data, sample_ids): if keep_sample(sample_id): new_dm_data.append(col) new_dm_data = array(new_dm_data).transpose() return format_distance_matrix(new_sample_ids, new_dm_data)
null
null
null
specified samples from distance matrix dm : tuple
codeqa
def filter samples from distance matrix dm samples to discard negate False try sample ids dm data dmexcept Value Error sample ids dm data parse distmat dm sample lookup {} fromkeys [e split [0 ] for e in samples to discard] temp dm data []new dm data []new sample ids []if negate def keep sample s return s in sample lookup else def keep sample s return s not in sample lookup for row sample id in zip dm data sample ids if keep sample sample id temp dm data append row new sample ids append sample id temp dm data array temp dm data transpose for col sample id in zip temp dm data sample ids if keep sample sample id new dm data append col new dm data array new dm data transpose return format distance matrix new sample ids new dm data
null
null
null
null
Question: What does the code remove ? Code: def filter_samples_from_distance_matrix(dm, samples_to_discard, negate=False): try: (sample_ids, dm_data) = dm except ValueError: (sample_ids, dm_data) = parse_distmat(dm) sample_lookup = {}.fromkeys([e.split()[0] for e in samples_to_discard]) temp_dm_data = [] new_dm_data = [] new_sample_ids = [] if negate: def keep_sample(s): return (s in sample_lookup) else: def keep_sample(s): return (s not in sample_lookup) for (row, sample_id) in zip(dm_data, sample_ids): if keep_sample(sample_id): temp_dm_data.append(row) new_sample_ids.append(sample_id) temp_dm_data = array(temp_dm_data).transpose() for (col, sample_id) in zip(temp_dm_data, sample_ids): if keep_sample(sample_id): new_dm_data.append(col) new_dm_data = array(new_dm_data).transpose() return format_distance_matrix(new_sample_ids, new_dm_data)
null
null
null
What does the code remove ?
def strip_control_sequences(string): global _STRIP_ANSI if (not _STRIP_ANSI): from evennia.utils.ansi import strip_raw_ansi as _STRIP_ANSI return _RE_CONTROL_CHAR.sub('', _STRIP_ANSI(string))
null
null
null
non - print text sequences
codeqa
def strip control sequences string global STRIP ANS Iif not STRIP ANSI from evennia utils ansi import strip raw ansi as STRIP ANS Ireturn RE CONTROL CHAR sub '' STRIP ANSI string
null
null
null
null
Question: What does the code remove ? Code: def strip_control_sequences(string): global _STRIP_ANSI if (not _STRIP_ANSI): from evennia.utils.ansi import strip_raw_ansi as _STRIP_ANSI return _RE_CONTROL_CHAR.sub('', _STRIP_ANSI(string))
null
null
null
What does the code create ?
def generate_new_element(items, prefix, numeric=False): while True: if numeric: candidate = (prefix + generate_random_numeric(8)) else: candidate = (prefix + generate_random_alphanumeric(8)) if (candidate not in items): return candidate LOG.debug(('Random collision on %s' % candidate))
null
null
null
a random string with prefix
codeqa
def generate new element items prefix numeric False while True if numeric candidate prefix + generate random numeric 8 else candidate prefix + generate random alphanumeric 8 if candidate not in items return candidate LOG debug ' Randomcollisionon%s' % candidate
null
null
null
null
Question: What does the code create ? Code: def generate_new_element(items, prefix, numeric=False): while True: if numeric: candidate = (prefix + generate_random_numeric(8)) else: candidate = (prefix + generate_random_alphanumeric(8)) if (candidate not in items): return candidate LOG.debug(('Random collision on %s' % candidate))
null
null
null
What does the code get ?
def getVisibleObjectLoopsList(importRadius, visibleObjects, z): visibleObjectLoopsList = [] for visibleObject in visibleObjects: visibleObjectLoops = visibleObject.getLoops(importRadius, z) visibleObjectLoopsList.append(visibleObjectLoops) return visibleObjectLoopsList
null
null
null
visible object loops list
codeqa
def get Visible Object Loops List import Radius visible Objects z visible Object Loops List []for visible Object in visible Objects visible Object Loops visible Object get Loops import Radius z visible Object Loops List append visible Object Loops return visible Object Loops List
null
null
null
null
Question: What does the code get ? Code: def getVisibleObjectLoopsList(importRadius, visibleObjects, z): visibleObjectLoopsList = [] for visibleObject in visibleObjects: visibleObjectLoops = visibleObject.getLoops(importRadius, z) visibleObjectLoopsList.append(visibleObjectLoops) return visibleObjectLoopsList
null
null
null
What do callback decorator require ?
def auth_basic(check, realm='private', text='Access denied'): def decorator(func): def wrapper(*a, **ka): (user, password) = (request.auth or (None, None)) if ((user is None) or (not check(user, password))): err = HTTPError(401, text) err.add_header('WWW-Authenticate', ('Basic realm="%s"' % realm)) return err return func(*a, **ka) return wrapper return decorator
null
null
null
http auth
codeqa
def auth basic check realm 'private' text ' Accessdenied' def decorator func def wrapper *a **ka user password request auth or None None if user is None or not check user password err HTTP Error 401 text err add header 'WWW- Authenticate' ' Basicrealm "%s"' % realm return errreturn func *a **ka return wrapperreturn decorator
null
null
null
null
Question: What do callback decorator require ? Code: def auth_basic(check, realm='private', text='Access denied'): def decorator(func): def wrapper(*a, **ka): (user, password) = (request.auth or (None, None)) if ((user is None) or (not check(user, password))): err = HTTPError(401, text) err.add_header('WWW-Authenticate', ('Basic realm="%s"' % realm)) return err return func(*a, **ka) return wrapper return decorator
null
null
null
What does the code get ?
@frappe.whitelist() def get_versions(): versions = {} for app in frappe.get_installed_apps(sort=True): versions[app] = {u'title': frappe.get_hooks(u'app_title', app_name=app)[0], u'description': frappe.get_hooks(u'app_description', app_name=app)[0]} try: versions[app][u'version'] = frappe.get_attr((app + u'.__version__')) except AttributeError: versions[app][u'version'] = u'0.0.1' return versions
null
null
null
versions of all installed apps
codeqa
@frappe whitelist def get versions versions {}for app in frappe get installed apps sort True versions[app] {u'title' frappe get hooks u'app title' app name app [0 ] u'description' frappe get hooks u'app description' app name app [0 ]}try versions[app][u'version'] frappe get attr app + u' version ' except Attribute Error versions[app][u'version'] u' 0 0 1'return versions
null
null
null
null
Question: What does the code get ? Code: @frappe.whitelist() def get_versions(): versions = {} for app in frappe.get_installed_apps(sort=True): versions[app] = {u'title': frappe.get_hooks(u'app_title', app_name=app)[0], u'description': frappe.get_hooks(u'app_description', app_name=app)[0]} try: versions[app][u'version'] = frappe.get_attr((app + u'.__version__')) except AttributeError: versions[app][u'version'] = u'0.0.1' return versions
null
null
null
What does the code reset ?
@utils.arg('--all-tenants', action='store_const', const=1, default=0, help=_('Reset state server(s) in another tenant by name (Admin only).')) @utils.arg('server', metavar='<server>', nargs='+', help=_('Name or ID of server(s).')) @utils.arg('--active', action='store_const', dest='state', default='error', const='active', help=_('Request the server be reset to "active" state instead of "error" state (the default).')) def do_reset_state(cs, args): failure_flag = False find_args = {'all_tenants': args.all_tenants} for server in args.server: try: _find_server(cs, server, **find_args).reset_state(args.state) msg = 'Reset state for server %s succeeded; new state is %s' print((msg % (server, args.state))) except Exception as e: failure_flag = True msg = ('Reset state for server %s failed: %s' % (server, e)) print(msg) if failure_flag: msg = 'Unable to reset the state for the specified server(s).' raise exceptions.CommandError(msg)
null
null
null
the state of a server
codeqa
@utils arg '--all-tenants' action 'store const' const 1 default 0 help ' Resetstateserver s inanothertenantbyname Adminonly ' @utils arg 'server' metavar '<server>' nargs '+' help ' Nameor I Dofserver s ' @utils arg '--active' action 'store const' dest 'state' default 'error' const 'active' help ' Requesttheserverberesetto"active"stateinsteadof"error"state thedefault ' def do reset state cs args failure flag Falsefind args {'all tenants' args all tenants}for server in args server try find server cs server **find args reset state args state msg ' Resetstateforserver%ssucceeded newstateis%s'print msg % server args state except Exception as e failure flag Truemsg ' Resetstateforserver%sfailed %s' % server e print msg if failure flag msg ' Unabletoresetthestateforthespecifiedserver s 'raise exceptions Command Error msg
null
null
null
null
Question: What does the code reset ? Code: @utils.arg('--all-tenants', action='store_const', const=1, default=0, help=_('Reset state server(s) in another tenant by name (Admin only).')) @utils.arg('server', metavar='<server>', nargs='+', help=_('Name or ID of server(s).')) @utils.arg('--active', action='store_const', dest='state', default='error', const='active', help=_('Request the server be reset to "active" state instead of "error" state (the default).')) def do_reset_state(cs, args): failure_flag = False find_args = {'all_tenants': args.all_tenants} for server in args.server: try: _find_server(cs, server, **find_args).reset_state(args.state) msg = 'Reset state for server %s succeeded; new state is %s' print((msg % (server, args.state))) except Exception as e: failure_flag = True msg = ('Reset state for server %s failed: %s' % (server, e)) print(msg) if failure_flag: msg = 'Unable to reset the state for the specified server(s).' raise exceptions.CommandError(msg)
null
null
null
What returns a geometry ?
def check_geom(result, func, cargs): if isinstance(result, six.integer_types): result = c_void_p(result) if (not result): raise OGRException(('Invalid geometry pointer returned from "%s".' % func.__name__)) return result
null
null
null
a function
codeqa
def check geom result func cargs if isinstance result six integer types result c void p result if not result raise OGR Exception ' Invalidgeometrypointerreturnedfrom"%s" ' % func name return result
null
null
null
null
Question: What returns a geometry ? Code: def check_geom(result, func, cargs): if isinstance(result, six.integer_types): result = c_void_p(result) if (not result): raise OGRException(('Invalid geometry pointer returned from "%s".' % func.__name__)) return result
null
null
null
What does a function return ?
def check_geom(result, func, cargs): if isinstance(result, six.integer_types): result = c_void_p(result) if (not result): raise OGRException(('Invalid geometry pointer returned from "%s".' % func.__name__)) return result
null
null
null
a geometry
codeqa
def check geom result func cargs if isinstance result six integer types result c void p result if not result raise OGR Exception ' Invalidgeometrypointerreturnedfrom"%s" ' % func name return result
null
null
null
null
Question: What does a function return ? Code: def check_geom(result, func, cargs): if isinstance(result, six.integer_types): result = c_void_p(result) if (not result): raise OGRException(('Invalid geometry pointer returned from "%s".' % func.__name__)) return result
null
null
null
What does the code return to represent the partition ?
def list_visitor(state, components): (f, lpart, pstack) = state partition = [] for i in range((lpart + 1)): part = [] for ps in pstack[f[i]:f[(i + 1)]]: if (ps.v > 0): part.extend(([components[ps.c]] * ps.v)) partition.append(part) return partition
null
null
null
a list of lists
codeqa
def list visitor state components f lpart pstack statepartition []for i in range lpart + 1 part []for ps in pstack[f[i] f[ i + 1 ]] if ps v > 0 part extend [components[ps c]] * ps v partition append part return partition
null
null
null
null
Question: What does the code return to represent the partition ? Code: def list_visitor(state, components): (f, lpart, pstack) = state partition = [] for i in range((lpart + 1)): part = [] for ps in pstack[f[i]:f[(i + 1)]]: if (ps.v > 0): part.extend(([components[ps.c]] * ps.v)) partition.append(part) return partition
null
null
null
For what purpose does the code return a list of lists ?
def list_visitor(state, components): (f, lpart, pstack) = state partition = [] for i in range((lpart + 1)): part = [] for ps in pstack[f[i]:f[(i + 1)]]: if (ps.v > 0): part.extend(([components[ps.c]] * ps.v)) partition.append(part) return partition
null
null
null
to represent the partition
codeqa
def list visitor state components f lpart pstack statepartition []for i in range lpart + 1 part []for ps in pstack[f[i] f[ i + 1 ]] if ps v > 0 part extend [components[ps c]] * ps v partition append part return partition
null
null
null
null
Question: For what purpose does the code return a list of lists ? Code: def list_visitor(state, components): (f, lpart, pstack) = state partition = [] for i in range((lpart + 1)): part = [] for ps in pstack[f[i]:f[(i + 1)]]: if (ps.v > 0): part.extend(([components[ps.c]] * ps.v)) partition.append(part) return partition
null
null
null
What does the code get from the database ?
@with_session def get_cached(style=None, title=None, year=None, trakt_id=None, trakt_slug=None, tmdb_id=None, imdb_id=None, tvdb_id=None, tvrage_id=None, session=None): ids = {u'id': trakt_id, u'slug': trakt_slug, u'tmdb_id': tmdb_id, u'imdb_id': imdb_id} if (style == u'show'): ids[u'tvdb_id'] = tvdb_id ids[u'tvrage_id'] = tvrage_id model = TraktShow else: model = TraktMovie result = None if any(ids.values()): result = session.query(model).filter(or_(((getattr(model, col) == val) for (col, val) in ids.items() if val))).first() elif title: (title, y) = split_title_year(title) year = (year or y) query = session.query(model).filter((model.title == title)) if year: query = query.filter((model.year == year)) result = query.first() return result
null
null
null
the cached info for a given show / movie
codeqa
@with sessiondef get cached style None title None year None trakt id None trakt slug None tmdb id None imdb id None tvdb id None tvrage id None session None ids {u'id' trakt id u'slug' trakt slug u'tmdb id' tmdb id u'imdb id' imdb id}if style u'show' ids[u'tvdb id'] tvdb idids[u'tvrage id'] tvrage idmodel Trakt Showelse model Trakt Movieresult Noneif any ids values result session query model filter or getattr model col val for col val in ids items if val first elif title title y split title year title year year or y query session query model filter model title title if year query query filter model year year result query first return result
null
null
null
null
Question: What does the code get from the database ? Code: @with_session def get_cached(style=None, title=None, year=None, trakt_id=None, trakt_slug=None, tmdb_id=None, imdb_id=None, tvdb_id=None, tvrage_id=None, session=None): ids = {u'id': trakt_id, u'slug': trakt_slug, u'tmdb_id': tmdb_id, u'imdb_id': imdb_id} if (style == u'show'): ids[u'tvdb_id'] = tvdb_id ids[u'tvrage_id'] = tvrage_id model = TraktShow else: model = TraktMovie result = None if any(ids.values()): result = session.query(model).filter(or_(((getattr(model, col) == val) for (col, val) in ids.items() if val))).first() elif title: (title, y) = split_title_year(title) year = (year or y) query = session.query(model).filter((model.title == title)) if year: query = query.filter((model.year == year)) result = query.first() return result
null
null
null
For what purpose is translation project added when ?
@pytest.mark.django_db def test_tp_empty_stats(project0_nongnu, project0, templates): language = LanguageDBFactory() tp = TranslationProject.objects.create(language=language, project=project0) tp.init_from_templates() assert (list(tp.stores.all()) == []) stats = tp.data_tool.get_stats() assert (stats['total'] == 0) assert (stats['translated'] == 0) assert (stats['fuzzy'] == 0) assert (stats['suggestions'] == 0) assert (stats['critical'] == 0)
null
null
null
for a project with existing but empty template translation project
codeqa
@pytest mark django dbdef test tp empty stats project 0 nongnu project 0 templates language Language DB Factory tp Translation Project objects create language language project project 0 tp init from templates assert list tp stores all [] stats tp data tool get stats assert stats['total'] 0 assert stats['translated'] 0 assert stats['fuzzy'] 0 assert stats['suggestions'] 0 assert stats['critical'] 0
null
null
null
null
Question: For what purpose is translation project added when ? Code: @pytest.mark.django_db def test_tp_empty_stats(project0_nongnu, project0, templates): language = LanguageDBFactory() tp = TranslationProject.objects.create(language=language, project=project0) tp.init_from_templates() assert (list(tp.stores.all()) == []) stats = tp.data_tool.get_stats() assert (stats['total'] == 0) assert (stats['translated'] == 0) assert (stats['fuzzy'] == 0) assert (stats['suggestions'] == 0) assert (stats['critical'] == 0)
null
null
null
What does the code add ?
def addCage(derivation, height, negatives, positives): copyShallow = derivation.elementNode.getCopyShallow() copyShallow.attributes['path'] = [Vector3(), Vector3(0.0, 0.0, height)] extrudeDerivation = extrude.ExtrudeDerivation(copyShallow) roundedExtendedRectangle = getRoundedExtendedRectangle(derivation.demiwidth, derivation.rectangleCenterX, 14) outsidePath = euclidean.getVector3Path(roundedExtendedRectangle) extrude.addPositives(extrudeDerivation, [outsidePath], positives) for bearingCenterX in derivation.bearingCenterXs: addNegativeSphere(derivation, negatives, bearingCenterX)
null
null
null
linear bearing cage
codeqa
def add Cage derivation height negatives positives copy Shallow derivation element Node get Copy Shallow copy Shallow attributes['path'] [ Vector 3 Vector 3 0 0 0 0 height ]extrude Derivation extrude Extrude Derivation copy Shallow rounded Extended Rectangle get Rounded Extended Rectangle derivation demiwidth derivation rectangle Center X 14 outside Path euclidean get Vector 3 Path rounded Extended Rectangle extrude add Positives extrude Derivation [outside Path] positives for bearing Center X in derivation bearing Center Xs add Negative Sphere derivation negatives bearing Center X
null
null
null
null
Question: What does the code add ? Code: def addCage(derivation, height, negatives, positives): copyShallow = derivation.elementNode.getCopyShallow() copyShallow.attributes['path'] = [Vector3(), Vector3(0.0, 0.0, height)] extrudeDerivation = extrude.ExtrudeDerivation(copyShallow) roundedExtendedRectangle = getRoundedExtendedRectangle(derivation.demiwidth, derivation.rectangleCenterX, 14) outsidePath = euclidean.getVector3Path(roundedExtendedRectangle) extrude.addPositives(extrudeDerivation, [outsidePath], positives) for bearingCenterX in derivation.bearingCenterXs: addNegativeSphere(derivation, negatives, bearingCenterX)
null
null
null
What uses a sequence ?
def find_sequence(fields, doing_specialization): for f in fields: if f.seq: if (not doing_specialization): return True if (str(f.type) not in _SPECIALIZED_SEQUENCES): return True return False
null
null
null
any field
codeqa
def find sequence fields doing specialization for f in fields if f seq if not doing specialization return Trueif str f type not in SPECIALIZED SEQUENCES return Truereturn False
null
null
null
null
Question: What uses a sequence ? Code: def find_sequence(fields, doing_specialization): for f in fields: if f.seq: if (not doing_specialization): return True if (str(f.type) not in _SPECIALIZED_SEQUENCES): return True return False
null
null
null
When does this seem ?
def text_clean(text): retval = text retval = retval.replace('\xe2\x80\x98', "'") retval = retval.replace('\xe2\x80\x99', "'") retval = retval.replace('\xe2', '') return retval
null
null
null
always
codeqa
def text clean text retval textretval retval replace '\xe 2 \x 80 \x 98 ' "'" retval retval replace '\xe 2 \x 80 \x 99 ' "'" retval retval replace '\xe 2 ' '' return retval
null
null
null
null
Question: When does this seem ? Code: def text_clean(text): retval = text retval = retval.replace('\xe2\x80\x98', "'") retval = retval.replace('\xe2\x80\x99', "'") retval = retval.replace('\xe2', '') return retval
null
null
null
What does the code remove ?
@error.context_aware def vg_remove(vg_name): error.context(("Removing volume '%s'" % vg_name), logging.info) if (not vg_check(vg_name)): raise error.TestError(("Volume group '%s' could not be found" % vg_name)) cmd = ('vgremove -f %s' % vg_name) result = utils.run(cmd) logging.info(result.stdout.rstrip())
null
null
null
a volume group
codeqa
@error context awaredef vg remove vg name error context " Removingvolume'%s'" % vg name logging info if not vg check vg name raise error Test Error " Volumegroup'%s'couldnotbefound" % vg name cmd 'vgremove-f%s' % vg name result utils run cmd logging info result stdout rstrip
null
null
null
null
Question: What does the code remove ? Code: @error.context_aware def vg_remove(vg_name): error.context(("Removing volume '%s'" % vg_name), logging.info) if (not vg_check(vg_name)): raise error.TestError(("Volume group '%s' could not be found" % vg_name)) cmd = ('vgremove -f %s' % vg_name) result = utils.run(cmd) logging.info(result.stdout.rstrip())
null
null
null
What does the code get ?
def _get_vm_ref_from_name(session, vm_name): vms = session._call_method(vim_util, 'get_objects', 'VirtualMachine', ['name']) return _get_object_from_results(session, vms, vm_name, _get_object_for_value)
null
null
null
reference to the vm with the name specified
codeqa
def get vm ref from name session vm name vms session call method vim util 'get objects' ' Virtual Machine' ['name'] return get object from results session vms vm name get object for value
null
null
null
null
Question: What does the code get ? Code: def _get_vm_ref_from_name(session, vm_name): vms = session._call_method(vim_util, 'get_objects', 'VirtualMachine', ['name']) return _get_object_from_results(session, vms, vm_name, _get_object_for_value)
null
null
null
When being pi used ?
def PiVersion(): with open('/proc/cpuinfo', 'r') as f: cpu_count = sum([1 for x in f.readlines() if x.startswith('processor')]) if (cpu_count == 1): return 'PiB' else: return 'Pi2'
null
null
null
currently
codeqa
def Pi Version with open '/proc/cpuinfo' 'r' as f cpu count sum [1 for x in f readlines if x startswith 'processor' ] if cpu count 1 return ' Pi B'else return ' Pi 2 '
null
null
null
null
Question: When being pi used ? Code: def PiVersion(): with open('/proc/cpuinfo', 'r') as f: cpu_count = sum([1 for x in f.readlines() if x.startswith('processor')]) if (cpu_count == 1): return 'PiB' else: return 'Pi2'
null
null
null
How do a socket bind ?
def bind_af_aware(sock, addr): if (HAS_UNIX_SOCKETS and (sock.family == socket.AF_UNIX)): support.unlink(addr) support.bind_unix_socket(sock, addr) else: sock.bind(addr)
null
null
null
according to its family
codeqa
def bind af aware sock addr if HAS UNIX SOCKETS and sock family socket AF UNIX support unlink addr support bind unix socket sock addr else sock bind addr
null
null
null
null
Question: How do a socket bind ? Code: def bind_af_aware(sock, addr): if (HAS_UNIX_SOCKETS and (sock.family == socket.AF_UNIX)): support.unlink(addr) support.bind_unix_socket(sock, addr) else: sock.bind(addr)
null
null
null
What compiles a * ?
def compileExe(file_name): cp = CompilerParameters() cp.GenerateExecutable = True cp.OutputAssembly = (file_name.split('.cs')[0] + '.exe') cp.GenerateInMemory = False cp.TreatWarningsAsErrors = False cp.IncludeDebugInformation = True cp.ReferencedAssemblies.Add('IronPython.dll') cr = PROVIDER.CompileAssemblyFromFile(cp, file_name)
null
null
null
helper function
codeqa
def compile Exe file name cp Compiler Parameters cp Generate Executable Truecp Output Assembly file name split ' cs' [0 ] + ' exe' cp Generate In Memory Falsecp Treat Warnings As Errors Falsecp Include Debug Information Truecp Referenced Assemblies Add ' Iron Python dll' cr PROVIDER Compile Assembly From File cp file name
null
null
null
null
Question: What compiles a * ? Code: def compileExe(file_name): cp = CompilerParameters() cp.GenerateExecutable = True cp.OutputAssembly = (file_name.split('.cs')[0] + '.exe') cp.GenerateInMemory = False cp.TreatWarningsAsErrors = False cp.IncludeDebugInformation = True cp.ReferencedAssemblies.Add('IronPython.dll') cr = PROVIDER.CompileAssemblyFromFile(cp, file_name)
null
null
null
What does helper function compile ?
def compileExe(file_name): cp = CompilerParameters() cp.GenerateExecutable = True cp.OutputAssembly = (file_name.split('.cs')[0] + '.exe') cp.GenerateInMemory = False cp.TreatWarningsAsErrors = False cp.IncludeDebugInformation = True cp.ReferencedAssemblies.Add('IronPython.dll') cr = PROVIDER.CompileAssemblyFromFile(cp, file_name)
null
null
null
a *
codeqa
def compile Exe file name cp Compiler Parameters cp Generate Executable Truecp Output Assembly file name split ' cs' [0 ] + ' exe' cp Generate In Memory Falsecp Treat Warnings As Errors Falsecp Include Debug Information Truecp Referenced Assemblies Add ' Iron Python dll' cr PROVIDER Compile Assembly From File cp file name
null
null
null
null
Question: What does helper function compile ? Code: def compileExe(file_name): cp = CompilerParameters() cp.GenerateExecutable = True cp.OutputAssembly = (file_name.split('.cs')[0] + '.exe') cp.GenerateInMemory = False cp.TreatWarningsAsErrors = False cp.IncludeDebugInformation = True cp.ReferencedAssemblies.Add('IronPython.dll') cr = PROVIDER.CompileAssemblyFromFile(cp, file_name)
null
null
null
Where do a provided pack exist ?
def check_pack_content_directory_exists(pack, content_type): packs_base_paths = get_packs_base_paths() for base_dir in packs_base_paths: pack_content_pack = os.path.join(base_dir, pack, content_type) if os.path.exists(pack_content_pack): return True return False
null
null
null
in one of the pack paths
codeqa
def check pack content directory exists pack content type packs base paths get packs base paths for base dir in packs base paths pack content pack os path join base dir pack content type if os path exists pack content pack return Truereturn False
null
null
null
null
Question: Where do a provided pack exist ? Code: def check_pack_content_directory_exists(pack, content_type): packs_base_paths = get_packs_base_paths() for base_dir in packs_base_paths: pack_content_pack = os.path.join(base_dir, pack, content_type) if os.path.exists(pack_content_pack): return True return False
null
null
null
What exists in one of the pack paths ?
def check_pack_content_directory_exists(pack, content_type): packs_base_paths = get_packs_base_paths() for base_dir in packs_base_paths: pack_content_pack = os.path.join(base_dir, pack, content_type) if os.path.exists(pack_content_pack): return True return False
null
null
null
a provided pack
codeqa
def check pack content directory exists pack content type packs base paths get packs base paths for base dir in packs base paths pack content pack os path join base dir pack content type if os path exists pack content pack return Truereturn False
null
null
null
null
Question: What exists in one of the pack paths ? Code: def check_pack_content_directory_exists(pack, content_type): packs_base_paths = get_packs_base_paths() for base_dir in packs_base_paths: pack_content_pack = os.path.join(base_dir, pack, content_type) if os.path.exists(pack_content_pack): return True return False
null
null
null
What does the code provide ?
def in6_and(a1, a2): return _in6_bitops(a1, a2, 1)
null
null
null
a bit to bit and of provided addresses
codeqa
def in 6 and a1 a2 return in 6 bitops a1 a2 1
null
null
null
null
Question: What does the code provide ? Code: def in6_and(a1, a2): return _in6_bitops(a1, a2, 1)
null
null
null
What does the code get ?
def getSettingsPath(subName=''): global settingsPath return getJoinedPath(settingsPath, subName)
null
null
null
the settings directory path
codeqa
def get Settings Path sub Name '' global settings Pathreturn get Joined Path settings Path sub Name
null
null
null
null
Question: What does the code get ? Code: def getSettingsPath(subName=''): global settingsPath return getJoinedPath(settingsPath, subName)
null
null
null
What does the code add ?
def _AddFilters(filters): _cpplint_state.AddFilters(filters)
null
null
null
more filter overrides
codeqa
def Add Filters filters cpplint state Add Filters filters
null
null
null
null
Question: What does the code add ? Code: def _AddFilters(filters): _cpplint_state.AddFilters(filters)
null
null
null
Where do a wildcard character appear ?
def wildcard_in_db(namespace): return (namespace.find('*') < namespace.find('.'))
null
null
null
in the database name
codeqa
def wildcard in db namespace return namespace find '*' < namespace find ' '
null
null
null
null
Question: Where do a wildcard character appear ? Code: def wildcard_in_db(namespace): return (namespace.find('*') < namespace.find('.'))
null
null
null
What appears in the database name ?
def wildcard_in_db(namespace): return (namespace.find('*') < namespace.find('.'))
null
null
null
a wildcard character
codeqa
def wildcard in db namespace return namespace find '*' < namespace find ' '
null
null
null
null
Question: What appears in the database name ? Code: def wildcard_in_db(namespace): return (namespace.find('*') < namespace.find('.'))
null
null
null
How does on formatted logging output turn ?
def enable_pretty_logging(options=None, logger=None): if (options is None): from tornado.options import options if (options.logging == 'none'): return if (logger is None): logger = logging.getLogger() logger.setLevel(getattr(logging, options.logging.upper())) if options.log_file_prefix: channel = logging.handlers.RotatingFileHandler(filename=options.log_file_prefix, maxBytes=options.log_file_max_size, backupCount=options.log_file_num_backups) channel.setFormatter(LogFormatter(color=False)) logger.addHandler(channel) if (options.log_to_stderr or ((options.log_to_stderr is None) and (not logger.handlers))): channel = logging.StreamHandler() channel.setFormatter(LogFormatter()) logger.addHandler(channel)
null
null
null
as configured
codeqa
def enable pretty logging options None logger None if options is None from tornado options import optionsif options logging 'none' returnif logger is None logger logging get Logger logger set Level getattr logging options logging upper if options log file prefix channel logging handlers Rotating File Handler filename options log file prefix max Bytes options log file max size backup Count options log file num backups channel set Formatter Log Formatter color False logger add Handler channel if options log to stderr or options log to stderr is None and not logger handlers channel logging Stream Handler channel set Formatter Log Formatter logger add Handler channel
null
null
null
null
Question: How does on formatted logging output turn ? Code: def enable_pretty_logging(options=None, logger=None): if (options is None): from tornado.options import options if (options.logging == 'none'): return if (logger is None): logger = logging.getLogger() logger.setLevel(getattr(logging, options.logging.upper())) if options.log_file_prefix: channel = logging.handlers.RotatingFileHandler(filename=options.log_file_prefix, maxBytes=options.log_file_max_size, backupCount=options.log_file_num_backups) channel.setFormatter(LogFormatter(color=False)) logger.addHandler(channel) if (options.log_to_stderr or ((options.log_to_stderr is None) and (not logger.handlers))): channel = logging.StreamHandler() channel.setFormatter(LogFormatter()) logger.addHandler(channel)
null
null
null
How does the module path return ?
def module_path(local_function): return os.path.abspath(inspect.getsourcefile(local_function))
null
null
null
without the use of _ _ file _ _
codeqa
def module path local function return os path abspath inspect getsourcefile local function
null
null
null
null
Question: How does the module path return ? Code: def module_path(local_function): return os.path.abspath(inspect.getsourcefile(local_function))
null
null
null
What do all items have ?
@pytest.mark.parametrize('i', range(len(ITEMS))) def test_no_userdata(objects, i): assert (objects.history.itemAt(i).userData() is None)
null
null
null
no user data
codeqa
@pytest mark parametrize 'i' range len ITEMS def test no userdata objects i assert objects history item At i user Data is None
null
null
null
null
Question: What do all items have ? Code: @pytest.mark.parametrize('i', range(len(ITEMS))) def test_no_userdata(objects, i): assert (objects.history.itemAt(i).userData() is None)
null
null
null
What does the code disconnect ?
def disconnect_entry_signals(): post_save.disconnect(sender=Entry, dispatch_uid=ENTRY_PS_PING_DIRECTORIES) post_save.disconnect(sender=Entry, dispatch_uid=ENTRY_PS_PING_EXTERNAL_URLS) post_save.disconnect(sender=Entry, dispatch_uid=ENTRY_PS_FLUSH_SIMILAR_CACHE) post_delete.disconnect(sender=Entry, dispatch_uid=ENTRY_PD_FLUSH_SIMILAR_CACHE)
null
null
null
all the signals on entry model
codeqa
def disconnect entry signals post save disconnect sender Entry dispatch uid ENTRY PS PING DIRECTORIES post save disconnect sender Entry dispatch uid ENTRY PS PING EXTERNAL URLS post save disconnect sender Entry dispatch uid ENTRY PS FLUSH SIMILAR CACHE post delete disconnect sender Entry dispatch uid ENTRY PD FLUSH SIMILAR CACHE
null
null
null
null
Question: What does the code disconnect ? Code: def disconnect_entry_signals(): post_save.disconnect(sender=Entry, dispatch_uid=ENTRY_PS_PING_DIRECTORIES) post_save.disconnect(sender=Entry, dispatch_uid=ENTRY_PS_PING_EXTERNAL_URLS) post_save.disconnect(sender=Entry, dispatch_uid=ENTRY_PS_FLUSH_SIMILAR_CACHE) post_delete.disconnect(sender=Entry, dispatch_uid=ENTRY_PD_FLUSH_SIMILAR_CACHE)
null
null
null
What moves to default group ?
def move_users(): group = Group.objects.get(name=u'Users') for user in User.objects.all(): user.groups.add(group)
null
null
null
users
codeqa
def move users group Group objects get name u' Users' for user in User objects all user groups add group
null
null
null
null
Question: What moves to default group ? Code: def move_users(): group = Group.objects.get(name=u'Users') for user in User.objects.all(): user.groups.add(group)
null
null
null
What does users move ?
def move_users(): group = Group.objects.get(name=u'Users') for user in User.objects.all(): user.groups.add(group)
null
null
null
to default group
codeqa
def move users group Group objects get name u' Users' for user in User objects all user groups add group
null
null
null
null
Question: What does users move ? Code: def move_users(): group = Group.objects.get(name=u'Users') for user in User.objects.all(): user.groups.add(group)
null
null
null
What needs tokens ?
def setup_dummy_social_apps(sender, **kwargs): from allauth.socialaccount.providers import registry from allauth.socialaccount.models import SocialApp from allauth.socialaccount.providers.oauth.provider import OAuthProvider from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider from django.contrib.sites.models import Site site = Site.objects.get_current() for provider in registry.get_list(): if (isinstance(provider, OAuth2Provider) or isinstance(provider, OAuthProvider)): try: SocialApp.objects.get(provider=provider.id, sites=site) except SocialApp.DoesNotExist: print ('Installing dummy application credentials for %s. Authentication via this provider will not work until you configure proper credentials via the Django admin (`SocialApp` models)' % provider.id) app = SocialApp.objects.create(provider=provider.id, secret='secret', client_id='client-id', name=('Dummy %s app' % provider.id)) app.sites.add(site)
null
null
null
allauth
codeqa
def setup dummy social apps sender **kwargs from allauth socialaccount providers import registryfrom allauth socialaccount models import Social Appfrom allauth socialaccount providers oauth provider import O Auth Providerfrom allauth socialaccount providers oauth 2 provider import O Auth 2 Providerfrom django contrib sites models import Sitesite Site objects get current for provider in registry get list if isinstance provider O Auth 2 Provider or isinstance provider O Auth Provider try Social App objects get provider provider id sites site except Social App Does Not Exist print ' Installingdummyapplicationcredentialsfor%s Authenticationviathisproviderwillnotworkuntilyouconfigurepropercredentialsviathe Djangoadmin ` Social App`models ' % provider id app Social App objects create provider provider id secret 'secret' client id 'client-id' name ' Dummy%sapp' % provider id app sites add site
null
null
null
null
Question: What needs tokens ? Code: def setup_dummy_social_apps(sender, **kwargs): from allauth.socialaccount.providers import registry from allauth.socialaccount.models import SocialApp from allauth.socialaccount.providers.oauth.provider import OAuthProvider from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider from django.contrib.sites.models import Site site = Site.objects.get_current() for provider in registry.get_list(): if (isinstance(provider, OAuth2Provider) or isinstance(provider, OAuthProvider)): try: SocialApp.objects.get(provider=provider.id, sites=site) except SocialApp.DoesNotExist: print ('Installing dummy application credentials for %s. Authentication via this provider will not work until you configure proper credentials via the Django admin (`SocialApp` models)' % provider.id) app = SocialApp.objects.create(provider=provider.id, secret='secret', client_id='client-id', name=('Dummy %s app' % provider.id)) app.sites.add(site)
null
null
null
What does the code save to disk ?
def save_state(): ArticleCache.do.flush_articles() NzbQueue.do.save() BPSMeter.do.save() rss.save() Rating.do.save() DirScanner.do.save() PostProcessor.do.save()
null
null
null
all internal bookkeeping
codeqa
def save state Article Cache do flush articles Nzb Queue do save BPS Meter do save rss save Rating do save Dir Scanner do save Post Processor do save
null
null
null
null
Question: What does the code save to disk ? Code: def save_state(): ArticleCache.do.flush_articles() NzbQueue.do.save() BPSMeter.do.save() rss.save() Rating.do.save() DirScanner.do.save() PostProcessor.do.save()
null
null
null
How do example restart ?
def reload(): return __csf_cmd('-r')
null
null
null
cli
codeqa
def reload return csf cmd '-r'
null
null
null
null
Question: How do example restart ? Code: def reload(): return __csf_cmd('-r')
null
null
null
What does the code create ?
def CreateClient(): client = gdata.docs.client.DocsClient(source=SampleConfig.APP_NAME) client.http_client.debug = SampleConfig.DEBUG try: gdata.sample_util.authorize_client(client, service=client.auth_service, source=client.source, scopes=client.auth_scopes) except gdata.client.BadAuthentication: exit('Invalid user credentials given.') except gdata.client.Error: exit('Login Error') return client
null
null
null
a documents list client
codeqa
def Create Client client gdata docs client Docs Client source Sample Config APP NAME client http client debug Sample Config DEBU Gtry gdata sample util authorize client client service client auth service source client source scopes client auth scopes except gdata client Bad Authentication exit ' Invalidusercredentialsgiven ' except gdata client Error exit ' Login Error' return client
null
null
null
null
Question: What does the code create ? Code: def CreateClient(): client = gdata.docs.client.DocsClient(source=SampleConfig.APP_NAME) client.http_client.debug = SampleConfig.DEBUG try: gdata.sample_util.authorize_client(client, service=client.auth_service, source=client.source, scopes=client.auth_scopes) except gdata.client.BadAuthentication: exit('Invalid user credentials given.') except gdata.client.Error: exit('Login Error') return client
null
null
null
What does the code create ?
@ownership_required def page_create(request, slug, template_name='groups/pages/page_form.html'): group = get_object_or_404(Group, slug=slug) form = GroupPageForm(initial={'group': group}) if (request.method == 'POST'): form = GroupPageForm(request.POST) if form.is_valid(): page = form.save(commit=False) page.group = group page.save() return redirect(request, page) return render(request, template_name, {'group': group, 'form': form})
null
null
null
a group page
codeqa
@ownership requireddef page create request slug template name 'groups/pages/page form html' group get object or 404 Group slug slug form Group Page Form initial {'group' group} if request method 'POST' form Group Page Form request POST if form is valid page form save commit False page group grouppage save return redirect request page return render request template name {'group' group 'form' form}
null
null
null
null
Question: What does the code create ? Code: @ownership_required def page_create(request, slug, template_name='groups/pages/page_form.html'): group = get_object_or_404(Group, slug=slug) form = GroupPageForm(initial={'group': group}) if (request.method == 'POST'): form = GroupPageForm(request.POST) if form.is_valid(): page = form.save(commit=False) page.group = group page.save() return redirect(request, page) return render(request, template_name, {'group': group, 'form': form})
null
null
null
In which direction does this walk ?
def removeNestedGroups(node): global numElemsRemoved num = 0 groupsToRemove = [] if (not ((node.nodeType == 1) and (node.nodeName == 'switch'))): for child in node.childNodes: if ((child.nodeName == 'g') and (child.namespaceURI == NS['SVG']) and (len(child.attributes) == 0)): for grandchild in child.childNodes: if ((grandchild.nodeType == 1) and (grandchild.namespaceURI == NS['SVG']) and (grandchild.nodeName in ['title', 'desc'])): break else: groupsToRemove.append(child) for g in groupsToRemove: while (g.childNodes.length > 0): g.parentNode.insertBefore(g.firstChild, g) g.parentNode.removeChild(g) numElemsRemoved += 1 num += 1 for child in node.childNodes: if (child.nodeType == 1): num += removeNestedGroups(child) return num
null
null
null
further and further
codeqa
def remove Nested Groups node global num Elems Removednum 0groups To Remove []if not node node Type 1 and node node Name 'switch' for child in node child Nodes if child node Name 'g' and child namespace URI NS['SVG'] and len child attributes 0 for grandchild in child child Nodes if grandchild node Type 1 and grandchild namespace URI NS['SVG'] and grandchild node Name in ['title' 'desc'] breakelse groups To Remove append child for g in groups To Remove while g child Nodes length > 0 g parent Node insert Before g first Child g g parent Node remove Child g num Elems Removed + 1num + 1for child in node child Nodes if child node Type 1 num + remove Nested Groups child return num
null
null
null
null
Question: In which direction does this walk ? Code: def removeNestedGroups(node): global numElemsRemoved num = 0 groupsToRemove = [] if (not ((node.nodeType == 1) and (node.nodeName == 'switch'))): for child in node.childNodes: if ((child.nodeName == 'g') and (child.namespaceURI == NS['SVG']) and (len(child.attributes) == 0)): for grandchild in child.childNodes: if ((grandchild.nodeType == 1) and (grandchild.namespaceURI == NS['SVG']) and (grandchild.nodeName in ['title', 'desc'])): break else: groupsToRemove.append(child) for g in groupsToRemove: while (g.childNodes.length > 0): g.parentNode.insertBefore(g.firstChild, g) g.parentNode.removeChild(g) numElemsRemoved += 1 num += 1 for child in node.childNodes: if (child.nodeType == 1): num += removeNestedGroups(child) return num
null
null
null
What do decorator specify ?
def flake8extn(func): func.version = PLUGIN_VERSION func.name = PLUGIN_NAME return func
null
null
null
flake8 extension details
codeqa
def flake 8 extn func func version PLUGIN VERSIO Nfunc name PLUGIN NAM Ereturn func
null
null
null
null
Question: What do decorator specify ? Code: def flake8extn(func): func.version = PLUGIN_VERSION func.name = PLUGIN_NAME return func
null
null
null
What requires that a user be logged in to access a handler ?
def login_required(handler_method): def check_login(self, *args): if (self.request.method != 'GET'): raise webapp.Error('The check_login decorator can only be used for GET requests') user = users.get_current_user() if (not user): self.redirect(users.create_login_url(self.request.uri)) return else: handler_method(self, *args) return check_login
null
null
null
a decorator
codeqa
def login required handler method def check login self *args if self request method 'GET' raise webapp Error ' Thecheck logindecoratorcanonlybeusedfor GE Trequests' user users get current user if not user self redirect users create login url self request uri returnelse handler method self *args return check login
null
null
null
null
Question: What requires that a user be logged in to access a handler ? Code: def login_required(handler_method): def check_login(self, *args): if (self.request.method != 'GET'): raise webapp.Error('The check_login decorator can only be used for GET requests') user = users.get_current_user() if (not user): self.redirect(users.create_login_url(self.request.uri)) return else: handler_method(self, *args) return check_login
null
null
null
In which direction be a user logged to access a handler ?
def login_required(handler_method): def check_login(self, *args): if (self.request.method != 'GET'): raise webapp.Error('The check_login decorator can only be used for GET requests') user = users.get_current_user() if (not user): self.redirect(users.create_login_url(self.request.uri)) return else: handler_method(self, *args) return check_login
null
null
null
in
codeqa
def login required handler method def check login self *args if self request method 'GET' raise webapp Error ' Thecheck logindecoratorcanonlybeusedfor GE Trequests' user users get current user if not user self redirect users create login url self request uri returnelse handler method self *args return check login
null
null
null
null
Question: In which direction be a user logged to access a handler ? Code: def login_required(handler_method): def check_login(self, *args): if (self.request.method != 'GET'): raise webapp.Error('The check_login decorator can only be used for GET requests') user = users.get_current_user() if (not user): self.redirect(users.create_login_url(self.request.uri)) return else: handler_method(self, *args) return check_login
null
null
null
For what purpose be a user logged in ?
def login_required(handler_method): def check_login(self, *args): if (self.request.method != 'GET'): raise webapp.Error('The check_login decorator can only be used for GET requests') user = users.get_current_user() if (not user): self.redirect(users.create_login_url(self.request.uri)) return else: handler_method(self, *args) return check_login
null
null
null
to access a handler
codeqa
def login required handler method def check login self *args if self request method 'GET' raise webapp Error ' Thecheck logindecoratorcanonlybeusedfor GE Trequests' user users get current user if not user self redirect users create login url self request uri returnelse handler method self *args return check login
null
null
null
null
Question: For what purpose be a user logged in ? Code: def login_required(handler_method): def check_login(self, *args): if (self.request.method != 'GET'): raise webapp.Error('The check_login decorator can only be used for GET requests') user = users.get_current_user() if (not user): self.redirect(users.create_login_url(self.request.uri)) return else: handler_method(self, *args) return check_login
null
null
null
What did a user access ?
def login_required(handler_method): def check_login(self, *args): if (self.request.method != 'GET'): raise webapp.Error('The check_login decorator can only be used for GET requests') user = users.get_current_user() if (not user): self.redirect(users.create_login_url(self.request.uri)) return else: handler_method(self, *args) return check_login
null
null
null
a handler
codeqa
def login required handler method def check login self *args if self request method 'GET' raise webapp Error ' Thecheck logindecoratorcanonlybeusedfor GE Trequests' user users get current user if not user self redirect users create login url self request uri returnelse handler method self *args return check login
null
null
null
null
Question: What did a user access ? Code: def login_required(handler_method): def check_login(self, *args): if (self.request.method != 'GET'): raise webapp.Error('The check_login decorator can only be used for GET requests') user = users.get_current_user() if (not user): self.redirect(users.create_login_url(self.request.uri)) return else: handler_method(self, *args) return check_login
null
null
null
What does the code return ?
def get_git_branch_name(ref_name): branch_ref_prefix = u'refs/heads/' if ref_name.startswith(branch_ref_prefix): return ref_name[len(branch_ref_prefix):]
null
null
null
the branch name corresponding to the specified ref name
codeqa
def get git branch name ref name branch ref prefix u'refs/heads/'if ref name startswith branch ref prefix return ref name[len branch ref prefix ]
null
null
null
null
Question: What does the code return ? Code: def get_git_branch_name(ref_name): branch_ref_prefix = u'refs/heads/' if ref_name.startswith(branch_ref_prefix): return ref_name[len(branch_ref_prefix):]
null
null
null
What runs what ?
def status(cwd, opts=None, user=None): def _status(cwd): cmd = ['hg', 'status'] if opts: for opt in opts.split(): cmd.append('{0}'.format(opt)) out = __salt__['cmd.run_stdout'](cmd, cwd=cwd, runas=user, python_shell=False) types = {'M': 'modified', 'A': 'added', 'R': 'removed', 'C': 'clean', '!': 'missing', '?': 'not tracked', 'I': 'ignored', ' ': 'origin of the previous file'} ret = {} for line in out.splitlines(): (t, f) = (types[line[0]], line[2:]) if (t not in ret): ret[t] = [] ret[t].append(f) return ret if salt.utils.is_iter(cwd): return dict(((cwd, _status(cwd)) for cwd in cwd)) else: return _status(cwd)
null
null
null
the minion
codeqa
def status cwd opts None user None def status cwd cmd ['hg' 'status']if opts for opt in opts split cmd append '{ 0 }' format opt out salt ['cmd run stdout'] cmd cwd cwd runas user python shell False types {'M' 'modified' 'A' 'added' 'R' 'removed' 'C' 'clean' ' ' 'missing' '?' 'nottracked' 'I' 'ignored' '' 'originofthepreviousfile'}ret {}for line in out splitlines t f types[line[ 0 ]] line[ 2 ] if t not in ret ret[t] []ret[t] append f return retif salt utils is iter cwd return dict cwd status cwd for cwd in cwd else return status cwd
null
null
null
null
Question: What runs what ? Code: def status(cwd, opts=None, user=None): def _status(cwd): cmd = ['hg', 'status'] if opts: for opt in opts.split(): cmd.append('{0}'.format(opt)) out = __salt__['cmd.run_stdout'](cmd, cwd=cwd, runas=user, python_shell=False) types = {'M': 'modified', 'A': 'added', 'R': 'removed', 'C': 'clean', '!': 'missing', '?': 'not tracked', 'I': 'ignored', ' ': 'origin of the previous file'} ret = {} for line in out.splitlines(): (t, f) = (types[line[0]], line[2:]) if (t not in ret): ret[t] = [] ret[t].append(f) return ret if salt.utils.is_iter(cwd): return dict(((cwd, _status(cwd)) for cwd in cwd)) else: return _status(cwd)
null
null
null
What does the minion run ?
def status(cwd, opts=None, user=None): def _status(cwd): cmd = ['hg', 'status'] if opts: for opt in opts.split(): cmd.append('{0}'.format(opt)) out = __salt__['cmd.run_stdout'](cmd, cwd=cwd, runas=user, python_shell=False) types = {'M': 'modified', 'A': 'added', 'R': 'removed', 'C': 'clean', '!': 'missing', '?': 'not tracked', 'I': 'ignored', ' ': 'origin of the previous file'} ret = {} for line in out.splitlines(): (t, f) = (types[line[0]], line[2:]) if (t not in ret): ret[t] = [] ret[t].append(f) return ret if salt.utils.is_iter(cwd): return dict(((cwd, _status(cwd)) for cwd in cwd)) else: return _status(cwd)
null
null
null
what
codeqa
def status cwd opts None user None def status cwd cmd ['hg' 'status']if opts for opt in opts split cmd append '{ 0 }' format opt out salt ['cmd run stdout'] cmd cwd cwd runas user python shell False types {'M' 'modified' 'A' 'added' 'R' 'removed' 'C' 'clean' ' ' 'missing' '?' 'nottracked' 'I' 'ignored' '' 'originofthepreviousfile'}ret {}for line in out splitlines t f types[line[ 0 ]] line[ 2 ] if t not in ret ret[t] []ret[t] append f return retif salt utils is iter cwd return dict cwd status cwd for cwd in cwd else return status cwd
null
null
null
null
Question: What does the minion run ? Code: def status(cwd, opts=None, user=None): def _status(cwd): cmd = ['hg', 'status'] if opts: for opt in opts.split(): cmd.append('{0}'.format(opt)) out = __salt__['cmd.run_stdout'](cmd, cwd=cwd, runas=user, python_shell=False) types = {'M': 'modified', 'A': 'added', 'R': 'removed', 'C': 'clean', '!': 'missing', '?': 'not tracked', 'I': 'ignored', ' ': 'origin of the previous file'} ret = {} for line in out.splitlines(): (t, f) = (types[line[0]], line[2:]) if (t not in ret): ret[t] = [] ret[t].append(f) return ret if salt.utils.is_iter(cwd): return dict(((cwd, _status(cwd)) for cwd in cwd)) else: return _status(cwd)
null
null
null
What does the code run ?
def web_annotation(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': 'WEB_ANNOTATION', 'maxResults': 10}]}]}) response = service_request.execute() print json.dumps(response, indent=2)
null
null
null
a web annotation request on the image
codeqa
def web annotation 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' 'WEB ANNOTATION' 'max Results' 10 }]}]} response service request execute print json dumps response indent 2
null
null
null
null
Question: What does the code run ? Code: def web_annotation(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': 'WEB_ANNOTATION', 'maxResults': 10}]}]}) response = service_request.execute() print json.dumps(response, indent=2)
null
null
null
What do helper produce ?
def define_plugin_entry(name, module_name): if isinstance(name, tuple): (entry, name) = name else: entry = name return ('%s = %s:%s' % (entry, module_name, name))
null
null
null
lines suitable for setup
codeqa
def define plugin entry name module name if isinstance name tuple entry name nameelse entry namereturn '%s %s %s' % entry module name name
null
null
null
null
Question: What do helper produce ? Code: def define_plugin_entry(name, module_name): if isinstance(name, tuple): (entry, name) = name else: entry = name return ('%s = %s:%s' % (entry, module_name, name))
null
null
null
What produces lines suitable for setup ?
def define_plugin_entry(name, module_name): if isinstance(name, tuple): (entry, name) = name else: entry = name return ('%s = %s:%s' % (entry, module_name, name))
null
null
null
helper
codeqa
def define plugin entry name module name if isinstance name tuple entry name nameelse entry namereturn '%s %s %s' % entry module name name
null
null
null
null
Question: What produces lines suitable for setup ? Code: def define_plugin_entry(name, module_name): if isinstance(name, tuple): (entry, name) = name else: entry = name return ('%s = %s:%s' % (entry, module_name, name))
null
null
null
How did components connect ?
@not_implemented_for('undirected') def number_strongly_connected_components(G): return len(list(strongly_connected_components(G)))
null
null
null
strongly
codeqa
@not implemented for 'undirected' def number strongly connected components G return len list strongly connected components G
null
null
null
null
Question: How did components connect ? Code: @not_implemented_for('undirected') def number_strongly_connected_components(G): return len(list(strongly_connected_components(G)))
null
null
null
What is representing the storage bytes limit ?
def ParseTotalStorageLimit(limit): limit = limit.strip() if (not limit): raise MalformedQueueConfiguration('Total Storage Limit must not be empty.') try: if (limit[(-1)] in BYTE_SUFFIXES): number = float(limit[0:(-1)]) for c in BYTE_SUFFIXES: if (limit[(-1)] != c): number = (number * 1024) else: return int(number) else: return int(limit) except ValueError: raise MalformedQueueConfiguration(('Total Storage Limit "%s" is invalid.' % limit))
null
null
null
a string
codeqa
def Parse Total Storage Limit limit limit limit strip if not limit raise Malformed Queue Configuration ' Total Storage Limitmustnotbeempty ' try if limit[ -1 ] in BYTE SUFFIXES number float limit[ 0 -1 ] for c in BYTE SUFFIXES if limit[ -1 ] c number number * 1024 else return int number else return int limit except Value Error raise Malformed Queue Configuration ' Total Storage Limit"%s"isinvalid ' % limit
null
null
null
null
Question: What is representing the storage bytes limit ? Code: def ParseTotalStorageLimit(limit): limit = limit.strip() if (not limit): raise MalformedQueueConfiguration('Total Storage Limit must not be empty.') try: if (limit[(-1)] in BYTE_SUFFIXES): number = float(limit[0:(-1)]) for c in BYTE_SUFFIXES: if (limit[(-1)] != c): number = (number * 1024) else: return int(number) else: return int(limit) except ValueError: raise MalformedQueueConfiguration(('Total Storage Limit "%s" is invalid.' % limit))
null
null
null
What do a string represent ?
def ParseTotalStorageLimit(limit): limit = limit.strip() if (not limit): raise MalformedQueueConfiguration('Total Storage Limit must not be empty.') try: if (limit[(-1)] in BYTE_SUFFIXES): number = float(limit[0:(-1)]) for c in BYTE_SUFFIXES: if (limit[(-1)] != c): number = (number * 1024) else: return int(number) else: return int(limit) except ValueError: raise MalformedQueueConfiguration(('Total Storage Limit "%s" is invalid.' % limit))
null
null
null
the storage bytes limit
codeqa
def Parse Total Storage Limit limit limit limit strip if not limit raise Malformed Queue Configuration ' Total Storage Limitmustnotbeempty ' try if limit[ -1 ] in BYTE SUFFIXES number float limit[ 0 -1 ] for c in BYTE SUFFIXES if limit[ -1 ] c number number * 1024 else return int number else return int limit except Value Error raise Malformed Queue Configuration ' Total Storage Limit"%s"isinvalid ' % limit
null
null
null
null
Question: What do a string represent ? Code: def ParseTotalStorageLimit(limit): limit = limit.strip() if (not limit): raise MalformedQueueConfiguration('Total Storage Limit must not be empty.') try: if (limit[(-1)] in BYTE_SUFFIXES): number = float(limit[0:(-1)]) for c in BYTE_SUFFIXES: if (limit[(-1)] != c): number = (number * 1024) else: return int(number) else: return int(limit) except ValueError: raise MalformedQueueConfiguration(('Total Storage Limit "%s" is invalid.' % limit))
null
null
null
What does this decode ?
def decode_cookie(cookie): try: (payload, digest) = cookie.rsplit(u'|', 1) if hasattr(digest, 'decode'): digest = digest.decode('ascii') except ValueError: return if safe_str_cmp(_cookie_digest(payload), digest): return payload
null
null
null
a cookie given by encode_cookie
codeqa
def decode cookie cookie try payload digest cookie rsplit u' ' 1 if hasattr digest 'decode' digest digest decode 'ascii' except Value Error returnif safe str cmp cookie digest payload digest return payload
null
null
null
null
Question: What does this decode ? Code: def decode_cookie(cookie): try: (payload, digest) = cookie.rsplit(u'|', 1) if hasattr(digest, 'decode'): digest = digest.decode('ascii') except ValueError: return if safe_str_cmp(_cookie_digest(payload), digest): return payload
null
null
null
What decodes a cookie given by encode_cookie ?
def decode_cookie(cookie): try: (payload, digest) = cookie.rsplit(u'|', 1) if hasattr(digest, 'decode'): digest = digest.decode('ascii') except ValueError: return if safe_str_cmp(_cookie_digest(payload), digest): return payload
null
null
null
this
codeqa
def decode cookie cookie try payload digest cookie rsplit u' ' 1 if hasattr digest 'decode' digest digest decode 'ascii' except Value Error returnif safe str cmp cookie digest payload digest return payload
null
null
null
null
Question: What decodes a cookie given by encode_cookie ? Code: def decode_cookie(cookie): try: (payload, digest) = cookie.rsplit(u'|', 1) if hasattr(digest, 'decode'): digest = digest.decode('ascii') except ValueError: return if safe_str_cmp(_cookie_digest(payload), digest): return payload
null
null
null
How would all bears be found otherwise ?
@pytest.fixture def disable_bears(mocker): mocker.patch.object(coalib.collecting.Collectors, '_import_bears', autospec=True, return_value=[])
null
null
null
with collect_bears
codeqa
@pytest fixturedef disable bears mocker mocker patch object coalib collecting Collectors ' import bears' autospec True return value []
null
null
null
null
Question: How would all bears be found otherwise ? Code: @pytest.fixture def disable_bears(mocker): mocker.patch.object(coalib.collecting.Collectors, '_import_bears', autospec=True, return_value=[])
null
null
null
What does the code get ?
def getNewRepository(): return SkeinlayerRepository()
null
null
null
the repository constructor
codeqa
def get New Repository return Skeinlayer Repository
null
null
null
null
Question: What does the code get ? Code: def getNewRepository(): return SkeinlayerRepository()
null
null
null
What does the code convert ?
def _get_suggested_filename(path): filename = os.path.basename(path) filename = re.sub('\\([0-9]+\\)$', '', filename) filename = urllib.parse.unquote(filename) filename = os.path.basename(filename) return filename
null
null
null
a path we got from chromium to a suggested filename
codeqa
def get suggested filename path filename os path basename path filename re sub '\\ [0 - 9 ]+\\ $' '' filename filename urllib parse unquote filename filename os path basename filename return filename
null
null
null
null
Question: What does the code convert ? Code: def _get_suggested_filename(path): filename = os.path.basename(path) filename = re.sub('\\([0-9]+\\)$', '', filename) filename = urllib.parse.unquote(filename) filename = os.path.basename(filename) return filename
null
null
null
What is containing the models for the given app_label ?
def get_app(app_label, emptyOK=False): get_apps() for app_name in settings.INSTALLED_APPS: if (app_label == app_name.split('.')[(-1)]): mod = load_app(app_name) if (mod is None): if emptyOK: return None else: return mod raise ImproperlyConfigured, ('App with label %s could not be found' % app_label)
null
null
null
the module
codeqa
def get app app label empty OK False get apps for app name in settings INSTALLED APPS if app label app name split ' ' [ -1 ] mod load app app name if mod is None if empty OK return Noneelse return modraise Improperly Configured ' Appwithlabel%scouldnotbefound' % app label
null
null
null
null
Question: What is containing the models for the given app_label ? Code: def get_app(app_label, emptyOK=False): get_apps() for app_name in settings.INSTALLED_APPS: if (app_label == app_name.split('.')[(-1)]): mod = load_app(app_name) if (mod is None): if emptyOK: return None else: return mod raise ImproperlyConfigured, ('App with label %s could not be found' % app_label)
null
null
null
What did you have ?
def has_request_context(): return (_request_ctx_stack.top is not None)
null
null
null
code that wants to test if a request context is there or not
codeqa
def has request context return request ctx stack top is not None
null
null
null
null
Question: What did you have ? Code: def has_request_context(): return (_request_ctx_stack.top is not None)
null
null
null
What wants to test if a request context is there or not ?
def has_request_context(): return (_request_ctx_stack.top is not None)
null
null
null
code
codeqa
def has request context return request ctx stack top is not None
null
null
null
null
Question: What wants to test if a request context is there or not ? Code: def has_request_context(): return (_request_ctx_stack.top is not None)
null
null
null
What does code want ?
def has_request_context(): return (_request_ctx_stack.top is not None)
null
null
null
to test if a request context is there or not
codeqa
def has request context return request ctx stack top is not None
null
null
null
null
Question: What does code want ? Code: def has_request_context(): return (_request_ctx_stack.top is not None)
null
null
null
What did the code set ?
def _auth(profile=None): if profile: credentials = __salt__['config.option'](profile) user = credentials['keystone.user'] password = credentials['keystone.password'] tenant = credentials['keystone.tenant'] auth_url = credentials['keystone.auth_url'] region_name = credentials.get('keystone.region_name', None) service_type = credentials['keystone.service_type'] else: user = __salt__['config.option']('keystone.user') password = __salt__['config.option']('keystone.password') tenant = __salt__['config.option']('keystone.tenant') auth_url = __salt__['config.option']('keystone.auth_url') region_name = __salt__['config.option']('keystone.region_name') service_type = __salt__['config.option']('keystone.service_type') kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'auth_url': auth_url, 'region_name': region_name, 'service_type': service_type} return suoneu.SaltNeutron(**kwargs)
null
null
null
neutron credentials
codeqa
def auth profile None if profile credentials salt ['config option'] profile user credentials['keystone user']password credentials['keystone password']tenant credentials['keystone tenant']auth url credentials['keystone auth url']region name credentials get 'keystone region name' None service type credentials['keystone service type']else user salt ['config option'] 'keystone user' password salt ['config option'] 'keystone password' tenant salt ['config option'] 'keystone tenant' auth url salt ['config option'] 'keystone auth url' region name salt ['config option'] 'keystone region name' service type salt ['config option'] 'keystone service type' kwargs {'username' user 'password' password 'tenant name' tenant 'auth url' auth url 'region name' region name 'service type' service type}return suoneu Salt Neutron **kwargs
null
null
null
null
Question: What did the code set ? Code: def _auth(profile=None): if profile: credentials = __salt__['config.option'](profile) user = credentials['keystone.user'] password = credentials['keystone.password'] tenant = credentials['keystone.tenant'] auth_url = credentials['keystone.auth_url'] region_name = credentials.get('keystone.region_name', None) service_type = credentials['keystone.service_type'] else: user = __salt__['config.option']('keystone.user') password = __salt__['config.option']('keystone.password') tenant = __salt__['config.option']('keystone.tenant') auth_url = __salt__['config.option']('keystone.auth_url') region_name = __salt__['config.option']('keystone.region_name') service_type = __salt__['config.option']('keystone.service_type') kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'auth_url': auth_url, 'region_name': region_name, 'service_type': service_type} return suoneu.SaltNeutron(**kwargs)