labNo
float64
1
10
taskNo
float64
0
4
questioner
stringclasses
2 values
question
stringlengths
9
201
code
stringlengths
18
30.3k
startLine
float64
0
192
endLine
float64
0
196
questionType
stringclasses
4 values
answer
stringlengths
2
905
src
stringclasses
3 values
code_processed
stringlengths
12
28.3k
id
stringlengths
2
5
raw_code
stringlengths
20
30.3k
raw_comment
stringlengths
10
242
comment
stringlengths
9
207
q_code
stringlengths
66
30.3k
null
null
null
What does the code get ?
def classname(object, modname): name = object.__name__ if (object.__module__ != modname): name = ((object.__module__ + '.') + name) return name
null
null
null
a class name
codeqa
def classname object modname name object name if object module modname name object module + ' ' + name return name
null
null
null
null
Question: What does the code get ? Code: def classname(object, modname): name = object.__name__ if (object.__module__ != modname): name = ((object.__module__ + '.') + name) return name
null
null
null
What does the code reduce ?
def minimalBases(classes): if (not __python3): classes = [c for c in classes if (c is not ClassType)] candidates = [] for m in classes: for n in classes: if (issubclass(n, m) and (m is not n)): break else: if (m in candidates): candidates.remove(m) candidates.append(m) return candidates
null
null
null
a list of base classes
codeqa
def minimal Bases classes if not python 3 classes [c for c in classes if c is not Class Type ]candidates []for m in classes for n in classes if issubclass n m and m is not n breakelse if m in candidates candidates remove m candidates append m return candidates
null
null
null
null
Question: What does the code reduce ? Code: def minimalBases(classes): if (not __python3): classes = [c for c in classes if (c is not ClassType)] candidates = [] for m in classes: for n in classes: if (issubclass(n, m) and (m is not n)): break else: if (m in candidates): candidates.remove(m) candidates.append(m) return candidates
null
null
null
What is ignoring further modules which would cause more collection errors ?
def test_exit_on_collection_with_maxfail_smaller_than_n_errors(testdir): testdir.makepyfile(**COLLECTION_ERROR_PY_FILES) res = testdir.runpytest('--maxfail=1') assert (res.ret == 2) res.stdout.fnmatch_lines(['*ERROR collecting test_02_import_error.py*', '*No module named *asdfa*', '*Interrupted: stopping after 1 failures*']) assert ('test_03' not in res.stdout.str())
null
null
null
maxfail errors
codeqa
def test exit on collection with maxfail smaller than n errors testdir testdir makepyfile **COLLECTION ERROR PY FILES res testdir runpytest '--maxfail 1' assert res ret 2 res stdout fnmatch lines ['*ERRO Rcollectingtest 02 import error py*' '* Nomodulenamed*asdfa*' '* Interrupted stoppingafter 1 failures*'] assert 'test 03 ' not in res stdout str
null
null
null
null
Question: What is ignoring further modules which would cause more collection errors ? Code: def test_exit_on_collection_with_maxfail_smaller_than_n_errors(testdir): testdir.makepyfile(**COLLECTION_ERROR_PY_FILES) res = testdir.runpytest('--maxfail=1') assert (res.ret == 2) res.stdout.fnmatch_lines(['*ERROR collecting test_02_import_error.py*', '*No module named *asdfa*', '*Interrupted: stopping after 1 failures*']) assert ('test_03' not in res.stdout.str())
null
null
null
What would further modules cause ?
def test_exit_on_collection_with_maxfail_smaller_than_n_errors(testdir): testdir.makepyfile(**COLLECTION_ERROR_PY_FILES) res = testdir.runpytest('--maxfail=1') assert (res.ret == 2) res.stdout.fnmatch_lines(['*ERROR collecting test_02_import_error.py*', '*No module named *asdfa*', '*Interrupted: stopping after 1 failures*']) assert ('test_03' not in res.stdout.str())
null
null
null
more collection errors
codeqa
def test exit on collection with maxfail smaller than n errors testdir testdir makepyfile **COLLECTION ERROR PY FILES res testdir runpytest '--maxfail 1' assert res ret 2 res stdout fnmatch lines ['*ERRO Rcollectingtest 02 import error py*' '* Nomodulenamed*asdfa*' '* Interrupted stoppingafter 1 failures*'] assert 'test 03 ' not in res stdout str
null
null
null
null
Question: What would further modules cause ? Code: def test_exit_on_collection_with_maxfail_smaller_than_n_errors(testdir): testdir.makepyfile(**COLLECTION_ERROR_PY_FILES) res = testdir.runpytest('--maxfail=1') assert (res.ret == 2) res.stdout.fnmatch_lines(['*ERROR collecting test_02_import_error.py*', '*No module named *asdfa*', '*Interrupted: stopping after 1 failures*']) assert ('test_03' not in res.stdout.str())
null
null
null
What would cause more collection errors ?
def test_exit_on_collection_with_maxfail_smaller_than_n_errors(testdir): testdir.makepyfile(**COLLECTION_ERROR_PY_FILES) res = testdir.runpytest('--maxfail=1') assert (res.ret == 2) res.stdout.fnmatch_lines(['*ERROR collecting test_02_import_error.py*', '*No module named *asdfa*', '*Interrupted: stopping after 1 failures*']) assert ('test_03' not in res.stdout.str())
null
null
null
further modules
codeqa
def test exit on collection with maxfail smaller than n errors testdir testdir makepyfile **COLLECTION ERROR PY FILES res testdir runpytest '--maxfail 1' assert res ret 2 res stdout fnmatch lines ['*ERRO Rcollectingtest 02 import error py*' '* Nomodulenamed*asdfa*' '* Interrupted stoppingafter 1 failures*'] assert 'test 03 ' not in res stdout str
null
null
null
null
Question: What would cause more collection errors ? Code: def test_exit_on_collection_with_maxfail_smaller_than_n_errors(testdir): testdir.makepyfile(**COLLECTION_ERROR_PY_FILES) res = testdir.runpytest('--maxfail=1') assert (res.ret == 2) res.stdout.fnmatch_lines(['*ERROR collecting test_02_import_error.py*', '*No module named *asdfa*', '*Interrupted: stopping after 1 failures*']) assert ('test_03' not in res.stdout.str())
null
null
null
What does the code remove from the locale role ?
@login_required @require_http_methods(['GET', 'POST']) def remove_from_locale(request, locale_code, user_id, role): locale = get_object_or_404(Locale, locale=locale_code) user = get_object_or_404(User, id=user_id) if (not _user_can_edit(request.user, locale)): raise PermissionDenied if (request.method == 'POST'): getattr(locale, ROLE_ATTRS[role]).remove(user) msg = _('{user} removed from successfully!').format(user=user.username) messages.add_message(request, messages.SUCCESS, msg) return HttpResponseRedirect(locale.get_absolute_url()) return render(request, 'wiki/confirm_remove_from_locale.html', {'locale': locale, 'leader': user, 'role': role})
null
null
null
a user
codeqa
@login required@require http methods ['GET' 'POST'] def remove from locale request locale code user id role locale get object or 404 Locale locale locale code user get object or 404 User id user id if not user can edit request user locale raise Permission Deniedif request method 'POST' getattr locale ROLE ATTRS[role] remove user msg '{user}removedfromsuccessfully ' format user user username messages add message request messages SUCCESS msg return Http Response Redirect locale get absolute url return render request 'wiki/confirm remove from locale html' {'locale' locale 'leader' user 'role' role}
null
null
null
null
Question: What does the code remove from the locale role ? Code: @login_required @require_http_methods(['GET', 'POST']) def remove_from_locale(request, locale_code, user_id, role): locale = get_object_or_404(Locale, locale=locale_code) user = get_object_or_404(User, id=user_id) if (not _user_can_edit(request.user, locale)): raise PermissionDenied if (request.method == 'POST'): getattr(locale, ROLE_ATTRS[role]).remove(user) msg = _('{user} removed from successfully!').format(user=user.username) messages.add_message(request, messages.SUCCESS, msg) return HttpResponseRedirect(locale.get_absolute_url()) return render(request, 'wiki/confirm_remove_from_locale.html', {'locale': locale, 'leader': user, 'role': role})
null
null
null
What did the code stub ?
def get_course_enrollment_info(course_id, include_expired=False): return _get_fake_course_info(course_id, include_expired)
null
null
null
enrollment data request
codeqa
def get course enrollment info course id include expired False return get fake course info course id include expired
null
null
null
null
Question: What did the code stub ? Code: def get_course_enrollment_info(course_id, include_expired=False): return _get_fake_course_info(course_id, include_expired)
null
null
null
What determines from create_flat_names output ?
def _create_shape(flat_names): try: (_, shape_str) = flat_names[(-1)].rsplit('__', 1) except ValueError: return () return tuple(((int(i) + 1) for i in shape_str.split('_')))
null
null
null
shape
codeqa
def create shape flat names try shape str flat names[ -1 ] rsplit ' ' 1 except Value Error return return tuple int i + 1 for i in shape str split ' '
null
null
null
null
Question: What determines from create_flat_names output ? Code: def _create_shape(flat_names): try: (_, shape_str) = flat_names[(-1)].rsplit('__', 1) except ValueError: return () return tuple(((int(i) + 1) for i in shape_str.split('_')))
null
null
null
Where do shape determine ?
def _create_shape(flat_names): try: (_, shape_str) = flat_names[(-1)].rsplit('__', 1) except ValueError: return () return tuple(((int(i) + 1) for i in shape_str.split('_')))
null
null
null
from create_flat_names output
codeqa
def create shape flat names try shape str flat names[ -1 ] rsplit ' ' 1 except Value Error return return tuple int i + 1 for i in shape str split ' '
null
null
null
null
Question: Where do shape determine ? Code: def _create_shape(flat_names): try: (_, shape_str) = flat_names[(-1)].rsplit('__', 1) except ValueError: return () return tuple(((int(i) + 1) for i in shape_str.split('_')))
null
null
null
When do email send ?
def send_email_after_import(email, result): if ('__error' in result): send_email(email, action=EVENT_IMPORT_FAIL, subject=MAILS[EVENT_IMPORT_FAIL]['subject'], html=MAILS[EVENT_IMPORT_FAIL]['message'].format(error_text=result['result']['message'])) else: send_email(email, action=EVENT_IMPORTED, subject=MAILS[EVENT_IMPORTED]['subject'].format(event_name=result['name']), html=MAILS[EVENT_IMPORTED]['message'].format(event_url=(request.url_root.strip('/') + ('/events/%d' % result['id']))))
null
null
null
after event import
codeqa
def send email after import email result if ' error' in result send email email action EVENT IMPORT FAIL subject MAILS[EVENT IMPORT FAIL]['subject'] html MAILS[EVENT IMPORT FAIL]['message'] format error text result['result']['message'] else send email email action EVENT IMPORTED subject MAILS[EVENT IMPORTED]['subject'] format event name result['name'] html MAILS[EVENT IMPORTED]['message'] format event url request url root strip '/' + '/events/%d' % result['id']
null
null
null
null
Question: When do email send ? Code: def send_email_after_import(email, result): if ('__error' in result): send_email(email, action=EVENT_IMPORT_FAIL, subject=MAILS[EVENT_IMPORT_FAIL]['subject'], html=MAILS[EVENT_IMPORT_FAIL]['message'].format(error_text=result['result']['message'])) else: send_email(email, action=EVENT_IMPORTED, subject=MAILS[EVENT_IMPORTED]['subject'].format(event_name=result['name']), html=MAILS[EVENT_IMPORTED]['message'].format(event_url=(request.url_root.strip('/') + ('/events/%d' % result['id']))))
null
null
null
What do we check to ?
def plugin_cache_dir(): return os.path.join(tempfile.gettempdir(), 'UltiSnips_test_vim_plugins')
null
null
null
our bundles
codeqa
def plugin cache dir return os path join tempfile gettempdir ' Ulti Snips test vim plugins'
null
null
null
null
Question: What do we check to ? Code: def plugin_cache_dir(): return os.path.join(tempfile.gettempdir(), 'UltiSnips_test_vim_plugins')
null
null
null
What does the code draw ?
def round_corner(radius, fill): corner = Image.new(u'L', (radius, radius), 0) draw = ImageDraw.Draw(corner) draw.pieslice((0, 0, (radius * 2), (radius * 2)), 180, 270, fill=fill) return corner
null
null
null
a round corner
codeqa
def round corner radius fill corner Image new u'L' radius radius 0 draw Image Draw Draw corner draw pieslice 0 0 radius * 2 radius * 2 180 270 fill fill return corner
null
null
null
null
Question: What does the code draw ? Code: def round_corner(radius, fill): corner = Image.new(u'L', (radius, radius), 0) draw = ImageDraw.Draw(corner) draw.pieslice((0, 0, (radius * 2), (radius * 2)), 180, 270, fill=fill) return corner
null
null
null
What does the code create ?
@memoize(for_each_device=True) def reduce(in_params, out_params, map_expr, reduce_expr, post_map_expr, identity, name, **kwargs): check_cuda_available() return cupy.ReductionKernel(in_params, out_params, map_expr, reduce_expr, post_map_expr, identity, name, **kwargs)
null
null
null
a global reduction kernel function
codeqa
@memoize for each device True def reduce in params out params map expr reduce expr post map expr identity name **kwargs check cuda available return cupy Reduction Kernel in params out params map expr reduce expr post map expr identity name **kwargs
null
null
null
null
Question: What does the code create ? Code: @memoize(for_each_device=True) def reduce(in_params, out_params, map_expr, reduce_expr, post_map_expr, identity, name, **kwargs): check_cuda_available() return cupy.ReductionKernel(in_params, out_params, map_expr, reduce_expr, post_map_expr, identity, name, **kwargs)
null
null
null
What does the code return ?
def avg(list): return (float(_sum(list)) / (len(list) or 1))
null
null
null
the arithmetic mean of the given list of values
codeqa
def avg list return float sum list / len list or 1
null
null
null
null
Question: What does the code return ? Code: def avg(list): return (float(_sum(list)) / (len(list) or 1))
null
null
null
What does the code extract ?
def get_latest_changelog(): started = False lines = [] with open(CHANGELOG) as f: for line in f: if re.match('^--+$', line.strip()): if started: del lines[(-1)] break else: started = True elif started: lines.append(line) return ''.join(lines).strip()
null
null
null
the first section of the changelog
codeqa
def get latest changelog started Falselines []with open CHANGELOG as f for line in f if re match '^--+$' line strip if started del lines[ -1 ]breakelse started Trueelif started lines append line return '' join lines strip
null
null
null
null
Question: What does the code extract ? Code: def get_latest_changelog(): started = False lines = [] with open(CHANGELOG) as f: for line in f: if re.match('^--+$', line.strip()): if started: del lines[(-1)] break else: started = True elif started: lines.append(line) return ''.join(lines).strip()
null
null
null
What does the code get ?
def keywords(text): NUM_KEYWORDS = 10 text = split_words(text) if text: num_words = len(text) text = [x for x in text if (x not in stopwords)] freq = {} for word in text: if (word in freq): freq[word] += 1 else: freq[word] = 1 min_size = min(NUM_KEYWORDS, len(freq)) keywords = sorted(freq.items(), key=(lambda x: (x[1], x[0])), reverse=True) keywords = keywords[:min_size] keywords = dict(((x, y) for (x, y) in keywords)) for k in keywords: articleScore = ((keywords[k] * 1.0) / max(num_words, 1)) keywords[k] = ((articleScore * 1.5) + 1) return dict(keywords) else: return dict()
null
null
null
the top 10 keywords and their frequency scores
codeqa
def keywords text NUM KEYWORDS 10 text split words text if text num words len text text [x for x in text if x not in stopwords ]freq {}for word in text if word in freq freq[word] + 1else freq[word] 1min size min NUM KEYWORDS len freq keywords sorted freq items key lambda x x[ 1 ] x[ 0 ] reverse True keywords keywords[ min size]keywords dict x y for x y in keywords for k in keywords article Score keywords[k] * 1 0 / max num words 1 keywords[k] article Score * 1 5 + 1 return dict keywords else return dict
null
null
null
null
Question: What does the code get ? Code: def keywords(text): NUM_KEYWORDS = 10 text = split_words(text) if text: num_words = len(text) text = [x for x in text if (x not in stopwords)] freq = {} for word in text: if (word in freq): freq[word] += 1 else: freq[word] = 1 min_size = min(NUM_KEYWORDS, len(freq)) keywords = sorted(freq.items(), key=(lambda x: (x[1], x[0])), reverse=True) keywords = keywords[:min_size] keywords = dict(((x, y) for (x, y) in keywords)) for k in keywords: articleScore = ((keywords[k] * 1.0) / max(num_words, 1)) keywords[k] = ((articleScore * 1.5) + 1) return dict(keywords) else: return dict()
null
null
null
What has decorator ensuring ?
def check_job_access_permission(exception_class=PopupException): def inner(view_func): def decorate(request, *args, **kwargs): if ('workflow' in kwargs): job_type = 'workflow' elif ('coordinator' in kwargs): job_type = 'coordinator' else: job_type = 'bundle' job = kwargs.get(job_type) if (job is not None): job = Job.objects.can_read_or_exception(request, job, exception_class=exception_class) kwargs[job_type] = job return view_func(request, *args, **kwargs) return wraps(view_func)(decorate) return inner
null
null
null
that the user has access to the workflow or coordinator
codeqa
def check job access permission exception class Popup Exception def inner view func def decorate request *args **kwargs if 'workflow' in kwargs job type 'workflow'elif 'coordinator' in kwargs job type 'coordinator'else job type 'bundle'job kwargs get job type if job is not None job Job objects can read or exception request job exception class exception class kwargs[job type] jobreturn view func request *args **kwargs return wraps view func decorate return inner
null
null
null
null
Question: What has decorator ensuring ? Code: def check_job_access_permission(exception_class=PopupException): def inner(view_func): def decorate(request, *args, **kwargs): if ('workflow' in kwargs): job_type = 'workflow' elif ('coordinator' in kwargs): job_type = 'coordinator' else: job_type = 'bundle' job = kwargs.get(job_type) if (job is not None): job = Job.objects.can_read_or_exception(request, job, exception_class=exception_class) kwargs[job_type] = job return view_func(request, *args, **kwargs) return wraps(view_func)(decorate) return inner
null
null
null
What has access to the workflow or coordinator ?
def check_job_access_permission(exception_class=PopupException): def inner(view_func): def decorate(request, *args, **kwargs): if ('workflow' in kwargs): job_type = 'workflow' elif ('coordinator' in kwargs): job_type = 'coordinator' else: job_type = 'bundle' job = kwargs.get(job_type) if (job is not None): job = Job.objects.can_read_or_exception(request, job, exception_class=exception_class) kwargs[job_type] = job return view_func(request, *args, **kwargs) return wraps(view_func)(decorate) return inner
null
null
null
the user
codeqa
def check job access permission exception class Popup Exception def inner view func def decorate request *args **kwargs if 'workflow' in kwargs job type 'workflow'elif 'coordinator' in kwargs job type 'coordinator'else job type 'bundle'job kwargs get job type if job is not None job Job objects can read or exception request job exception class exception class kwargs[job type] jobreturn view func request *args **kwargs return wraps view func decorate return inner
null
null
null
null
Question: What has access to the workflow or coordinator ? Code: def check_job_access_permission(exception_class=PopupException): def inner(view_func): def decorate(request, *args, **kwargs): if ('workflow' in kwargs): job_type = 'workflow' elif ('coordinator' in kwargs): job_type = 'coordinator' else: job_type = 'bundle' job = kwargs.get(job_type) if (job is not None): job = Job.objects.can_read_or_exception(request, job, exception_class=exception_class) kwargs[job_type] = job return view_func(request, *args, **kwargs) return wraps(view_func)(decorate) return inner
null
null
null
What does the code get ?
def getSliceElementZ(sliceElement): idValue = sliceElement.attributeDictionary['id'].strip() return float(idValue[len('z:'):].strip())
null
null
null
the slice element z
codeqa
def get Slice Element Z slice Element id Value slice Element attribute Dictionary['id'] strip return float id Value[len 'z ' ] strip
null
null
null
null
Question: What does the code get ? Code: def getSliceElementZ(sliceElement): idValue = sliceElement.attributeDictionary['id'].strip() return float(idValue[len('z:'):].strip())
null
null
null
What does the code add ?
def addToMenu(master, menu, repository, window): settings.addPluginsParentToMenu(skeinforge_analyze.getPluginsDirectoryPath(), menu, __file__, skeinforge_analyze.getPluginFileNames())
null
null
null
a tool plugin menu
codeqa
def add To Menu master menu repository window settings add Plugins Parent To Menu skeinforge analyze get Plugins Directory Path menu file skeinforge analyze get Plugin File Names
null
null
null
null
Question: What does the code add ? Code: def addToMenu(master, menu, repository, window): settings.addPluginsParentToMenu(skeinforge_analyze.getPluginsDirectoryPath(), menu, __file__, skeinforge_analyze.getPluginFileNames())
null
null
null
What does the code get ?
def get_in_process_course_actions(request): return [course for course in CourseRerunState.objects.find_all(exclude_args={'state': CourseRerunUIStateManager.State.SUCCEEDED}, should_display=True) if has_studio_read_access(request.user, course.course_key)]
null
null
null
all in - process course actions
codeqa
def get in process course actions request return [course for course in Course Rerun State objects find all exclude args {'state' Course Rerun UI State Manager State SUCCEEDED} should display True if has studio read access request user course course key ]
null
null
null
null
Question: What does the code get ? Code: def get_in_process_course_actions(request): return [course for course in CourseRerunState.objects.find_all(exclude_args={'state': CourseRerunUIStateManager.State.SUCCEEDED}, should_display=True) if has_studio_read_access(request.user, course.course_key)]
null
null
null
What has the property that it fits within box_width and box_height and has the same aspect ratio as the original size ?
def bounding_box(bw, bh, w, h): (new_width, new_height) = (w, h) if (bw and (new_width > bw)): new_width = bw new_height = (new_width / (float(w) / h)) if (bh and (new_height > bh)): new_height = bh new_width = (new_height * (float(w) / h)) return (new_width, new_height)
null
null
null
a tuple
codeqa
def bounding box bw bh w h new width new height w h if bw and new width > bw new width bwnew height new width / float w / h if bh and new height > bh new height bhnew width new height * float w / h return new width new height
null
null
null
null
Question: What has the property that it fits within box_width and box_height and has the same aspect ratio as the original size ? Code: def bounding_box(bw, bh, w, h): (new_width, new_height) = (w, h) if (bw and (new_width > bw)): new_width = bw new_height = (new_width / (float(w) / h)) if (bh and (new_height > bh)): new_height = bh new_width = (new_height * (float(w) / h)) return (new_width, new_height)
null
null
null
What does a tuple have ?
def bounding_box(bw, bh, w, h): (new_width, new_height) = (w, h) if (bw and (new_width > bw)): new_width = bw new_height = (new_width / (float(w) / h)) if (bh and (new_height > bh)): new_height = bh new_width = (new_height * (float(w) / h)) return (new_width, new_height)
null
null
null
the property that it fits within box_width and box_height and has the same aspect ratio as the original size
codeqa
def bounding box bw bh w h new width new height w h if bw and new width > bw new width bwnew height new width / float w / h if bh and new height > bh new height bhnew width new height * float w / h return new width new height
null
null
null
null
Question: What does a tuple have ? Code: def bounding_box(bw, bh, w, h): (new_width, new_height) = (w, h) if (bw and (new_width > bw)): new_width = bw new_height = (new_width / (float(w) / h)) if (bh and (new_height > bh)): new_height = bh new_width = (new_height * (float(w) / h)) return (new_width, new_height)
null
null
null
What does it have ?
def bounding_box(bw, bh, w, h): (new_width, new_height) = (w, h) if (bw and (new_width > bw)): new_width = bw new_height = (new_width / (float(w) / h)) if (bh and (new_height > bh)): new_height = bh new_width = (new_height * (float(w) / h)) return (new_width, new_height)
null
null
null
the same aspect ratio as the original size
codeqa
def bounding box bw bh w h new width new height w h if bw and new width > bw new width bwnew height new width / float w / h if bh and new height > bh new height bhnew width new height * float w / h return new width new height
null
null
null
null
Question: What does it have ? Code: def bounding_box(bw, bh, w, h): (new_width, new_height) = (w, h) if (bw and (new_width > bw)): new_width = bw new_height = (new_width / (float(w) / h)) if (bh and (new_height > bh)): new_height = bh new_width = (new_height * (float(w) / h)) return (new_width, new_height)
null
null
null
Where does it fit ?
def bounding_box(bw, bh, w, h): (new_width, new_height) = (w, h) if (bw and (new_width > bw)): new_width = bw new_height = (new_width / (float(w) / h)) if (bh and (new_height > bh)): new_height = bh new_width = (new_height * (float(w) / h)) return (new_width, new_height)
null
null
null
within box_width and box_height
codeqa
def bounding box bw bh w h new width new height w h if bw and new width > bw new width bwnew height new width / float w / h if bh and new height > bh new height bhnew width new height * float w / h return new width new height
null
null
null
null
Question: Where does it fit ? Code: def bounding_box(bw, bh, w, h): (new_width, new_height) = (w, h) if (bw and (new_width > bw)): new_width = bw new_height = (new_width / (float(w) / h)) if (bh and (new_height > bh)): new_height = bh new_width = (new_height * (float(w) / h)) return (new_width, new_height)
null
null
null
What does the code perform with variance adjustment and no p - value calculation ?
def ttest_1samp_no_p(X, sigma=0, method='relative'): if (method not in ['absolute', 'relative']): raise ValueError(('method must be "absolute" or "relative", not %s' % method)) var = np.var(X, axis=0, ddof=1) if (sigma > 0): limit = ((sigma * np.max(var)) if (method == 'relative') else sigma) var += limit return (np.mean(X, axis=0) / np.sqrt((var / X.shape[0])))
null
null
null
t - test
codeqa
def ttest 1samp no p X sigma 0 method 'relative' if method not in ['absolute' 'relative'] raise Value Error 'methodmustbe"absolute"or"relative" not%s' % method var np var X axis 0 ddof 1 if sigma > 0 limit sigma * np max var if method 'relative' else sigma var + limitreturn np mean X axis 0 / np sqrt var / X shape[ 0 ]
null
null
null
null
Question: What does the code perform with variance adjustment and no p - value calculation ? Code: def ttest_1samp_no_p(X, sigma=0, method='relative'): if (method not in ['absolute', 'relative']): raise ValueError(('method must be "absolute" or "relative", not %s' % method)) var = np.var(X, axis=0, ddof=1) if (sigma > 0): limit = ((sigma * np.max(var)) if (method == 'relative') else sigma) var += limit return (np.mean(X, axis=0) / np.sqrt((var / X.shape[0])))
null
null
null
What shares a global scope ?
def _detect_global_scope(node, frame, defframe): def_scope = scope = None if (frame and frame.parent): scope = frame.parent.scope() if (defframe and defframe.parent): def_scope = defframe.parent.scope() if isinstance(frame, astroid.Function): if (not isinstance(node.parent, (astroid.Function, astroid.Arguments))): return False elif any(((not isinstance(f, (astroid.Class, astroid.Module))) for f in (frame, defframe))): return False break_scopes = [] for s in (scope, def_scope): parent_scope = s while parent_scope: if (not isinstance(parent_scope, (astroid.Class, astroid.Module))): break_scopes.append(parent_scope) break if parent_scope.parent: parent_scope = parent_scope.parent.scope() else: break if (break_scopes and (len(set(break_scopes)) != 1)): return False return (frame.lineno < defframe.lineno)
null
null
null
the given frames
codeqa
def detect global scope node frame defframe def scope scope Noneif frame and frame parent scope frame parent scope if defframe and defframe parent def scope defframe parent scope if isinstance frame astroid Function if not isinstance node parent astroid Function astroid Arguments return Falseelif any not isinstance f astroid Class astroid Module for f in frame defframe return Falsebreak scopes []for s in scope def scope parent scope swhile parent scope if not isinstance parent scope astroid Class astroid Module break scopes append parent scope breakif parent scope parent parent scope parent scope parent scope else breakif break scopes and len set break scopes 1 return Falsereturn frame lineno < defframe lineno
null
null
null
null
Question: What shares a global scope ? Code: def _detect_global_scope(node, frame, defframe): def_scope = scope = None if (frame and frame.parent): scope = frame.parent.scope() if (defframe and defframe.parent): def_scope = defframe.parent.scope() if isinstance(frame, astroid.Function): if (not isinstance(node.parent, (astroid.Function, astroid.Arguments))): return False elif any(((not isinstance(f, (astroid.Class, astroid.Module))) for f in (frame, defframe))): return False break_scopes = [] for s in (scope, def_scope): parent_scope = s while parent_scope: if (not isinstance(parent_scope, (astroid.Class, astroid.Module))): break_scopes.append(parent_scope) break if parent_scope.parent: parent_scope = parent_scope.parent.scope() else: break if (break_scopes and (len(set(break_scopes)) != 1)): return False return (frame.lineno < defframe.lineno)
null
null
null
What do the given frames share ?
def _detect_global_scope(node, frame, defframe): def_scope = scope = None if (frame and frame.parent): scope = frame.parent.scope() if (defframe and defframe.parent): def_scope = defframe.parent.scope() if isinstance(frame, astroid.Function): if (not isinstance(node.parent, (astroid.Function, astroid.Arguments))): return False elif any(((not isinstance(f, (astroid.Class, astroid.Module))) for f in (frame, defframe))): return False break_scopes = [] for s in (scope, def_scope): parent_scope = s while parent_scope: if (not isinstance(parent_scope, (astroid.Class, astroid.Module))): break_scopes.append(parent_scope) break if parent_scope.parent: parent_scope = parent_scope.parent.scope() else: break if (break_scopes and (len(set(break_scopes)) != 1)): return False return (frame.lineno < defframe.lineno)
null
null
null
a global scope
codeqa
def detect global scope node frame defframe def scope scope Noneif frame and frame parent scope frame parent scope if defframe and defframe parent def scope defframe parent scope if isinstance frame astroid Function if not isinstance node parent astroid Function astroid Arguments return Falseelif any not isinstance f astroid Class astroid Module for f in frame defframe return Falsebreak scopes []for s in scope def scope parent scope swhile parent scope if not isinstance parent scope astroid Class astroid Module break scopes append parent scope breakif parent scope parent parent scope parent scope parent scope else breakif break scopes and len set break scopes 1 return Falsereturn frame lineno < defframe lineno
null
null
null
null
Question: What do the given frames share ? Code: def _detect_global_scope(node, frame, defframe): def_scope = scope = None if (frame and frame.parent): scope = frame.parent.scope() if (defframe and defframe.parent): def_scope = defframe.parent.scope() if isinstance(frame, astroid.Function): if (not isinstance(node.parent, (astroid.Function, astroid.Arguments))): return False elif any(((not isinstance(f, (astroid.Class, astroid.Module))) for f in (frame, defframe))): return False break_scopes = [] for s in (scope, def_scope): parent_scope = s while parent_scope: if (not isinstance(parent_scope, (astroid.Class, astroid.Module))): break_scopes.append(parent_scope) break if parent_scope.parent: parent_scope = parent_scope.parent.scope() else: break if (break_scopes and (len(set(break_scopes)) != 1)): return False return (frame.lineno < defframe.lineno)
null
null
null
Where did properties specify ?
def read_simple_binding(jboss_config, binding_name, profile=None): log.debug('======================== MODULE FUNCTION: jboss7.read_simple_binding, %s', binding_name) return __read_simple_binding(jboss_config, binding_name, profile=profile)
null
null
null
above
codeqa
def read simple binding jboss config binding name profile None log debug ' MODULEFUNCTION jboss 7 read simple binding %s' binding name return read simple binding jboss config binding name profile profile
null
null
null
null
Question: Where did properties specify ? Code: def read_simple_binding(jboss_config, binding_name, profile=None): log.debug('======================== MODULE FUNCTION: jboss7.read_simple_binding, %s', binding_name) return __read_simple_binding(jboss_config, binding_name, profile=profile)
null
null
null
What specified above ?
def read_simple_binding(jboss_config, binding_name, profile=None): log.debug('======================== MODULE FUNCTION: jboss7.read_simple_binding, %s', binding_name) return __read_simple_binding(jboss_config, binding_name, profile=profile)
null
null
null
properties
codeqa
def read simple binding jboss config binding name profile None log debug ' MODULEFUNCTION jboss 7 read simple binding %s' binding name return read simple binding jboss config binding name profile profile
null
null
null
null
Question: What specified above ? Code: def read_simple_binding(jboss_config, binding_name, profile=None): log.debug('======================== MODULE FUNCTION: jboss7.read_simple_binding, %s', binding_name) return __read_simple_binding(jboss_config, binding_name, profile=profile)
null
null
null
How does the code sort them ?
def sort(seq): if (len(seq) <= 1): return seq else: pivot = seq[0] (left, right) = ([], []) for x in seq[1:]: if (x < pivot): left.append(x) else: right.append(x) return ((sort(left) + [pivot]) + sort(right))
null
null
null
in ascending order
codeqa
def sort seq if len seq < 1 return seqelse pivot seq[ 0 ] left right [] [] for x in seq[ 1 ] if x < pivot left append x else right append x return sort left + [pivot] + sort right
null
null
null
null
Question: How does the code sort them ? Code: def sort(seq): if (len(seq) <= 1): return seq else: pivot = seq[0] (left, right) = ([], []) for x in seq[1:]: if (x < pivot): left.append(x) else: right.append(x) return ((sort(left) + [pivot]) + sort(right))
null
null
null
What does the code take ?
def sort(seq): if (len(seq) <= 1): return seq else: pivot = seq[0] (left, right) = ([], []) for x in seq[1:]: if (x < pivot): left.append(x) else: right.append(x) return ((sort(left) + [pivot]) + sort(right))
null
null
null
a list of integers
codeqa
def sort seq if len seq < 1 return seqelse pivot seq[ 0 ] left right [] [] for x in seq[ 1 ] if x < pivot left append x else right append x return sort left + [pivot] + sort right
null
null
null
null
Question: What does the code take ? Code: def sort(seq): if (len(seq) <= 1): return seq else: pivot = seq[0] (left, right) = ([], []) for x in seq[1:]: if (x < pivot): left.append(x) else: right.append(x) return ((sort(left) + [pivot]) + sort(right))
null
null
null
What does the code find ?
def cert_from_instance(instance): if instance.signature: if instance.signature.key_info: return cert_from_key_info(instance.signature.key_info, ignore_age=True) return []
null
null
null
certificates that are part of an instance
codeqa
def cert from instance instance if instance signature if instance signature key info return cert from key info instance signature key info ignore age True return []
null
null
null
null
Question: What does the code find ? Code: def cert_from_instance(instance): if instance.signature: if instance.signature.key_info: return cert_from_key_info(instance.signature.key_info, ignore_age=True) return []
null
null
null
What does the code turn back into its character representation ?
def ids(probabilities): return [str(c) for c in np.argmax(probabilities, 1)]
null
null
null
a 1-hot encoding or a probability distribution over the possible characters
codeqa
def ids probabilities return [str c for c in np argmax probabilities 1 ]
null
null
null
null
Question: What does the code turn back into its character representation ? Code: def ids(probabilities): return [str(c) for c in np.argmax(probabilities, 1)]
null
null
null
When does the code normalize ?
def ensure_utc(time, tz='UTC'): if (not time.tzinfo): time = time.replace(tzinfo=pytz.timezone(tz)) return time.replace(tzinfo=pytz.utc)
null
null
null
a time
codeqa
def ensure utc time tz 'UTC' if not time tzinfo time time replace tzinfo pytz timezone tz return time replace tzinfo pytz utc
null
null
null
null
Question: When does the code normalize ? Code: def ensure_utc(time, tz='UTC'): if (not time.tzinfo): time = time.replace(tzinfo=pytz.timezone(tz)) return time.replace(tzinfo=pytz.utc)
null
null
null
What does the code render ?
@render_to('distributed/learn.html') def learn(request): context = {'channel': CHANNEL, 'pdfjs': settings.PDFJS} return context
null
null
null
the all - in - one sidebar navigation / content - viewing app
codeqa
@render to 'distributed/learn html' def learn request context {'channel' CHANNEL 'pdfjs' settings PDFJS}return context
null
null
null
null
Question: What does the code render ? Code: @render_to('distributed/learn.html') def learn(request): context = {'channel': CHANNEL, 'pdfjs': settings.PDFJS} return context
null
null
null
What does the code return ?
@blueprint.route('/projects/<project>/meters/<meter>') def list_samples_by_project(project, meter): check_authorized_project(project) return _list_samples(project=project, meter=meter)
null
null
null
a list of raw samples for the project
codeqa
@blueprint route '/projects/<project>/meters/<meter>' def list samples by project project meter check authorized project project return list samples project project meter meter
null
null
null
null
Question: What does the code return ? Code: @blueprint.route('/projects/<project>/meters/<meter>') def list_samples_by_project(project, meter): check_authorized_project(project) return _list_samples(project=project, meter=meter)
null
null
null
What does the code split at newline ?
def splitline(text): index = (text.find('\n') + 1) if index: return (text[:index], text[index:]) else: return (text, '')
null
null
null
the given text
codeqa
def splitline text index text find '\n' + 1 if index return text[ index] text[index ] else return text ''
null
null
null
null
Question: What does the code split at newline ? Code: def splitline(text): index = (text.find('\n') + 1) if index: return (text[:index], text[index:]) else: return (text, '')
null
null
null
How does the code split the given text ?
def splitline(text): index = (text.find('\n') + 1) if index: return (text[:index], text[index:]) else: return (text, '')
null
null
null
at newline
codeqa
def splitline text index text find '\n' + 1 if index return text[ index] text[index ] else return text ''
null
null
null
null
Question: How does the code split the given text ? Code: def splitline(text): index = (text.find('\n') + 1) if index: return (text[:index], text[index:]) else: return (text, '')
null
null
null
What does the code retrieve ?
def quota_usage_get_all_by_project_and_user(context, project_id, user_id): return IMPL.quota_usage_get_all_by_project_and_user(context, project_id, user_id)
null
null
null
all usage associated with a given resource
codeqa
def quota usage get all by project and user context project id user id return IMPL quota usage get all by project and user context project id user id
null
null
null
null
Question: What does the code retrieve ? Code: def quota_usage_get_all_by_project_and_user(context, project_id, user_id): return IMPL.quota_usage_get_all_by_project_and_user(context, project_id, user_id)
null
null
null
What does the code begin ?
def _MaybeSetupTransaction(request, keys): return _GetConnection()._set_request_transaction(request)
null
null
null
a transaction
codeqa
def Maybe Setup Transaction request keys return Get Connection set request transaction request
null
null
null
null
Question: What does the code begin ? Code: def _MaybeSetupTransaction(request, keys): return _GetConnection()._set_request_transaction(request)
null
null
null
What is requesting user ?
def _send_decision_email(instance): context = {'name': instance.user.username, 'api_management_url': urlunsplit((('https' if (settings.HTTPS == 'on') else 'http'), instance.site.domain, reverse('api_admin:api-status'), '', '')), 'authentication_docs_url': settings.AUTH_DOCUMENTATION_URL, 'api_docs_url': settings.API_DOCUMENTATION_URL, 'support_email_address': settings.API_ACCESS_FROM_EMAIL, 'platform_name': configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME)} message = render_to_string('api_admin/api_access_request_email_{status}.txt'.format(status=instance.status), context) try: send_mail(_('API access request'), message, settings.API_ACCESS_FROM_EMAIL, [instance.user.email], fail_silently=False) instance.contacted = True except SMTPException: log.exception('Error sending API user notification email for request [%s].', instance.id)
null
null
null
with the decision made about their request
codeqa
def send decision email instance context {'name' instance user username 'api management url' urlunsplit 'https' if settings HTTPS 'on' else 'http' instance site domain reverse 'api admin api-status' '' '' 'authentication docs url' settings AUTH DOCUMENTATION URL 'api docs url' settings API DOCUMENTATION URL 'support email address' settings API ACCESS FROM EMAIL 'platform name' configuration helpers get value 'PLATFORM NAME' settings PLATFORM NAME }message render to string 'api admin/api access request email {status} txt' format status instance status context try send mail 'AP Iaccessrequest' message settings API ACCESS FROM EMAIL [instance user email] fail silently False instance contacted Trueexcept SMTP Exception log exception ' Errorsending AP Iusernotificationemailforrequest[%s] ' instance id
null
null
null
null
Question: What is requesting user ? Code: def _send_decision_email(instance): context = {'name': instance.user.username, 'api_management_url': urlunsplit((('https' if (settings.HTTPS == 'on') else 'http'), instance.site.domain, reverse('api_admin:api-status'), '', '')), 'authentication_docs_url': settings.AUTH_DOCUMENTATION_URL, 'api_docs_url': settings.API_DOCUMENTATION_URL, 'support_email_address': settings.API_ACCESS_FROM_EMAIL, 'platform_name': configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME)} message = render_to_string('api_admin/api_access_request_email_{status}.txt'.format(status=instance.status), context) try: send_mail(_('API access request'), message, settings.API_ACCESS_FROM_EMAIL, [instance.user.email], fail_silently=False) instance.contacted = True except SMTPException: log.exception('Error sending API user notification email for request [%s].', instance.id)
null
null
null
How can the user access it ?
def bucket_exists(access_key, secret_key, bucket_name): if (not bucket_name): return False connection = connect_s3(access_key, secret_key) if (bucket_name != bucket_name.lower()): connection.calling_format = OrdinaryCallingFormat() try: connect_s3(access_key, secret_key).head_bucket(bucket_name) except exception.S3ResponseError as e: if (e.status not in (301, 302)): return False return True
null
null
null
with the given keys
codeqa
def bucket exists access key secret key bucket name if not bucket name return Falseconnection connect s3 access key secret key if bucket name bucket name lower connection calling format Ordinary Calling Format try connect s3 access key secret key head bucket bucket name except exception S3 Response Error as e if e status not in 301 302 return Falsereturn True
null
null
null
null
Question: How can the user access it ? Code: def bucket_exists(access_key, secret_key, bucket_name): if (not bucket_name): return False connection = connect_s3(access_key, secret_key) if (bucket_name != bucket_name.lower()): connection.calling_format = OrdinaryCallingFormat() try: connect_s3(access_key, secret_key).head_bucket(bucket_name) except exception.S3ResponseError as e: if (e.status not in (301, 302)): return False return True
null
null
null
What can access it with the given keys ?
def bucket_exists(access_key, secret_key, bucket_name): if (not bucket_name): return False connection = connect_s3(access_key, secret_key) if (bucket_name != bucket_name.lower()): connection.calling_format = OrdinaryCallingFormat() try: connect_s3(access_key, secret_key).head_bucket(bucket_name) except exception.S3ResponseError as e: if (e.status not in (301, 302)): return False return True
null
null
null
the user
codeqa
def bucket exists access key secret key bucket name if not bucket name return Falseconnection connect s3 access key secret key if bucket name bucket name lower connection calling format Ordinary Calling Format try connect s3 access key secret key head bucket bucket name except exception S3 Response Error as e if e status not in 301 302 return Falsereturn True
null
null
null
null
Question: What can access it with the given keys ? Code: def bucket_exists(access_key, secret_key, bucket_name): if (not bucket_name): return False connection = connect_s3(access_key, secret_key) if (bucket_name != bucket_name.lower()): connection.calling_format = OrdinaryCallingFormat() try: connect_s3(access_key, secret_key).head_bucket(bucket_name) except exception.S3ResponseError as e: if (e.status not in (301, 302)): return False return True
null
null
null
Where did the camera use ?
def my_calibration(sz): (row, col) = sz fx = ((2555 * col) / 2592) fy = ((2586 * row) / 1936) K = diag([fx, fy, 1]) K[(0, 2)] = (0.5 * col) K[(1, 2)] = (0.5 * row) return K
null
null
null
in this example
codeqa
def my calibration sz row col szfx 2555 * col / 2592 fy 2586 * row / 1936 K diag [fx fy 1] K[ 0 2 ] 0 5 * col K[ 1 2 ] 0 5 * row return K
null
null
null
null
Question: Where did the camera use ? Code: def my_calibration(sz): (row, col) = sz fx = ((2555 * col) / 2592) fy = ((2586 * row) / 1936) K = diag([fx, fy, 1]) K[(0, 2)] = (0.5 * col) K[(1, 2)] = (0.5 * row) return K
null
null
null
What used in this example ?
def my_calibration(sz): (row, col) = sz fx = ((2555 * col) / 2592) fy = ((2586 * row) / 1936) K = diag([fx, fy, 1]) K[(0, 2)] = (0.5 * col) K[(1, 2)] = (0.5 * row) return K
null
null
null
the camera
codeqa
def my calibration sz row col szfx 2555 * col / 2592 fy 2586 * row / 1936 K diag [fx fy 1] K[ 0 2 ] 0 5 * col K[ 1 2 ] 0 5 * row return K
null
null
null
null
Question: What used in this example ? Code: def my_calibration(sz): (row, col) = sz fx = ((2555 * col) / 2592) fy = ((2586 * row) / 1936) K = diag([fx, fy, 1]) K[(0, 2)] = (0.5 * col) K[(1, 2)] = (0.5 * row) return K
null
null
null
What does the code send ?
def call(conf, *args, **kwargs): data = _multi_send(_call, *args, **kwargs) return data[(-1)]
null
null
null
a message
codeqa
def call conf *args **kwargs data multi send call *args **kwargs return data[ -1 ]
null
null
null
null
Question: What does the code send ? Code: def call(conf, *args, **kwargs): data = _multi_send(_call, *args, **kwargs) return data[(-1)]
null
null
null
What does the code add ?
def taint(taintedSet, taintedAttribute): taintedSet.add(taintedAttribute) if (taintedAttribute == 'marker'): taintedSet |= set(['marker-start', 'marker-mid', 'marker-end']) if (taintedAttribute in ['marker-start', 'marker-mid', 'marker-end']): taintedSet.add('marker') return taintedSet
null
null
null
an attribute to a set of attributes
codeqa
def taint tainted Set tainted Attribute tainted Set add tainted Attribute if tainted Attribute 'marker' tainted Set set ['marker-start' 'marker-mid' 'marker-end'] if tainted Attribute in ['marker-start' 'marker-mid' 'marker-end'] tainted Set add 'marker' return tainted Set
null
null
null
null
Question: What does the code add ? Code: def taint(taintedSet, taintedAttribute): taintedSet.add(taintedAttribute) if (taintedAttribute == 'marker'): taintedSet |= set(['marker-start', 'marker-mid', 'marker-end']) if (taintedAttribute in ['marker-start', 'marker-mid', 'marker-end']): taintedSet.add('marker') return taintedSet
null
null
null
What does the code sanitize ?
def sanitize_url(address): if (address.startswith('http://') or address.startswith('https://')): return address else: return 'http://{}'.format(address)
null
null
null
url
codeqa
def sanitize url address if address startswith 'http //' or address startswith 'https //' return addresselse return 'http //{}' format address
null
null
null
null
Question: What does the code sanitize ? Code: def sanitize_url(address): if (address.startswith('http://') or address.startswith('https://')): return address else: return 'http://{}'.format(address)
null
null
null
By how much is metrics data missing at a timestamp ?
def MissingMetricsCriteria(): return ([], [])
null
null
null
completely
codeqa
def Missing Metrics Criteria return [] []
null
null
null
null
Question: By how much is metrics data missing at a timestamp ? Code: def MissingMetricsCriteria(): return ([], [])
null
null
null
What is missing at a timestamp ?
def MissingMetricsCriteria(): return ([], [])
null
null
null
metrics data
codeqa
def Missing Metrics Criteria return [] []
null
null
null
null
Question: What is missing at a timestamp ? Code: def MissingMetricsCriteria(): return ([], [])
null
null
null
Where is metrics data missing completely ?
def MissingMetricsCriteria(): return ([], [])
null
null
null
at a timestamp
codeqa
def Missing Metrics Criteria return [] []
null
null
null
null
Question: Where is metrics data missing completely ? Code: def MissingMetricsCriteria(): return ([], [])
null
null
null
For what purpose can we extend it ?
def yaml_load(source, loader=yaml.Loader): def construct_yaml_str(self, node): u'\n Override the default string handling function to always return\n unicode objects.\n ' return self.construct_scalar(node) class Loader(loader, ): u'\n Define a custom loader derived from the global loader to leave the\n global loader unaltered.\n ' Loader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str) try: return yaml.load(source, Loader) finally: if hasattr(source, u'close'): source.close()
null
null
null
to suit our needs
codeqa
def yaml load source loader yaml Loader def construct yaml str self node u'\n Overridethedefaultstringhandlingfunctiontoalwaysreturn\nunicodeobjects \n'return self construct scalar node class Loader loader u'\n Defineacustomloaderderivedfromthegloballoadertoleavethe\ngloballoaderunaltered \n' Loader add constructor u'tag yaml org 2002 str' construct yaml str try return yaml load source Loader finally if hasattr source u'close' source close
null
null
null
null
Question: For what purpose can we extend it ? Code: def yaml_load(source, loader=yaml.Loader): def construct_yaml_str(self, node): u'\n Override the default string handling function to always return\n unicode objects.\n ' return self.construct_scalar(node) class Loader(loader, ): u'\n Define a custom loader derived from the global loader to leave the\n global loader unaltered.\n ' Loader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str) try: return yaml.load(source, Loader) finally: if hasattr(source, u'close'): source.close()
null
null
null
What does the code insert ?
def insert(graph, node, a, b): if (not isinstance(node, Node)): node = graph[node] if (not isinstance(a, Node)): a = graph[a] if (not isinstance(b, Node)): b = graph[b] for e in graph.edges: if ((e.node1 == a) and (e.node2 == b)): graph._add_edge_copy(e, node1=a, node2=node) graph._add_edge_copy(e, node1=node, node2=b) if ((e.node1 == b) and (e.node2 == a)): graph._add_edge_copy(e, node1=b, node2=node) graph._add_edge_copy(e, node1=node, node2=a) unlink(graph, a, b)
null
null
null
the given node between node a and node b
codeqa
def insert graph node a b if not isinstance node Node node graph[node]if not isinstance a Node a graph[a]if not isinstance b Node b graph[b]for e in graph edges if e node 1 a and e node 2 b graph add edge copy e node 1 a node 2 node graph add edge copy e node 1 node node 2 b if e node 1 b and e node 2 a graph add edge copy e node 1 b node 2 node graph add edge copy e node 1 node node 2 a unlink graph a b
null
null
null
null
Question: What does the code insert ? Code: def insert(graph, node, a, b): if (not isinstance(node, Node)): node = graph[node] if (not isinstance(a, Node)): a = graph[a] if (not isinstance(b, Node)): b = graph[b] for e in graph.edges: if ((e.node1 == a) and (e.node2 == b)): graph._add_edge_copy(e, node1=a, node2=node) graph._add_edge_copy(e, node1=node, node2=b) if ((e.node1 == b) and (e.node2 == a)): graph._add_edge_copy(e, node1=b, node2=node) graph._add_edge_copy(e, node1=node, node2=a) unlink(graph, a, b)
null
null
null
What does the code use by device number ?
def get_context(devnum=0): return _runtime.get_or_create_context(devnum)
null
null
null
a device
codeqa
def get context devnum 0 return runtime get or create context devnum
null
null
null
null
Question: What does the code use by device number ? Code: def get_context(devnum=0): return _runtime.get_or_create_context(devnum)
null
null
null
How does the code use a device ?
def get_context(devnum=0): return _runtime.get_or_create_context(devnum)
null
null
null
by device number
codeqa
def get context devnum 0 return runtime get or create context devnum
null
null
null
null
Question: How does the code use a device ? Code: def get_context(devnum=0): return _runtime.get_or_create_context(devnum)
null
null
null
What does the code get ?
def get_context(devnum=0): return _runtime.get_or_create_context(devnum)
null
null
null
the current device
codeqa
def get context devnum 0 return runtime get or create context devnum
null
null
null
null
Question: What does the code get ? Code: def get_context(devnum=0): return _runtime.get_or_create_context(devnum)
null
null
null
What can switch the flag values temporarily ?
def FlagOverrider(**flag_kwargs): def Decorator(f): 'Allow a function to safely change flags, restoring them on return.' def Decorated(*args, **kwargs): global FLAGS old_flags = copy.copy(FLAGS) for (k, v) in flag_kwargs.items(): setattr(FLAGS, k, v) try: return f(*args, **kwargs) finally: FLAGS = old_flags return Decorated return Decorator
null
null
null
a helpful decorator
codeqa
def Flag Overrider **flag kwargs def Decorator f ' Allowafunctiontosafelychangeflags restoringthemonreturn 'def Decorated *args **kwargs global FLAG Sold flags copy copy FLAGS for k v in flag kwargs items setattr FLAGS k v try return f *args **kwargs finally FLAGS old flagsreturn Decoratedreturn Decorator
null
null
null
null
Question: What can switch the flag values temporarily ? Code: def FlagOverrider(**flag_kwargs): def Decorator(f): 'Allow a function to safely change flags, restoring them on return.' def Decorated(*args, **kwargs): global FLAGS old_flags = copy.copy(FLAGS) for (k, v) in flag_kwargs.items(): setattr(FLAGS, k, v) try: return f(*args, **kwargs) finally: FLAGS = old_flags return Decorated return Decorator
null
null
null
When can a helpful decorator switch the flag values ?
def FlagOverrider(**flag_kwargs): def Decorator(f): 'Allow a function to safely change flags, restoring them on return.' def Decorated(*args, **kwargs): global FLAGS old_flags = copy.copy(FLAGS) for (k, v) in flag_kwargs.items(): setattr(FLAGS, k, v) try: return f(*args, **kwargs) finally: FLAGS = old_flags return Decorated return Decorator
null
null
null
temporarily
codeqa
def Flag Overrider **flag kwargs def Decorator f ' Allowafunctiontosafelychangeflags restoringthemonreturn 'def Decorated *args **kwargs global FLAG Sold flags copy copy FLAGS for k v in flag kwargs items setattr FLAGS k v try return f *args **kwargs finally FLAGS old flagsreturn Decoratedreturn Decorator
null
null
null
null
Question: When can a helpful decorator switch the flag values ? Code: def FlagOverrider(**flag_kwargs): def Decorator(f): 'Allow a function to safely change flags, restoring them on return.' def Decorated(*args, **kwargs): global FLAGS old_flags = copy.copy(FLAGS) for (k, v) in flag_kwargs.items(): setattr(FLAGS, k, v) try: return f(*args, **kwargs) finally: FLAGS = old_flags return Decorated return Decorator
null
null
null
What can a helpful decorator switch temporarily ?
def FlagOverrider(**flag_kwargs): def Decorator(f): 'Allow a function to safely change flags, restoring them on return.' def Decorated(*args, **kwargs): global FLAGS old_flags = copy.copy(FLAGS) for (k, v) in flag_kwargs.items(): setattr(FLAGS, k, v) try: return f(*args, **kwargs) finally: FLAGS = old_flags return Decorated return Decorator
null
null
null
the flag values
codeqa
def Flag Overrider **flag kwargs def Decorator f ' Allowafunctiontosafelychangeflags restoringthemonreturn 'def Decorated *args **kwargs global FLAG Sold flags copy copy FLAGS for k v in flag kwargs items setattr FLAGS k v try return f *args **kwargs finally FLAGS old flagsreturn Decoratedreturn Decorator
null
null
null
null
Question: What can a helpful decorator switch temporarily ? Code: def FlagOverrider(**flag_kwargs): def Decorator(f): 'Allow a function to safely change flags, restoring them on return.' def Decorated(*args, **kwargs): global FLAGS old_flags = copy.copy(FLAGS) for (k, v) in flag_kwargs.items(): setattr(FLAGS, k, v) try: return f(*args, **kwargs) finally: FLAGS = old_flags return Decorated return Decorator
null
null
null
For what purpose do logger return ?
def log(): global _log if (_log is None): _log = wf().logger return _log
null
null
null
for this module
codeqa
def log global logif log is None log wf loggerreturn log
null
null
null
null
Question: For what purpose do logger return ? Code: def log(): global _log if (_log is None): _log = wf().logger return _log
null
null
null
What does the code add to the end of a target ?
def _SuffixName(name, suffix): parts = name.rsplit('#', 1) parts[0] = ('%s_%s' % (parts[0], suffix)) return '#'.join(parts)
null
null
null
a suffix
codeqa
def Suffix Name name suffix parts name rsplit '#' 1 parts[ 0 ] '%s %s' % parts[ 0 ] suffix return '#' join parts
null
null
null
null
Question: What does the code add to the end of a target ? Code: def _SuffixName(name, suffix): parts = name.rsplit('#', 1) parts[0] = ('%s_%s' % (parts[0], suffix)) return '#'.join(parts)
null
null
null
What does the code retrieve by name ?
def get_tenant(keystone, name): tenants = [x for x in keystone.tenants.list() if (x.name == name)] count = len(tenants) if (count == 0): raise KeyError(('No keystone tenants with name %s' % name)) elif (count > 1): raise ValueError(('%d tenants with name %s' % (count, name))) else: return tenants[0]
null
null
null
a tenant
codeqa
def get tenant keystone name tenants [x for x in keystone tenants list if x name name ]count len tenants if count 0 raise Key Error ' Nokeystonetenantswithname%s' % name elif count > 1 raise Value Error '%dtenantswithname%s' % count name else return tenants[ 0 ]
null
null
null
null
Question: What does the code retrieve by name ? Code: def get_tenant(keystone, name): tenants = [x for x in keystone.tenants.list() if (x.name == name)] count = len(tenants) if (count == 0): raise KeyError(('No keystone tenants with name %s' % name)) elif (count > 1): raise ValueError(('%d tenants with name %s' % (count, name))) else: return tenants[0]
null
null
null
How does the code retrieve a tenant ?
def get_tenant(keystone, name): tenants = [x for x in keystone.tenants.list() if (x.name == name)] count = len(tenants) if (count == 0): raise KeyError(('No keystone tenants with name %s' % name)) elif (count > 1): raise ValueError(('%d tenants with name %s' % (count, name))) else: return tenants[0]
null
null
null
by name
codeqa
def get tenant keystone name tenants [x for x in keystone tenants list if x name name ]count len tenants if count 0 raise Key Error ' Nokeystonetenantswithname%s' % name elif count > 1 raise Value Error '%dtenantswithname%s' % count name else return tenants[ 0 ]
null
null
null
null
Question: How does the code retrieve a tenant ? Code: def get_tenant(keystone, name): tenants = [x for x in keystone.tenants.list() if (x.name == name)] count = len(tenants) if (count == 0): raise KeyError(('No keystone tenants with name %s' % name)) elif (count > 1): raise ValueError(('%d tenants with name %s' % (count, name))) else: return tenants[0]
null
null
null
What locks a transaction during the function call ?
def _SynchronizeTxn(function): def sync(txn, *args, **kwargs): txn._lock.acquire() try: Check((txn._state is LiveTxn.ACTIVE), 'transaction closed') return function(txn, *args, **kwargs) finally: txn._lock.release() return sync
null
null
null
a decorator
codeqa
def Synchronize Txn function def sync txn *args **kwargs txn lock acquire try Check txn state is Live Txn ACTIVE 'transactionclosed' return function txn *args **kwargs finally txn lock release return sync
null
null
null
null
Question: What locks a transaction during the function call ? Code: def _SynchronizeTxn(function): def sync(txn, *args, **kwargs): txn._lock.acquire() try: Check((txn._state is LiveTxn.ACTIVE), 'transaction closed') return function(txn, *args, **kwargs) finally: txn._lock.release() return sync
null
null
null
When does a decorator lock a transaction ?
def _SynchronizeTxn(function): def sync(txn, *args, **kwargs): txn._lock.acquire() try: Check((txn._state is LiveTxn.ACTIVE), 'transaction closed') return function(txn, *args, **kwargs) finally: txn._lock.release() return sync
null
null
null
during the function call
codeqa
def Synchronize Txn function def sync txn *args **kwargs txn lock acquire try Check txn state is Live Txn ACTIVE 'transactionclosed' return function txn *args **kwargs finally txn lock release return sync
null
null
null
null
Question: When does a decorator lock a transaction ? Code: def _SynchronizeTxn(function): def sync(txn, *args, **kwargs): txn._lock.acquire() try: Check((txn._state is LiveTxn.ACTIVE), 'transaction closed') return function(txn, *args, **kwargs) finally: txn._lock.release() return sync
null
null
null
What does a decorator lock during the function call ?
def _SynchronizeTxn(function): def sync(txn, *args, **kwargs): txn._lock.acquire() try: Check((txn._state is LiveTxn.ACTIVE), 'transaction closed') return function(txn, *args, **kwargs) finally: txn._lock.release() return sync
null
null
null
a transaction
codeqa
def Synchronize Txn function def sync txn *args **kwargs txn lock acquire try Check txn state is Live Txn ACTIVE 'transactionclosed' return function txn *args **kwargs finally txn lock release return sync
null
null
null
null
Question: What does a decorator lock during the function call ? Code: def _SynchronizeTxn(function): def sync(txn, *args, **kwargs): txn._lock.acquire() try: Check((txn._state is LiveTxn.ACTIVE), 'transaction closed') return function(txn, *args, **kwargs) finally: txn._lock.release() return sync
null
null
null
What does the code get ?
def _get_linux_adapter_name_and_ip_address(mac_address): network_adapters = _get_linux_network_adapters() return _get_adapter_name_and_ip_address(network_adapters, mac_address)
null
null
null
linux network adapter name
codeqa
def get linux adapter name and ip address mac address network adapters get linux network adapters return get adapter name and ip address network adapters mac address
null
null
null
null
Question: What does the code get ? Code: def _get_linux_adapter_name_and_ip_address(mac_address): network_adapters = _get_linux_network_adapters() return _get_adapter_name_and_ip_address(network_adapters, mac_address)
null
null
null
What is missing in a given config dict ?
def upgrade_config(config, config_path=os.path.expanduser('~/.jrnl_conf')): missing_keys = set(default_config).difference(config) if missing_keys: for key in missing_keys: config[key] = default_config[key] with open(config_path, 'w') as f: json.dump(config, f, indent=2) print '[.jrnl_conf updated to newest version]'
null
null
null
keys
codeqa
def upgrade config config config path os path expanduser '~/ jrnl conf' missing keys set default config difference config if missing keys for key in missing keys config[key] default config[key]with open config path 'w' as f json dump config f indent 2 print '[ jrnl confupdatedtonewestversion]'
null
null
null
null
Question: What is missing in a given config dict ? Code: def upgrade_config(config, config_path=os.path.expanduser('~/.jrnl_conf')): missing_keys = set(default_config).difference(config) if missing_keys: for key in missing_keys: config[key] = default_config[key] with open(config_path, 'w') as f: json.dump(config, f, indent=2) print '[.jrnl_conf updated to newest version]'
null
null
null
Where do keys miss ?
def upgrade_config(config, config_path=os.path.expanduser('~/.jrnl_conf')): missing_keys = set(default_config).difference(config) if missing_keys: for key in missing_keys: config[key] = default_config[key] with open(config_path, 'w') as f: json.dump(config, f, indent=2) print '[.jrnl_conf updated to newest version]'
null
null
null
in a given config dict
codeqa
def upgrade config config config path os path expanduser '~/ jrnl conf' missing keys set default config difference config if missing keys for key in missing keys config[key] default config[key]with open config path 'w' as f json dump config f indent 2 print '[ jrnl confupdatedtonewestversion]'
null
null
null
null
Question: Where do keys miss ? Code: def upgrade_config(config, config_path=os.path.expanduser('~/.jrnl_conf')): missing_keys = set(default_config).difference(config) if missing_keys: for key in missing_keys: config[key] = default_config[key] with open(config_path, 'w') as f: json.dump(config, f, indent=2) print '[.jrnl_conf updated to newest version]'
null
null
null
How do views come from the database ?
def generate_views(action): view_id = (action.get('view_id') or False) if isinstance(view_id, (list, tuple)): view_id = view_id[0] view_modes = action['view_mode'].split(',') if (len(view_modes) > 1): if view_id: raise ValueError(('Non-db action dictionaries should provide either multiple view modes or a single view mode and an optional view id.\n\n Got view modes %r and view id %r for action %r' % (view_modes, view_id, action))) action['views'] = [(False, mode) for mode in view_modes] return action['views'] = [(view_id, view_modes[0])]
null
null
null
directly
codeqa
def generate views action view id action get 'view id' or False if isinstance view id list tuple view id view id[ 0 ]view modes action['view mode'] split ' ' if len view modes > 1 if view id raise Value Error ' Non-dbactiondictionariesshouldprovideeithermultipleviewmodesorasingleviewmodeandanoptionalviewid \n\n Gotviewmodes%randviewid%rforaction%r' % view modes view id action action['views'] [ False mode for mode in view modes]returnaction['views'] [ view id view modes[ 0 ] ]
null
null
null
null
Question: How do views come from the database ? Code: def generate_views(action): view_id = (action.get('view_id') or False) if isinstance(view_id, (list, tuple)): view_id = view_id[0] view_modes = action['view_mode'].split(',') if (len(view_modes) > 1): if view_id: raise ValueError(('Non-db action dictionaries should provide either multiple view modes or a single view mode and an optional view id.\n\n Got view modes %r and view id %r for action %r' % (view_modes, view_id, action))) action['views'] = [(False, mode) for mode in view_modes] return action['views'] = [(view_id, view_modes[0])]
null
null
null
What does the code delete ?
def delete_multi(keys, **ctx_options): return [future.get_result() for future in delete_multi_async(keys, **ctx_options)]
null
null
null
a sequence of keys
codeqa
def delete multi keys **ctx options return [future get result for future in delete multi async keys **ctx options ]
null
null
null
null
Question: What does the code delete ? Code: def delete_multi(keys, **ctx_options): return [future.get_result() for future in delete_multi_async(keys, **ctx_options)]
null
null
null
For what purpose did deltas require ?
def downsize_quota_delta(context, instance): old_flavor = instance.get_flavor('old') new_flavor = instance.get_flavor('new') return resize_quota_delta(context, new_flavor, old_flavor, 1, (-1))
null
null
null
to adjust quota
codeqa
def downsize quota delta context instance old flavor instance get flavor 'old' new flavor instance get flavor 'new' return resize quota delta context new flavor old flavor 1 -1
null
null
null
null
Question: For what purpose did deltas require ? Code: def downsize_quota_delta(context, instance): old_flavor = instance.get_flavor('old') new_flavor = instance.get_flavor('new') return resize_quota_delta(context, new_flavor, old_flavor, 1, (-1))
null
null
null
What did the code read ?
def read_packed_refs_with_peeled(f): last = None for l in f: if (l[0] == '#'): continue l = l.rstrip('\r\n') if l.startswith('^'): if (not last): raise PackedRefsException('unexpected peeled ref line') if (not valid_hexsha(l[1:])): raise PackedRefsException(('Invalid hex sha %r' % l[1:])) (sha, name) = _split_ref_line(last) last = None (yield (sha, name, l[1:])) else: if last: (sha, name) = _split_ref_line(last) (yield (sha, name, None)) last = l if last: (sha, name) = _split_ref_line(last) (yield (sha, name, None))
null
null
null
a packed refs file including peeled refs
codeqa
def read packed refs with peeled f last Nonefor l in f if l[ 0 ] '#' continuel l rstrip '\r\n' if l startswith '^' if not last raise Packed Refs Exception 'unexpectedpeeledrefline' if not valid hexsha l[ 1 ] raise Packed Refs Exception ' Invalidhexsha%r' % l[ 1 ] sha name split ref line last last None yield sha name l[ 1 ] else if last sha name split ref line last yield sha name None last lif last sha name split ref line last yield sha name None
null
null
null
null
Question: What did the code read ? Code: def read_packed_refs_with_peeled(f): last = None for l in f: if (l[0] == '#'): continue l = l.rstrip('\r\n') if l.startswith('^'): if (not last): raise PackedRefsException('unexpected peeled ref line') if (not valid_hexsha(l[1:])): raise PackedRefsException(('Invalid hex sha %r' % l[1:])) (sha, name) = _split_ref_line(last) last = None (yield (sha, name, l[1:])) else: if last: (sha, name) = _split_ref_line(last) (yield (sha, name, None)) last = l if last: (sha, name) = _split_ref_line(last) (yield (sha, name, None))
null
null
null
What does the code generate ?
def _random_range(**kwargs): min_inclusive = kwargs.pop('min_inclusive', None) max_inclusive = kwargs.pop('max_inclusive', None) max_exclusive = kwargs.pop('max_exclusive', None) randfunc = kwargs.pop('randfunc', None) if kwargs: raise ValueError(('Unknown keywords: ' + str(kwargs.keys))) if (None not in (max_inclusive, max_exclusive)): raise ValueError('max_inclusive and max_exclusive cannot be both specified') if (max_exclusive is not None): max_inclusive = (max_exclusive - 1) if (None in (min_inclusive, max_inclusive)): raise ValueError('Missing keyword to identify the interval') if (randfunc is None): randfunc = Random.new().read norm_maximum = (max_inclusive - min_inclusive) bits_needed = Integer(norm_maximum).size_in_bits() norm_candidate = (-1) while (not (0 <= norm_candidate <= norm_maximum)): norm_candidate = _random(max_bits=bits_needed, randfunc=randfunc) return (norm_candidate + min_inclusive)
null
null
null
a random integer within a given internal
codeqa
def random range **kwargs min inclusive kwargs pop 'min inclusive' None max inclusive kwargs pop 'max inclusive' None max exclusive kwargs pop 'max exclusive' None randfunc kwargs pop 'randfunc' None if kwargs raise Value Error ' Unknownkeywords ' + str kwargs keys if None not in max inclusive max exclusive raise Value Error 'max inclusiveandmax exclusivecannotbebothspecified' if max exclusive is not None max inclusive max exclusive - 1 if None in min inclusive max inclusive raise Value Error ' Missingkeywordtoidentifytheinterval' if randfunc is None randfunc Random new readnorm maximum max inclusive - min inclusive bits needed Integer norm maximum size in bits norm candidate -1 while not 0 < norm candidate < norm maximum norm candidate random max bits bits needed randfunc randfunc return norm candidate + min inclusive
null
null
null
null
Question: What does the code generate ? Code: def _random_range(**kwargs): min_inclusive = kwargs.pop('min_inclusive', None) max_inclusive = kwargs.pop('max_inclusive', None) max_exclusive = kwargs.pop('max_exclusive', None) randfunc = kwargs.pop('randfunc', None) if kwargs: raise ValueError(('Unknown keywords: ' + str(kwargs.keys))) if (None not in (max_inclusive, max_exclusive)): raise ValueError('max_inclusive and max_exclusive cannot be both specified') if (max_exclusive is not None): max_inclusive = (max_exclusive - 1) if (None in (min_inclusive, max_inclusive)): raise ValueError('Missing keyword to identify the interval') if (randfunc is None): randfunc = Random.new().read norm_maximum = (max_inclusive - min_inclusive) bits_needed = Integer(norm_maximum).size_in_bits() norm_candidate = (-1) while (not (0 <= norm_candidate <= norm_maximum)): norm_candidate = _random(max_bits=bits_needed, randfunc=randfunc) return (norm_candidate + min_inclusive)
null
null
null
What does the code delete ?
def delslice(model, start, end): if isinstance(model, PyListModel): del model[start:end] elif isinstance(model, QAbstractItemModel): model.removeRows(start, (end - start)) else: raise TypeError(type(model))
null
null
null
the start
codeqa
def delslice model start end if isinstance model Py List Model del model[start end]elif isinstance model Q Abstract Item Model model remove Rows start end - start else raise Type Error type model
null
null
null
null
Question: What does the code delete ? Code: def delslice(model, start, end): if isinstance(model, PyListModel): del model[start:end] elif isinstance(model, QAbstractItemModel): model.removeRows(start, (end - start)) else: raise TypeError(type(model))
null
null
null
What does the code generate ?
def rand_text_alpha(length, bad=''): chars = (upperAlpha + lowerAlpha) return rand_base(length, bad, set(chars))
null
null
null
a random string with alpha chars
codeqa
def rand text alpha length bad '' chars upper Alpha + lower Alpha return rand base length bad set chars
null
null
null
null
Question: What does the code generate ? Code: def rand_text_alpha(length, bad=''): chars = (upperAlpha + lowerAlpha) return rand_base(length, bad, set(chars))
null
null
null
What does this method return ?
def follow_link(connection, link): if link: return connection.follow_link(link) else: return None
null
null
null
the entity of the element which link points to
codeqa
def follow link connection link if link return connection follow link link else return None
null
null
null
null
Question: What does this method return ? Code: def follow_link(connection, link): if link: return connection.follow_link(link) else: return None
null
null
null
What does the code open using the given name ?
def _open_logfile(logfile_base_name): timestamp = int(time.time()) while True: logfile_name = ('%s.%d-%d.gz' % (logfile_base_name, timestamp, os.getpid())) if (not os.path.exists(logfile_name)): break timestamp += 1 logfile = gzip.GzipFile(logfile_name, 'w') return logfile
null
null
null
an output file
codeqa
def open logfile logfile base name timestamp int time time while True logfile name '%s %d-%d gz' % logfile base name timestamp os getpid if not os path exists logfile name breaktimestamp + 1logfile gzip Gzip File logfile name 'w' return logfile
null
null
null
null
Question: What does the code open using the given name ? Code: def _open_logfile(logfile_base_name): timestamp = int(time.time()) while True: logfile_name = ('%s.%d-%d.gz' % (logfile_base_name, timestamp, os.getpid())) if (not os.path.exists(logfile_name)): break timestamp += 1 logfile = gzip.GzipFile(logfile_name, 'w') return logfile
null
null
null
How does the code open an output file ?
def _open_logfile(logfile_base_name): timestamp = int(time.time()) while True: logfile_name = ('%s.%d-%d.gz' % (logfile_base_name, timestamp, os.getpid())) if (not os.path.exists(logfile_name)): break timestamp += 1 logfile = gzip.GzipFile(logfile_name, 'w') return logfile
null
null
null
using the given name
codeqa
def open logfile logfile base name timestamp int time time while True logfile name '%s %d-%d gz' % logfile base name timestamp os getpid if not os path exists logfile name breaktimestamp + 1logfile gzip Gzip File logfile name 'w' return logfile
null
null
null
null
Question: How does the code open an output file ? Code: def _open_logfile(logfile_base_name): timestamp = int(time.time()) while True: logfile_name = ('%s.%d-%d.gz' % (logfile_base_name, timestamp, os.getpid())) if (not os.path.exists(logfile_name)): break timestamp += 1 logfile = gzip.GzipFile(logfile_name, 'w') return logfile
null
null
null
What does the code remove ?
def additions_remove(**kwargs): kernel = __grains__.get('kernel', '') if (kernel == 'Linux'): ret = _additions_remove_linux() if (not ret): ret = _additions_remove_use_cd(**kwargs) return ret
null
null
null
virtualbox guest additions
codeqa
def additions remove **kwargs kernel grains get 'kernel' '' if kernel ' Linux' ret additions remove linux if not ret ret additions remove use cd **kwargs return ret
null
null
null
null
Question: What does the code remove ? Code: def additions_remove(**kwargs): kernel = __grains__.get('kernel', '') if (kernel == 'Linux'): ret = _additions_remove_linux() if (not ret): ret = _additions_remove_use_cd(**kwargs) return ret
null
null
null
What did the code set ?
def _set_gps_from_zone(kwargs, location, zone): if (zone is not None): kwargs['gps'] = (zone.attributes['latitude'], zone.attributes['longitude']) kwargs['gps_accuracy'] = zone.attributes['radius'] kwargs['location_name'] = location return kwargs
null
null
null
the see parameters from the zone parameters
codeqa
def set gps from zone kwargs location zone if zone is not None kwargs['gps'] zone attributes['latitude'] zone attributes['longitude'] kwargs['gps accuracy'] zone attributes['radius']kwargs['location name'] locationreturn kwargs
null
null
null
null
Question: What did the code set ? Code: def _set_gps_from_zone(kwargs, location, zone): if (zone is not None): kwargs['gps'] = (zone.attributes['latitude'], zone.attributes['longitude']) kwargs['gps_accuracy'] = zone.attributes['radius'] kwargs['location_name'] = location return kwargs
null
null
null
What do windows functions return ?
def ErrCheckHandle(result, func, args): if (not result): raise WinError() return AutoHANDLE(result)
null
null
null
a handle
codeqa
def Err Check Handle result func args if not result raise Win Error return Auto HANDLE result
null
null
null
null
Question: What do windows functions return ? Code: def ErrCheckHandle(result, func, args): if (not result): raise WinError() return AutoHANDLE(result)
null
null
null
What return a handle ?
def ErrCheckHandle(result, func, args): if (not result): raise WinError() return AutoHANDLE(result)
null
null
null
windows functions
codeqa
def Err Check Handle result func args if not result raise Win Error return Auto HANDLE result
null
null
null
null
Question: What return a handle ? Code: def ErrCheckHandle(result, func, args): if (not result): raise WinError() return AutoHANDLE(result)
null
null
null
What does the code get ?
def _selfOfMethod(methodObject): if _PY3: return methodObject.__self__ return methodObject.im_self
null
null
null
the object that a bound method is bound to
codeqa
def self Of Method method Object if PY 3 return method Object self return method Object im self
null
null
null
null
Question: What does the code get ? Code: def _selfOfMethod(methodObject): if _PY3: return methodObject.__self__ return methodObject.im_self
null
null
null
When does a callable to be executed register ?
def register_adapter(mod, func): if (not hasattr(func, '__call__')): raise TypeError('func must be callable') imports.when_imported(mod, func)
null
null
null
when a module is imported
codeqa
def register adapter mod func if not hasattr func ' call ' raise Type Error 'funcmustbecallable' imports when imported mod func
null
null
null
null
Question: When does a callable to be executed register ? Code: def register_adapter(mod, func): if (not hasattr(func, '__call__')): raise TypeError('func must be callable') imports.when_imported(mod, func)
null
null
null
When be a callable executed ?
def register_adapter(mod, func): if (not hasattr(func, '__call__')): raise TypeError('func must be callable') imports.when_imported(mod, func)
null
null
null
when a module is imported
codeqa
def register adapter mod func if not hasattr func ' call ' raise Type Error 'funcmustbecallable' imports when imported mod func
null
null
null
null
Question: When be a callable executed ? Code: def register_adapter(mod, func): if (not hasattr(func, '__call__')): raise TypeError('func must be callable') imports.when_imported(mod, func)
null
null
null
What does the code find ?
def _getSlotValue(name, slotData, default=None): for slotFrame in slotData[::(-1)]: if ((slotFrame is not None) and (name in slotFrame)): return slotFrame[name] else: if (default is not None): return default raise UnfilledSlot(name)
null
null
null
the value of the named slot in the given stack of slot data
codeqa
def get Slot Value name slot Data default None for slot Frame in slot Data[ -1 ] if slot Frame is not None and name in slot Frame return slot Frame[name]else if default is not None return defaultraise Unfilled Slot name
null
null
null
null
Question: What does the code find ? Code: def _getSlotValue(name, slotData, default=None): for slotFrame in slotData[::(-1)]: if ((slotFrame is not None) and (name in slotFrame)): return slotFrame[name] else: if (default is not None): return default raise UnfilledSlot(name)
null
null
null
What does the code remove ?
def uninstall(packages, purge=False, options=None): manager = MANAGER command = ('purge' if purge else 'remove') if (options is None): options = [] if (not isinstance(packages, basestring)): packages = ' '.join(packages) options.append('--assume-yes') options = ' '.join(options) cmd = ('%(manager)s %(command)s %(options)s %(packages)s' % locals()) run_as_root(cmd, pty=False)
null
null
null
one or more packages
codeqa
def uninstall packages purge False options None manager MANAGE Rcommand 'purge' if purge else 'remove' if options is None options []if not isinstance packages basestring packages '' join packages options append '--assume-yes' options '' join options cmd '% manager s% command s% options s% packages s' % locals run as root cmd pty False
null
null
null
null
Question: What does the code remove ? Code: def uninstall(packages, purge=False, options=None): manager = MANAGER command = ('purge' if purge else 'remove') if (options is None): options = [] if (not isinstance(packages, basestring)): packages = ' '.join(packages) options.append('--assume-yes') options = ' '.join(options) cmd = ('%(manager)s %(command)s %(options)s %(packages)s' % locals()) run_as_root(cmd, pty=False)
null
null
null
What do you read ?
def file_upload_quota_broken(request): response = file_upload_echo(request) request.upload_handlers.insert(0, QuotaUploadHandler()) return response
null
null
null
files
codeqa
def file upload quota broken request response file upload echo request request upload handlers insert 0 Quota Upload Handler return response
null
null
null
null
Question: What do you read ? Code: def file_upload_quota_broken(request): response = file_upload_echo(request) request.upload_handlers.insert(0, QuotaUploadHandler()) return response
null
null
null
Do you change handlers after reading files ?
def file_upload_quota_broken(request): response = file_upload_echo(request) request.upload_handlers.insert(0, QuotaUploadHandler()) return response
null
null
null
No
codeqa
def file upload quota broken request response file upload echo request request upload handlers insert 0 Quota Upload Handler return response
null
null
null
null
Question: Do you change handlers after reading files ? Code: def file_upload_quota_broken(request): response = file_upload_echo(request) request.upload_handlers.insert(0, QuotaUploadHandler()) return response
null
null
null
How do a locale set ?
@contextmanager def set_locale(new_locale, lc_var=locale.LC_ALL): current_locale = locale.getlocale() try: locale.setlocale(lc_var, new_locale) try: normalized_locale = locale.getlocale() except ValueError: (yield new_locale) else: if all(((lc is not None) for lc in normalized_locale)): (yield '.'.join(normalized_locale)) else: (yield new_locale) finally: locale.setlocale(lc_var, current_locale)
null
null
null
temporarily
codeqa
@contextmanagerdef set locale new locale lc var locale LC ALL current locale locale getlocale try locale setlocale lc var new locale try normalized locale locale getlocale except Value Error yield new locale else if all lc is not None for lc in normalized locale yield ' ' join normalized locale else yield new locale finally locale setlocale lc var current locale
null
null
null
null
Question: How do a locale set ? Code: @contextmanager def set_locale(new_locale, lc_var=locale.LC_ALL): current_locale = locale.getlocale() try: locale.setlocale(lc_var, new_locale) try: normalized_locale = locale.getlocale() except ValueError: (yield new_locale) else: if all(((lc is not None) for lc in normalized_locale)): (yield '.'.join(normalized_locale)) else: (yield new_locale) finally: locale.setlocale(lc_var, current_locale)
null
null
null
What does the code create on file f ?
def mmap_read(f, sz=0, close=True): return _mmap_do(f, sz, mmap.MAP_PRIVATE, mmap.PROT_READ, close)
null
null
null
a read - only memory mapped region
codeqa
def mmap read f sz 0 close True return mmap do f sz mmap MAP PRIVATE mmap PROT READ close
null
null
null
null
Question: What does the code create on file f ? Code: def mmap_read(f, sz=0, close=True): return _mmap_do(f, sz, mmap.MAP_PRIVATE, mmap.PROT_READ, close)
null
null
null
Where does the code create a read - only memory mapped region ?
def mmap_read(f, sz=0, close=True): return _mmap_do(f, sz, mmap.MAP_PRIVATE, mmap.PROT_READ, close)
null
null
null
on file f
codeqa
def mmap read f sz 0 close True return mmap do f sz mmap MAP PRIVATE mmap PROT READ close
null
null
null
null
Question: Where does the code create a read - only memory mapped region ? Code: def mmap_read(f, sz=0, close=True): return _mmap_do(f, sz, mmap.MAP_PRIVATE, mmap.PROT_READ, close)
null
null
null
What is containing all emojis with their name and filename ?
def collect_emojis(): emojis = dict() full_path = os.path.join(_basedir, 'static', 'emoji') if (not os.path.exists(full_path)): return emojis for emoji in os.listdir(full_path): (name, ending) = emoji.split('.') if (ending in ['png', 'gif', 'jpg', 'jpeg']): emojis[name] = emoji return emojis
null
null
null
a dictionary
codeqa
def collect emojis emojis dict full path os path join basedir 'static' 'emoji' if not os path exists full path return emojisfor emoji in os listdir full path name ending emoji split ' ' if ending in ['png' 'gif' 'jpg' 'jpeg'] emojis[name] emojireturn emojis
null
null
null
null
Question: What is containing all emojis with their name and filename ? Code: def collect_emojis(): emojis = dict() full_path = os.path.join(_basedir, 'static', 'emoji') if (not os.path.exists(full_path)): return emojis for emoji in os.listdir(full_path): (name, ending) = emoji.split('.') if (ending in ['png', 'gif', 'jpg', 'jpeg']): emojis[name] = emoji return emojis
null
null
null
What does the code decode ?
def html_unquote(s, encoding=None): if isinstance(s, six.binary_type): s = s.decode((encoding or default_encoding)) return _unquote_re.sub(_entity_subber, s)
null
null
null
the value
codeqa
def html unquote s encoding None if isinstance s six binary type s s decode encoding or default encoding return unquote re sub entity subber s
null
null
null
null
Question: What does the code decode ? Code: def html_unquote(s, encoding=None): if isinstance(s, six.binary_type): s = s.decode((encoding or default_encoding)) return _unquote_re.sub(_entity_subber, s)
null
null
null
How did dictionary insertion nest ?
def insert_into(target, keys, value): for key in keys[:(-1)]: if (key not in target): target[key] = {} target = target[key] target[keys[(-1)]] = value
null
null
null
code
codeqa
def insert into target keys value for key in keys[ -1 ] if key not in target target[key] {}target target[key]target[keys[ -1 ]] value
null
null
null
null
Question: How did dictionary insertion nest ? Code: def insert_into(target, keys, value): for key in keys[:(-1)]: if (key not in target): target[key] = {} target = target[key] target[keys[(-1)]] = value
null
null
null
What do they provide ?
def get_confirmation(question): while True: response = input((u'%s (y/n): ' % question)).lower() if (re.match(u'^[yn]', response) is not None): break print((u"Incorrect option '%s'" % response)) return (response[0] == u'y')
null
null
null
an answer that starts with either a y or an n
codeqa
def get confirmation question while True response input u'%s y/n ' % question lower if re match u'^[yn]' response is not None breakprint u" Incorrectoption'%s'" % response return response[ 0 ] u'y'
null
null
null
null
Question: What do they provide ? Code: def get_confirmation(question): while True: response = input((u'%s (y/n): ' % question)).lower() if (re.match(u'^[yn]', response) is not None): break print((u"Incorrect option '%s'" % response)) return (response[0] == u'y')
null
null
null
Who provide an answer that starts with either a y or an n ?
def get_confirmation(question): while True: response = input((u'%s (y/n): ' % question)).lower() if (re.match(u'^[yn]', response) is not None): break print((u"Incorrect option '%s'" % response)) return (response[0] == u'y')
null
null
null
they
codeqa
def get confirmation question while True response input u'%s y/n ' % question lower if re match u'^[yn]' response is not None breakprint u" Incorrectoption'%s'" % response return response[ 0 ] u'y'
null
null
null
null
Question: Who provide an answer that starts with either a y or an n ? Code: def get_confirmation(question): while True: response = input((u'%s (y/n): ' % question)).lower() if (re.match(u'^[yn]', response) is not None): break print((u"Incorrect option '%s'" % response)) return (response[0] == u'y')
null
null
null
What has the socket been set ?
def get_socket_inherit(socket): try: if iswindows: import win32api, win32con flags = win32api.GetHandleInformation(socket.fileno()) return bool((flags & win32con.HANDLE_FLAG_INHERIT)) else: import fcntl flags = fcntl.fcntl(socket.fileno(), fcntl.F_GETFD) return (not bool((flags & fcntl.FD_CLOEXEC))) except: import traceback traceback.print_exc()
null
null
null
to allow inheritance across forks and execs to child processes
codeqa
def get socket inherit socket try if iswindows import win 32 api win 32 conflags win 32 api Get Handle Information socket fileno return bool flags & win 32 con HANDLE FLAG INHERIT else import fcntlflags fcntl fcntl socket fileno fcntl F GETFD return not bool flags & fcntl FD CLOEXEC except import tracebacktraceback print exc
null
null
null
null
Question: What has the socket been set ? Code: def get_socket_inherit(socket): try: if iswindows: import win32api, win32con flags = win32api.GetHandleInformation(socket.fileno()) return bool((flags & win32con.HANDLE_FLAG_INHERIT)) else: import fcntl flags = fcntl.fcntl(socket.fileno(), fcntl.F_GETFD) return (not bool((flags & fcntl.FD_CLOEXEC))) except: import traceback traceback.print_exc()