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 create ?
def create_comment(request, comment_data): thread_id = comment_data.get('thread_id') if (not thread_id): raise ValidationError({'thread_id': ['This field is required.']}) (cc_thread, context) = _get_thread_and_context(request, thread_id) if cc_thread['closed']: raise PermissionDenied _check_initializable_comment_fields(comment_data, context) serializer = CommentSerializer(data=comment_data, context=context) actions_form = CommentActionsForm(comment_data) if (not (serializer.is_valid() and actions_form.is_valid())): raise ValidationError(dict((serializer.errors.items() + actions_form.errors.items()))) serializer.save() cc_comment = serializer.instance comment_created.send(sender=None, user=request.user, post=cc_comment) api_comment = serializer.data _do_extra_actions(api_comment, cc_comment, comment_data.keys(), actions_form, context, request) track_comment_created_event(request, context['course'], cc_comment, cc_thread['commentable_id'], followed=False) return api_comment
null
null
null
a comment
codeqa
def create comment request comment data thread id comment data get 'thread id' if not thread id raise Validation Error {'thread id' [' Thisfieldisrequired ']} cc thread context get thread and context request thread id if cc thread['closed'] raise Permission Denied check initializable comment fields comment data context serializer Comment Serializer data comment data context context actions form Comment Actions Form comment data if not serializer is valid and actions form is valid raise Validation Error dict serializer errors items + actions form errors items serializer save cc comment serializer instancecomment created send sender None user request user post cc comment api comment serializer data do extra actions api comment cc comment comment data keys actions form context request track comment created event request context['course'] cc comment cc thread['commentable id'] followed False return api comment
null
null
null
null
Question: What does the code create ? Code: def create_comment(request, comment_data): thread_id = comment_data.get('thread_id') if (not thread_id): raise ValidationError({'thread_id': ['This field is required.']}) (cc_thread, context) = _get_thread_and_context(request, thread_id) if cc_thread['closed']: raise PermissionDenied _check_initializable_comment_fields(comment_data, context) serializer = CommentSerializer(data=comment_data, context=context) actions_form = CommentActionsForm(comment_data) if (not (serializer.is_valid() and actions_form.is_valid())): raise ValidationError(dict((serializer.errors.items() + actions_form.errors.items()))) serializer.save() cc_comment = serializer.instance comment_created.send(sender=None, user=request.user, post=cc_comment) api_comment = serializer.data _do_extra_actions(api_comment, cc_comment, comment_data.keys(), actions_form, context, request) track_comment_created_event(request, context['course'], cc_comment, cc_thread['commentable_id'], followed=False) return api_comment
null
null
null
What do annotations link to a particular mapping ?
def _orm_deannotate(element): return sql_util._deep_deannotate(element, values=('_orm_adapt', 'parententity'))
null
null
null
a column
codeqa
def orm deannotate element return sql util deep deannotate element values ' orm adapt' 'parententity'
null
null
null
null
Question: What do annotations link to a particular mapping ? Code: def _orm_deannotate(element): return sql_util._deep_deannotate(element, values=('_orm_adapt', 'parententity'))
null
null
null
What does the code remove ?
def _orm_deannotate(element): return sql_util._deep_deannotate(element, values=('_orm_adapt', 'parententity'))
null
null
null
annotations that link a column to a particular mapping
codeqa
def orm deannotate element return sql util deep deannotate element values ' orm adapt' 'parententity'
null
null
null
null
Question: What does the code remove ? Code: def _orm_deannotate(element): return sql_util._deep_deannotate(element, values=('_orm_adapt', 'parententity'))
null
null
null
What link a column to a particular mapping ?
def _orm_deannotate(element): return sql_util._deep_deannotate(element, values=('_orm_adapt', 'parententity'))
null
null
null
annotations
codeqa
def orm deannotate element return sql util deep deannotate element values ' orm adapt' 'parententity'
null
null
null
null
Question: What link a column to a particular mapping ? Code: def _orm_deannotate(element): return sql_util._deep_deannotate(element, values=('_orm_adapt', 'parententity'))
null
null
null
What do internal helper copy from another future ?
def _copy_future_state(source, dest): assert source.done() if dest.cancelled(): return assert (not dest.done()) if source.cancelled(): dest.cancel() else: exception = source.exception() if (exception is not None): dest.set_exception(exception) else: result = source.result() dest.set_result(result)
null
null
null
state
codeqa
def copy future state source dest assert source done if dest cancelled returnassert not dest done if source cancelled dest cancel else exception source exception if exception is not None dest set exception exception else result source result dest set result result
null
null
null
null
Question: What do internal helper copy from another future ? Code: def _copy_future_state(source, dest): assert source.done() if dest.cancelled(): return assert (not dest.done()) if source.cancelled(): dest.cancel() else: exception = source.exception() if (exception is not None): dest.set_exception(exception) else: result = source.result() dest.set_result(result)
null
null
null
What does the code remove from the string ?
def strip_ansi_codes(s): return re.sub(u'\x1b\\[([0-9]+)(;[0-9]+)*m', u'', s)
null
null
null
ansi color codes
codeqa
def strip ansi codes s return re sub u'\x 1 b\\[ [0 - 9 ]+ [0 - 9 ]+ *m' u'' s
null
null
null
null
Question: What does the code remove from the string ? Code: def strip_ansi_codes(s): return re.sub(u'\x1b\\[([0-9]+)(;[0-9]+)*m', u'', s)
null
null
null
What does the code get ?
def getNewDerivation(elementNode): return HeightmapDerivation(elementNode)
null
null
null
new derivation
codeqa
def get New Derivation element Node return Heightmap Derivation element Node
null
null
null
null
Question: What does the code get ? Code: def getNewDerivation(elementNode): return HeightmapDerivation(elementNode)
null
null
null
What does the code get ?
def getBottomPath(path): bottom = 999999999.9 for point in path: bottom = min(bottom, point.z) return bottom
null
null
null
the bottom of the path
codeqa
def get Bottom Path path bottom 999999999 9for point in path bottom min bottom point z return bottom
null
null
null
null
Question: What does the code get ? Code: def getBottomPath(path): bottom = 999999999.9 for point in path: bottom = min(bottom, point.z) return bottom
null
null
null
What does the code get ?
def _get_installed_models(table_list): from django.db import models all_models = [] for app in models.get_apps(): for model in models.get_models(app): all_models.append(model) return set([m for m in all_models if (m._meta.db_table in table_list)])
null
null
null
a set of all models that are installed
codeqa
def get installed models table list from django db import modelsall models []for app in models get apps for model in models get models app all models append model return set [m for m in all models if m meta db table in table list ]
null
null
null
null
Question: What does the code get ? Code: def _get_installed_models(table_list): from django.db import models all_models = [] for app in models.get_apps(): for model in models.get_models(app): all_models.append(model) return set([m for m in all_models if (m._meta.db_table in table_list)])
null
null
null
What does the code turn into a locale name ?
def to_locale(language, to_lower=False): p = language.find('-') if (p >= 0): if to_lower: return ((language[:p].lower() + '_') + language[(p + 1):].lower()) else: if (len(language[(p + 1):]) > 2): return (((language[:p].lower() + '_') + language[(p + 1)].upper()) + language[(p + 2):].lower()) return ((language[:p].lower() + '_') + language[(p + 1):].upper()) else: return language.lower()
null
null
null
a language name
codeqa
def to locale language to lower False p language find '-' if p > 0 if to lower return language[ p] lower + ' ' + language[ p + 1 ] lower else if len language[ p + 1 ] > 2 return language[ p] lower + ' ' + language[ p + 1 ] upper + language[ p + 2 ] lower return language[ p] lower + ' ' + language[ p + 1 ] upper else return language lower
null
null
null
null
Question: What does the code turn into a locale name ? Code: def to_locale(language, to_lower=False): p = language.find('-') if (p >= 0): if to_lower: return ((language[:p].lower() + '_') + language[(p + 1):].lower()) else: if (len(language[(p + 1):]) > 2): return (((language[:p].lower() + '_') + language[(p + 1)].upper()) + language[(p + 2):].lower()) return ((language[:p].lower() + '_') + language[(p + 1):].upper()) else: return language.lower()
null
null
null
What do admins control ?
def subscription(): output = s3_rest_controller() return output
null
null
null
subscriptions for people
codeqa
def subscription output s3 rest controller return output
null
null
null
null
Question: What do admins control ? Code: def subscription(): output = s3_rest_controller() return output
null
null
null
What controls subscriptions for people ?
def subscription(): output = s3_rest_controller() return output
null
null
null
admins
codeqa
def subscription output s3 rest controller return output
null
null
null
null
Question: What controls subscriptions for people ? Code: def subscription(): output = s3_rest_controller() return output
null
null
null
When do process run ?
def set_process_title(progname, info=None): proctitle = ('[%s]' % progname) proctitle = (('%s %s' % (proctitle, info)) if info else proctitle) if _setproctitle: _setproctitle.setproctitle(proctitle) return proctitle
null
null
null
currently
codeqa
def set process title progname info None proctitle '[%s]' % progname proctitle '%s%s' % proctitle info if info else proctitle if setproctitle setproctitle setproctitle proctitle return proctitle
null
null
null
null
Question: When do process run ? Code: def set_process_title(progname, info=None): proctitle = ('[%s]' % progname) proctitle = (('%s %s' % (proctitle, info)) if info else proctitle) if _setproctitle: _setproctitle.setproctitle(proctitle) return proctitle
null
null
null
What does the code get ?
def mac(interface): with settings(hide('running', 'stdout')): res = sudo(("/sbin/ifconfig %(interface)s | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'" % locals())) return res
null
null
null
the mac address assigned to an interface
codeqa
def mac interface with settings hide 'running' 'stdout' res sudo "/sbin/ifconfig% interface s grep-o-E' [[ xdigit ]]{ 1 2} {5 }[[ xdigit ]]{ 1 2}'" % locals return res
null
null
null
null
Question: What does the code get ? Code: def mac(interface): with settings(hide('running', 'stdout')): res = sudo(("/sbin/ifconfig %(interface)s | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'" % locals())) return res
null
null
null
What does the code delete ?
def snapshot_metadata_delete(context, snapshot_id, key): IMPL.snapshot_metadata_delete(context, snapshot_id, key)
null
null
null
the given metadata item
codeqa
def snapshot metadata delete context snapshot id key IMPL snapshot metadata delete context snapshot id key
null
null
null
null
Question: What does the code delete ? Code: def snapshot_metadata_delete(context, snapshot_id, key): IMPL.snapshot_metadata_delete(context, snapshot_id, key)
null
null
null
How do content return ?
def _get_file(src): try: if (('://' in src) or (src[0:2] == '//')): response = urllib2.urlopen(src) return response.read() else: with open(src, 'rb') as fh: return fh.read() except Exception as e: raise RuntimeError('Error generating base64image: {}'.format(e))
null
null
null
from local or remote file
codeqa
def get file src try if ' //' in src or src[ 0 2] '//' response urllib 2 urlopen src return response read else with open src 'rb' as fh return fh read except Exception as e raise Runtime Error ' Errorgeneratingbase 64 image {}' format e
null
null
null
null
Question: How do content return ? Code: def _get_file(src): try: if (('://' in src) or (src[0:2] == '//')): response = urllib2.urlopen(src) return response.read() else: with open(src, 'rb') as fh: return fh.read() except Exception as e: raise RuntimeError('Error generating base64image: {}'.format(e))
null
null
null
What does the code stop ?
def stop(jail=''): cmd = 'service jail onestop {0}'.format(jail) return (not __salt__['cmd.retcode'](cmd))
null
null
null
the specified jail or all
codeqa
def stop jail '' cmd 'servicejailonestop{ 0 }' format jail return not salt ['cmd retcode'] cmd
null
null
null
null
Question: What does the code stop ? Code: def stop(jail=''): cmd = 'service jail onestop {0}'.format(jail) return (not __salt__['cmd.retcode'](cmd))
null
null
null
How do to destroy the dataset recursive try ?
def volume_absent(name, force=False, recursive=False): return _absent(name, 'volume', force, recursive)
null
null
null
harder
codeqa
def volume absent name force False recursive False return absent name 'volume' force recursive
null
null
null
null
Question: How do to destroy the dataset recursive try ? Code: def volume_absent(name, force=False, recursive=False): return _absent(name, 'volume', force, recursive)
null
null
null
What does the code ensure ?
def volume_absent(name, force=False, recursive=False): return _absent(name, 'volume', force, recursive)
null
null
null
volume is absent on the system name
codeqa
def volume absent name force False recursive False return absent name 'volume' force recursive
null
null
null
null
Question: What does the code ensure ? Code: def volume_absent(name, force=False, recursive=False): return _absent(name, 'volume', force, recursive)
null
null
null
How do the dataset destroy ?
def volume_absent(name, force=False, recursive=False): return _absent(name, 'volume', force, recursive)
null
null
null
recursive
codeqa
def volume absent name force False recursive False return absent name 'volume' force recursive
null
null
null
null
Question: How do the dataset destroy ? Code: def volume_absent(name, force=False, recursive=False): return _absent(name, 'volume', force, recursive)
null
null
null
For what purpose does the code update the glance metadata ?
@require_context @require_snapshot_exists def volume_glance_metadata_copy_to_snapshot(context, snapshot_id, volume_id): session = get_session() with session.begin(): metadata = _volume_glance_metadata_get(context, volume_id, session=session) for meta in metadata: vol_glance_metadata = models.VolumeGlanceMetadata() vol_glance_metadata.snapshot_id = snapshot_id vol_glance_metadata.key = meta['key'] vol_glance_metadata.value = meta['value'] vol_glance_metadata.save(session=session)
null
null
null
for a snapshot
codeqa
@require context@require snapshot existsdef volume glance metadata copy to snapshot context snapshot id volume id session get session with session begin metadata volume glance metadata get context volume id session session for meta in metadata vol glance metadata models Volume Glance Metadata vol glance metadata snapshot id snapshot idvol glance metadata key meta['key']vol glance metadata value meta['value']vol glance metadata save session session
null
null
null
null
Question: For what purpose does the code update the glance metadata ? Code: @require_context @require_snapshot_exists def volume_glance_metadata_copy_to_snapshot(context, snapshot_id, volume_id): session = get_session() with session.begin(): metadata = _volume_glance_metadata_get(context, volume_id, session=session) for meta in metadata: vol_glance_metadata = models.VolumeGlanceMetadata() vol_glance_metadata.snapshot_id = snapshot_id vol_glance_metadata.key = meta['key'] vol_glance_metadata.value = meta['value'] vol_glance_metadata.save(session=session)
null
null
null
What does the code update for a snapshot ?
@require_context @require_snapshot_exists def volume_glance_metadata_copy_to_snapshot(context, snapshot_id, volume_id): session = get_session() with session.begin(): metadata = _volume_glance_metadata_get(context, volume_id, session=session) for meta in metadata: vol_glance_metadata = models.VolumeGlanceMetadata() vol_glance_metadata.snapshot_id = snapshot_id vol_glance_metadata.key = meta['key'] vol_glance_metadata.value = meta['value'] vol_glance_metadata.save(session=session)
null
null
null
the glance metadata
codeqa
@require context@require snapshot existsdef volume glance metadata copy to snapshot context snapshot id volume id session get session with session begin metadata volume glance metadata get context volume id session session for meta in metadata vol glance metadata models Volume Glance Metadata vol glance metadata snapshot id snapshot idvol glance metadata key meta['key']vol glance metadata value meta['value']vol glance metadata save session session
null
null
null
null
Question: What does the code update for a snapshot ? Code: @require_context @require_snapshot_exists def volume_glance_metadata_copy_to_snapshot(context, snapshot_id, volume_id): session = get_session() with session.begin(): metadata = _volume_glance_metadata_get(context, volume_id, session=session) for meta in metadata: vol_glance_metadata = models.VolumeGlanceMetadata() vol_glance_metadata.snapshot_id = snapshot_id vol_glance_metadata.key = meta['key'] vol_glance_metadata.value = meta['value'] vol_glance_metadata.save(session=session)
null
null
null
How do over all objects of the same class iterate ?
def iter_all(class_name): for (cls, wdict) in six.iteritems(live_refs): if (cls.__name__ == class_name): return six.iterkeys(wdict)
null
null
null
by its class name
codeqa
def iter all class name for cls wdict in six iteritems live refs if cls name class name return six iterkeys wdict
null
null
null
null
Question: How do over all objects of the same class iterate ? Code: def iter_all(class_name): for (cls, wdict) in six.iteritems(live_refs): if (cls.__name__ == class_name): return six.iterkeys(wdict)
null
null
null
What did the code set ?
def set_enabled_auth_backend(backend_id): siteconfig = SiteConfiguration.objects.get_current() siteconfig.set(u'auth_backend', backend_id)
null
null
null
the authentication backend to be used
codeqa
def set enabled auth backend backend id siteconfig Site Configuration objects get current siteconfig set u'auth backend' backend id
null
null
null
null
Question: What did the code set ? Code: def set_enabled_auth_backend(backend_id): siteconfig = SiteConfiguration.objects.get_current() siteconfig.set(u'auth_backend', backend_id)
null
null
null
What does the code stop ?
def _patch_stopall(): for patch in list(_patch._active_patches): patch.stop()
null
null
null
all active patches
codeqa
def patch stopall for patch in list patch active patches patch stop
null
null
null
null
Question: What does the code stop ? Code: def _patch_stopall(): for patch in list(_patch._active_patches): patch.stop()
null
null
null
What does the code resolve ?
def _decision_relationships(workflow, parent, child_el): for switch in child_el: if (not isinstance(switch.tag, basestring)): continue for case in switch: if (not isinstance(case.tag, basestring)): continue if ('to' not in case.attrib): raise RuntimeError((_("Node %s has a link that is missing 'to' attribute.") % parent.name)) to = case.attrib['to'] try: child = Node.objects.get(workflow=workflow, name=to) except Node.DoesNotExist as e: raise RuntimeError((_('Node %s has not been defined.') % to)) if (etree.QName(case).localname == 'default'): name = 'default' obj = Link.objects.create(name=name, parent=parent, child=child) else: name = 'start' comment = case.text.strip() obj = Link.objects.create(name=name, parent=parent, child=child, comment=comment) obj.save()
null
null
null
the switch statement like nature of decision nodes
codeqa
def decision relationships workflow parent child el for switch in child el if not isinstance switch tag basestring continuefor case in switch if not isinstance case tag basestring continueif 'to' not in case attrib raise Runtime Error " Node%shasalinkthatismissing'to'attribute " % parent name to case attrib['to']try child Node objects get workflow workflow name to except Node Does Not Exist as e raise Runtime Error ' Node%shasnotbeendefined ' % to if etree Q Name case localname 'default' name 'default'obj Link objects create name name parent parent child child else name 'start'comment case text strip obj Link objects create name name parent parent child child comment comment obj save
null
null
null
null
Question: What does the code resolve ? Code: def _decision_relationships(workflow, parent, child_el): for switch in child_el: if (not isinstance(switch.tag, basestring)): continue for case in switch: if (not isinstance(case.tag, basestring)): continue if ('to' not in case.attrib): raise RuntimeError((_("Node %s has a link that is missing 'to' attribute.") % parent.name)) to = case.attrib['to'] try: child = Node.objects.get(workflow=workflow, name=to) except Node.DoesNotExist as e: raise RuntimeError((_('Node %s has not been defined.') % to)) if (etree.QName(case).localname == 'default'): name = 'default' obj = Link.objects.create(name=name, parent=parent, child=child) else: name = 'start' comment = case.text.strip() obj = Link.objects.create(name=name, parent=parent, child=child, comment=comment) obj.save()
null
null
null
What does the code delete from spacewalk ?
def deleteAllGroups(server): try: (client, key) = _get_session(server) except Exception as exc: err_msg = 'Exception raised when connecting to spacewalk server ({0}): {1}'.format(server, exc) log.error(err_msg) return {'Error': err_msg} groups = client.systemgroup.listAllGroups(key) deleted_groups = [] failed_groups = [] for group in groups: if (client.systemgroup.delete(key, group['name']) == 1): deleted_groups.append(group['name']) else: failed_groups.append(group['name']) ret = {'deleted': deleted_groups} if failed_groups: ret['failed'] = failed_groups return ret
null
null
null
all server groups
codeqa
def delete All Groups server try client key get session server except Exception as exc err msg ' Exceptionraisedwhenconnectingtospacewalkserver {0 } {1 }' format server exc log error err msg return {' Error' err msg}groups client systemgroup list All Groups key deleted groups []failed groups []for group in groups if client systemgroup delete key group['name'] 1 deleted groups append group['name'] else failed groups append group['name'] ret {'deleted' deleted groups}if failed groups ret['failed'] failed groupsreturn ret
null
null
null
null
Question: What does the code delete from spacewalk ? Code: def deleteAllGroups(server): try: (client, key) = _get_session(server) except Exception as exc: err_msg = 'Exception raised when connecting to spacewalk server ({0}): {1}'.format(server, exc) log.error(err_msg) return {'Error': err_msg} groups = client.systemgroup.listAllGroups(key) deleted_groups = [] failed_groups = [] for group in groups: if (client.systemgroup.delete(key, group['name']) == 1): deleted_groups.append(group['name']) else: failed_groups.append(group['name']) ret = {'deleted': deleted_groups} if failed_groups: ret['failed'] = failed_groups return ret
null
null
null
What does the code send for the specified user ?
def send_reset_password_instructions(user): token = generate_reset_password_token(user) reset_link = url_for_security('reset_password', token=token, _external=True) send_mail(config_value('EMAIL_SUBJECT_PASSWORD_RESET'), user.email, 'reset_instructions', user=user, reset_link=reset_link) reset_password_instructions_sent.send(app._get_current_object(), user=user, token=token)
null
null
null
the reset password instructions email
codeqa
def send reset password instructions user token generate reset password token user reset link url for security 'reset password' token token external True send mail config value 'EMAIL SUBJECT PASSWORD RESET' user email 'reset instructions' user user reset link reset link reset password instructions sent send app get current object user user token token
null
null
null
null
Question: What does the code send for the specified user ? Code: def send_reset_password_instructions(user): token = generate_reset_password_token(user) reset_link = url_for_security('reset_password', token=token, _external=True) send_mail(config_value('EMAIL_SUBJECT_PASSWORD_RESET'), user.email, 'reset_instructions', user=user, reset_link=reset_link) reset_password_instructions_sent.send(app._get_current_object(), user=user, token=token)
null
null
null
When being by backend processes removed empty object directories ?
def renamer(old, new, fsync=True): dirpath = os.path.dirname(new) try: count = makedirs_count(dirpath) os.rename(old, new) except OSError: count = makedirs_count(dirpath) os.rename(old, new) if fsync: for i in range(0, (count + 1)): fsync_dir(dirpath) dirpath = os.path.dirname(dirpath)
null
null
null
during uploads
codeqa
def renamer old new fsync True dirpath os path dirname new try count makedirs count dirpath os rename old new except OS Error count makedirs count dirpath os rename old new if fsync for i in range 0 count + 1 fsync dir dirpath dirpath os path dirname dirpath
null
null
null
null
Question: When being by backend processes removed empty object directories ? Code: def renamer(old, new, fsync=True): dirpath = os.path.dirname(new) try: count = makedirs_count(dirpath) os.rename(old, new) except OSError: count = makedirs_count(dirpath) os.rename(old, new) if fsync: for i in range(0, (count + 1)): fsync_dir(dirpath) dirpath = os.path.dirname(dirpath)
null
null
null
When do 4 digit and 2 digit return ?
def get_decades(year): if year: try: decade = (year[2:3] + '0') decade2 = (year[:3] + '0') except: decade = '' decade2 = '' else: decade = '' decade2 = '' return (decade, decade2)
null
null
null
decades given year
codeqa
def get decades year if year try decade year[ 2 3] + '0 ' decade 2 year[ 3] + '0 ' except decade ''decade 2 ''else decade ''decade 2 ''return decade decade 2
null
null
null
null
Question: When do 4 digit and 2 digit return ? Code: def get_decades(year): if year: try: decade = (year[2:3] + '0') decade2 = (year[:3] + '0') except: decade = '' decade2 = '' else: decade = '' decade2 = '' return (decade, decade2)
null
null
null
What does the code require ?
@pytest.fixture def tutorial(english, settings): import pytest_pootle shutil.copytree(os.path.join(os.path.dirname(pytest_pootle.__file__), 'data', 'po', 'tutorial'), os.path.join(settings.POOTLE_TRANSLATION_DIRECTORY, 'tutorial')) return _require_project('tutorial', 'Tutorial', english)
null
null
null
tutorial test project
codeqa
@pytest fixturedef tutorial english settings import pytest pootleshutil copytree os path join os path dirname pytest pootle file 'data' 'po' 'tutorial' os path join settings POOTLE TRANSLATION DIRECTORY 'tutorial' return require project 'tutorial' ' Tutorial' english
null
null
null
null
Question: What does the code require ? Code: @pytest.fixture def tutorial(english, settings): import pytest_pootle shutil.copytree(os.path.join(os.path.dirname(pytest_pootle.__file__), 'data', 'po', 'tutorial'), os.path.join(settings.POOTLE_TRANSLATION_DIRECTORY, 'tutorial')) return _require_project('tutorial', 'Tutorial', english)
null
null
null
What calculates certain changes in a certain circumstance ?
def assert_calculated_changes(case, node_state, node_config, nonmanifest_datasets, expected_changes, additional_node_states=frozenset(), leases=Leases(), discovered_datasets=None): api = UnusableAPI() deployer = BlockDeviceDeployer(node_uuid=node_state.uuid, hostname=node_state.hostname, block_device_api=api) cluster_state = compute_cluster_state(node_state, additional_node_states, nonmanifest_datasets) if (discovered_datasets is None): local_state = local_state_from_shared_state(node_state=node_state, nonmanifest_datasets=cluster_state.nonmanifest_datasets) else: local_state = BlockDeviceDeployerLocalState(node_uuid=node_state.uuid, hostname=node_state.hostname, datasets=dataset_map_from_iterable(discovered_datasets)) case.assertEqual(local_state.shared_state_changes(), (node_state.set('applications', None), NonManifestDatasets(datasets=cluster_state.nonmanifest_datasets)), 'Inconsistent test data.') return assert_calculated_changes_for_deployer(case, deployer, node_state, node_config, nonmanifest_datasets, additional_node_states, set(), expected_changes, local_state, leases=leases)
null
null
null
blockdevicedeployer
codeqa
def assert calculated changes case node state node config nonmanifest datasets expected changes additional node states frozenset leases Leases discovered datasets None api Unusable API deployer Block Device Deployer node uuid node state uuid hostname node state hostname block device api api cluster state compute cluster state node state additional node states nonmanifest datasets if discovered datasets is None local state local state from shared state node state node state nonmanifest datasets cluster state nonmanifest datasets else local state Block Device Deployer Local State node uuid node state uuid hostname node state hostname datasets dataset map from iterable discovered datasets case assert Equal local state shared state changes node state set 'applications' None Non Manifest Datasets datasets cluster state nonmanifest datasets ' Inconsistenttestdata ' return assert calculated changes for deployer case deployer node state node config nonmanifest datasets additional node states set expected changes local state leases leases
null
null
null
null
Question: What calculates certain changes in a certain circumstance ? Code: def assert_calculated_changes(case, node_state, node_config, nonmanifest_datasets, expected_changes, additional_node_states=frozenset(), leases=Leases(), discovered_datasets=None): api = UnusableAPI() deployer = BlockDeviceDeployer(node_uuid=node_state.uuid, hostname=node_state.hostname, block_device_api=api) cluster_state = compute_cluster_state(node_state, additional_node_states, nonmanifest_datasets) if (discovered_datasets is None): local_state = local_state_from_shared_state(node_state=node_state, nonmanifest_datasets=cluster_state.nonmanifest_datasets) else: local_state = BlockDeviceDeployerLocalState(node_uuid=node_state.uuid, hostname=node_state.hostname, datasets=dataset_map_from_iterable(discovered_datasets)) case.assertEqual(local_state.shared_state_changes(), (node_state.set('applications', None), NonManifestDatasets(datasets=cluster_state.nonmanifest_datasets)), 'Inconsistent test data.') return assert_calculated_changes_for_deployer(case, deployer, node_state, node_config, nonmanifest_datasets, additional_node_states, set(), expected_changes, local_state, leases=leases)
null
null
null
How do all frames list ?
@requires_segment_info def frame_lister(pl, segment_info, full_stack=False, maxframes=3): if full_stack: initial_stack_length = 0 frames = segment_info[u'pdb'].stack else: initial_stack_length = segment_info[u'initial_stack_length'] frames = segment_info[u'pdb'].stack[initial_stack_length:] if (len(frames) > maxframes): frames = frames[(- maxframes):] return (({u'curframe': frame[0], u'initial_stack_length': initial_stack_length}, {}) for frame in frames)
null
null
null
in segment_info format
codeqa
@requires segment infodef frame lister pl segment info full stack False maxframes 3 if full stack initial stack length 0frames segment info[u'pdb'] stackelse initial stack length segment info[u'initial stack length']frames segment info[u'pdb'] stack[initial stack length ]if len frames > maxframes frames frames[ - maxframes ]return {u'curframe' frame[ 0 ] u'initial stack length' initial stack length} {} for frame in frames
null
null
null
null
Question: How do all frames list ? Code: @requires_segment_info def frame_lister(pl, segment_info, full_stack=False, maxframes=3): if full_stack: initial_stack_length = 0 frames = segment_info[u'pdb'].stack else: initial_stack_length = segment_info[u'initial_stack_length'] frames = segment_info[u'pdb'].stack[initial_stack_length:] if (len(frames) > maxframes): frames = frames[(- maxframes):] return (({u'curframe': frame[0], u'initial_stack_length': initial_stack_length}, {}) for frame in frames)
null
null
null
Where does the code generate an icinga2 certificate and key ?
def generate_cert(name): ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} cert = '/etc/icinga2/pki/{0}.crt'.format(name) key = '/etc/icinga2/pki/{0}.key'.format(name) if (os.path.isfile(cert) and os.path.isfile(key)): ret['comment'] = 'No execution needed. Cert: {0} and key: {1} already generated.'.format(cert, key) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Certificate and key generation would be executed' return ret cert_save = __salt__['icinga2.generate_cert'](name) if (not cert_save): ret['comment'] = 'Certificate and key generated' ret['changes']['cert'] = 'Executed. Certificate saved: {0}'.format(cert) ret['changes']['key'] = 'Executed. Key saved: {0}'.format(key) return ret
null
null
null
on the client
codeqa
def generate cert name ret {'name' name 'changes' {} 'result' True 'comment' ''}cert '/etc/icinga 2 /pki/{ 0 } crt' format name key '/etc/icinga 2 /pki/{ 0 } key' format name if os path isfile cert and os path isfile key ret['comment'] ' Noexecutionneeded Cert {0 }andkey {1 }alreadygenerated ' format cert key return retif opts ['test'] ret['result'] Noneret['comment'] ' Certificateandkeygenerationwouldbeexecuted'return retcert save salt ['icinga 2 generate cert'] name if not cert save ret['comment'] ' Certificateandkeygenerated'ret['changes']['cert'] ' Executed Certificatesaved {0 }' format cert ret['changes']['key'] ' Executed Keysaved {0 }' format key return ret
null
null
null
null
Question: Where does the code generate an icinga2 certificate and key ? Code: def generate_cert(name): ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} cert = '/etc/icinga2/pki/{0}.crt'.format(name) key = '/etc/icinga2/pki/{0}.key'.format(name) if (os.path.isfile(cert) and os.path.isfile(key)): ret['comment'] = 'No execution needed. Cert: {0} and key: {1} already generated.'.format(cert, key) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Certificate and key generation would be executed' return ret cert_save = __salt__['icinga2.generate_cert'](name) if (not cert_save): ret['comment'] = 'Certificate and key generated' ret['changes']['cert'] = 'Executed. Certificate saved: {0}'.format(cert) ret['changes']['key'] = 'Executed. Key saved: {0}'.format(key) return ret
null
null
null
What does the code generate on the client ?
def generate_cert(name): ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} cert = '/etc/icinga2/pki/{0}.crt'.format(name) key = '/etc/icinga2/pki/{0}.key'.format(name) if (os.path.isfile(cert) and os.path.isfile(key)): ret['comment'] = 'No execution needed. Cert: {0} and key: {1} already generated.'.format(cert, key) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Certificate and key generation would be executed' return ret cert_save = __salt__['icinga2.generate_cert'](name) if (not cert_save): ret['comment'] = 'Certificate and key generated' ret['changes']['cert'] = 'Executed. Certificate saved: {0}'.format(cert) ret['changes']['key'] = 'Executed. Key saved: {0}'.format(key) return ret
null
null
null
an icinga2 certificate and key
codeqa
def generate cert name ret {'name' name 'changes' {} 'result' True 'comment' ''}cert '/etc/icinga 2 /pki/{ 0 } crt' format name key '/etc/icinga 2 /pki/{ 0 } key' format name if os path isfile cert and os path isfile key ret['comment'] ' Noexecutionneeded Cert {0 }andkey {1 }alreadygenerated ' format cert key return retif opts ['test'] ret['result'] Noneret['comment'] ' Certificateandkeygenerationwouldbeexecuted'return retcert save salt ['icinga 2 generate cert'] name if not cert save ret['comment'] ' Certificateandkeygenerated'ret['changes']['cert'] ' Executed Certificatesaved {0 }' format cert ret['changes']['key'] ' Executed Keysaved {0 }' format key return ret
null
null
null
null
Question: What does the code generate on the client ? Code: def generate_cert(name): ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} cert = '/etc/icinga2/pki/{0}.crt'.format(name) key = '/etc/icinga2/pki/{0}.key'.format(name) if (os.path.isfile(cert) and os.path.isfile(key)): ret['comment'] = 'No execution needed. Cert: {0} and key: {1} already generated.'.format(cert, key) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Certificate and key generation would be executed' return ret cert_save = __salt__['icinga2.generate_cert'](name) if (not cert_save): ret['comment'] = 'Certificate and key generated' ret['changes']['cert'] = 'Executed. Certificate saved: {0}'.format(cert) ret['changes']['key'] = 'Executed. Key saved: {0}'.format(key) return ret
null
null
null
When is this called ?
def at_server_stop(): pass
null
null
null
just before the server is shut down
codeqa
def at server stop pass
null
null
null
null
Question: When is this called ? Code: def at_server_stop(): pass
null
null
null
What do all exceptions want ?
def add_bgp_error_metadata(code, sub_code, def_desc='unknown'): if (_EXCEPTION_REGISTRY.get((code, sub_code)) is not None): raise ValueError(('BGPSException with code %d and sub-code %d already defined.' % (code, sub_code))) def decorator(subclass): 'Sets class constants for exception code and sub-code.\n\n If given class is sub-class of BGPSException we sets class constants.\n ' if issubclass(subclass, BGPSException): _EXCEPTION_REGISTRY[(code, sub_code)] = subclass subclass.CODE = code subclass.SUB_CODE = sub_code subclass.DEF_DESC = def_desc return subclass return decorator
null
null
null
to set exception class meta - data
codeqa
def add bgp error metadata code sub code def desc 'unknown' if EXCEPTION REGISTRY get code sub code is not None raise Value Error 'BGPS Exceptionwithcode%dandsub-code%dalreadydefined ' % code sub code def decorator subclass ' Setsclassconstantsforexceptioncodeandsub-code \n\n Ifgivenclassissub-classof BGPS Exceptionwesetsclassconstants \n'if issubclass subclass BGPS Exception EXCEPTION REGISTRY[ code sub code ] subclasssubclass CODE codesubclass SUB CODE sub codesubclass DEF DESC def descreturn subclassreturn decorator
null
null
null
null
Question: What do all exceptions want ? Code: def add_bgp_error_metadata(code, sub_code, def_desc='unknown'): if (_EXCEPTION_REGISTRY.get((code, sub_code)) is not None): raise ValueError(('BGPSException with code %d and sub-code %d already defined.' % (code, sub_code))) def decorator(subclass): 'Sets class constants for exception code and sub-code.\n\n If given class is sub-class of BGPSException we sets class constants.\n ' if issubclass(subclass, BGPSException): _EXCEPTION_REGISTRY[(code, sub_code)] = subclass subclass.CODE = code subclass.SUB_CODE = sub_code subclass.DEF_DESC = def_desc return subclass return decorator
null
null
null
What does the code ensure ?
def role_absent(name, profile=None, **connection_args): ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Role "{0}" is already absent'.format(name)} role = __salt__['keystone.role_get'](name=name, profile=profile, **connection_args) if ('Error' not in role): if __opts__.get('test'): ret['result'] = None ret['comment'] = 'Role "{0}" will be deleted'.format(name) return ret __salt__['keystone.role_delete'](name=name, profile=profile, **connection_args) ret['comment'] = 'Role "{0}" has been deleted'.format(name) ret['changes']['Role'] = 'Deleted' return ret
null
null
null
that the keystone role is absent
codeqa
def role absent name profile None **connection args ret {'name' name 'changes' {} 'result' True 'comment' ' Role"{ 0 }"isalreadyabsent' format name }role salt ['keystone role get'] name name profile profile **connection args if ' Error' not in role if opts get 'test' ret['result'] Noneret['comment'] ' Role"{ 0 }"willbedeleted' format name return ret salt ['keystone role delete'] name name profile profile **connection args ret['comment'] ' Role"{ 0 }"hasbeendeleted' format name ret['changes'][' Role'] ' Deleted'return ret
null
null
null
null
Question: What does the code ensure ? Code: def role_absent(name, profile=None, **connection_args): ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Role "{0}" is already absent'.format(name)} role = __salt__['keystone.role_get'](name=name, profile=profile, **connection_args) if ('Error' not in role): if __opts__.get('test'): ret['result'] = None ret['comment'] = 'Role "{0}" will be deleted'.format(name) return ret __salt__['keystone.role_delete'](name=name, profile=profile, **connection_args) ret['comment'] = 'Role "{0}" has been deleted'.format(name) ret['changes']['Role'] = 'Deleted' return ret
null
null
null
What does the code minimize ?
def linprog(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None, method='simplex', callback=None, options=None): meth = method.lower() if (options is None): options = {} if (meth == 'simplex'): return _linprog_simplex(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=bounds, callback=callback, **options) else: raise ValueError(('Unknown solver %s' % method))
null
null
null
a linear objective function subject to linear equality and inequality constraints
codeqa
def linprog c A ub None b ub None A eq None b eq None bounds None method 'simplex' callback None options None meth method lower if options is None options {}if meth 'simplex' return linprog simplex c A ub A ub b ub b ub A eq A eq b eq b eq bounds bounds callback callback **options else raise Value Error ' Unknownsolver%s' % method
null
null
null
null
Question: What does the code minimize ? Code: def linprog(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None, method='simplex', callback=None, options=None): meth = method.lower() if (options is None): options = {} if (meth == 'simplex'): return _linprog_simplex(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=bounds, callback=callback, **options) else: raise ValueError(('Unknown solver %s' % method))
null
null
null
What does the code create ?
def makeFactory(configdict): pubkeyfile = os.path.join(_GAME_DIR, 'server', 'ssh-public.key') privkeyfile = os.path.join(_GAME_DIR, 'server', 'ssh-private.key') def chainProtocolFactory(username=None): return insults.ServerProtocol(configdict['protocolFactory'], *configdict.get('protocolConfigdict', (username,)), **configdict.get('protocolKwArgs', {})) rlm = PassAvatarIdTerminalRealm() rlm.transportFactory = TerminalSessionTransport_getPeer rlm.chainedProtocolFactory = chainProtocolFactory factory = ConchFactory(Portal(rlm)) factory.sessionhandler = configdict['sessions'] try: (publicKey, privateKey) = getKeyPair(pubkeyfile, privkeyfile) factory.publicKeys = {'ssh-rsa': publicKey} factory.privateKeys = {'ssh-rsa': privateKey} except Exception as err: print('getKeyPair error: {err}\n WARNING: Evennia could not auto-generate SSH keypair. Using conch default keys instead.\nIf this error persists, create {pub} and {priv} yourself using third-party tools.'.format(err=err, pub=pubkeyfile, priv=privkeyfile)) factory.services = factory.services.copy() factory.services['ssh-userauth'] = ExtraInfoAuthServer factory.portal.registerChecker(PlayerDBPasswordChecker(factory)) return factory
null
null
null
the ssh server factory
codeqa
def make Factory configdict pubkeyfile os path join GAME DIR 'server' 'ssh-public key' privkeyfile os path join GAME DIR 'server' 'ssh-private key' def chain Protocol Factory username None return insults Server Protocol configdict['protocol Factory'] *configdict get 'protocol Configdict' username **configdict get 'protocol Kw Args' {} rlm Pass Avatar Id Terminal Realm rlm transport Factory Terminal Session Transport get Peerrlm chained Protocol Factory chain Protocol Factoryfactory Conch Factory Portal rlm factory sessionhandler configdict['sessions']try public Key private Key get Key Pair pubkeyfile privkeyfile factory public Keys {'ssh-rsa' public Key}factory private Keys {'ssh-rsa' private Key}except Exception as err print 'get Key Pairerror {err}\n WARNING Evenniacouldnotauto-generate SS Hkeypair Usingconchdefaultkeysinstead \n Ifthiserrorpersists create{pub}and{priv}yourselfusingthird-partytools ' format err err pub pubkeyfile priv privkeyfile factory services factory services copy factory services['ssh-userauth'] Extra Info Auth Serverfactory portal register Checker Player DB Password Checker factory return factory
null
null
null
null
Question: What does the code create ? Code: def makeFactory(configdict): pubkeyfile = os.path.join(_GAME_DIR, 'server', 'ssh-public.key') privkeyfile = os.path.join(_GAME_DIR, 'server', 'ssh-private.key') def chainProtocolFactory(username=None): return insults.ServerProtocol(configdict['protocolFactory'], *configdict.get('protocolConfigdict', (username,)), **configdict.get('protocolKwArgs', {})) rlm = PassAvatarIdTerminalRealm() rlm.transportFactory = TerminalSessionTransport_getPeer rlm.chainedProtocolFactory = chainProtocolFactory factory = ConchFactory(Portal(rlm)) factory.sessionhandler = configdict['sessions'] try: (publicKey, privateKey) = getKeyPair(pubkeyfile, privkeyfile) factory.publicKeys = {'ssh-rsa': publicKey} factory.privateKeys = {'ssh-rsa': privateKey} except Exception as err: print('getKeyPair error: {err}\n WARNING: Evennia could not auto-generate SSH keypair. Using conch default keys instead.\nIf this error persists, create {pub} and {priv} yourself using third-party tools.'.format(err=err, pub=pubkeyfile, priv=privkeyfile)) factory.services = factory.services.copy() factory.services['ssh-userauth'] = ExtraInfoAuthServer factory.portal.registerChecker(PlayerDBPasswordChecker(factory)) return factory
null
null
null
What does the code handle ?
def _doc_link(rawtext, text, options={}, content=[]): (has_explicit_title, title, slug) = split_explicit_title(text) twin_slugs = False post = None for p in doc_role.site.timeline: if (p.meta('slug') == slug): if (post is None): post = p else: twin_slugs = True break try: if (post is None): raise ValueError except ValueError: return (False, False, None, None, slug) if (not has_explicit_title): title = post.title() permalink = post.permalink() return (True, twin_slugs, title, permalink, slug)
null
null
null
the doc role
codeqa
def doc link rawtext text options {} content [] has explicit title title slug split explicit title text twin slugs Falsepost Nonefor p in doc role site timeline if p meta 'slug' slug if post is None post pelse twin slugs Truebreaktry if post is None raise Value Errorexcept Value Error return False False None None slug if not has explicit title title post title permalink post permalink return True twin slugs title permalink slug
null
null
null
null
Question: What does the code handle ? Code: def _doc_link(rawtext, text, options={}, content=[]): (has_explicit_title, title, slug) = split_explicit_title(text) twin_slugs = False post = None for p in doc_role.site.timeline: if (p.meta('slug') == slug): if (post is None): post = p else: twin_slugs = True break try: if (post is None): raise ValueError except ValueError: return (False, False, None, None, slug) if (not has_explicit_title): title = post.title() permalink = post.permalink() return (True, twin_slugs, title, permalink, slug)
null
null
null
What does the code make by inserting them into a dictionary ?
def uniquify(lst): dct = {} result = [] for k in lst: if (k not in dct): result.append(k) dct[k] = 1 return result
null
null
null
the elements of a list unique
codeqa
def uniquify lst dct {}result []for k in lst if k not in dct result append k dct[k] 1return result
null
null
null
null
Question: What does the code make by inserting them into a dictionary ? Code: def uniquify(lst): dct = {} result = [] for k in lst: if (k not in dct): result.append(k) dct[k] = 1 return result
null
null
null
How does the code make the elements of a list unique ?
def uniquify(lst): dct = {} result = [] for k in lst: if (k not in dct): result.append(k) dct[k] = 1 return result
null
null
null
by inserting them into a dictionary
codeqa
def uniquify lst dct {}result []for k in lst if k not in dct result append k dct[k] 1return result
null
null
null
null
Question: How does the code make the elements of a list unique ? Code: def uniquify(lst): dct = {} result = [] for k in lst: if (k not in dct): result.append(k) dct[k] = 1 return result
null
null
null
For what purpose does all matching snippet files return ?
def find_snippet_files(ft, directory): patterns = ['%s.snippets', '%s_*.snippets', os.path.join('%s', '*')] ret = set() directory = os.path.expanduser(directory) for pattern in patterns: for fn in glob.glob(os.path.join(directory, (pattern % ft))): ret.add(os.path.realpath(fn)) return ret
null
null
null
for ft in directory
codeqa
def find snippet files ft directory patterns ['%s snippets' '%s * snippets' os path join '%s' '*' ]ret set directory os path expanduser directory for pattern in patterns for fn in glob glob os path join directory pattern % ft ret add os path realpath fn return ret
null
null
null
null
Question: For what purpose does all matching snippet files return ? Code: def find_snippet_files(ft, directory): patterns = ['%s.snippets', '%s_*.snippets', os.path.join('%s', '*')] ret = set() directory = os.path.expanduser(directory) for pattern in patterns: for fn in glob.glob(os.path.join(directory, (pattern % ft))): ret.add(os.path.realpath(fn)) return ret
null
null
null
What does the code shorten ?
def random_reduce(circuit, gate_ids, seed=None): from sympy.utilities.randtest import _randrange if (not gate_ids): return circuit if isinstance(circuit, Mul): circuit = circuit.args ids = flatten_ids(gate_ids) randrange = _randrange(seed) while ids: i = randrange(len(ids)) id = ids.pop(i) if (find_subcircuit(circuit, id) != (-1)): break else: return circuit return replace_subcircuit(circuit, id)
null
null
null
the length of a quantum circuit
codeqa
def random reduce circuit gate ids seed None from sympy utilities randtest import randrangeif not gate ids return circuitif isinstance circuit Mul circuit circuit argsids flatten ids gate ids randrange randrange seed while ids i randrange len ids id ids pop i if find subcircuit circuit id -1 breakelse return circuitreturn replace subcircuit circuit id
null
null
null
null
Question: What does the code shorten ? Code: def random_reduce(circuit, gate_ids, seed=None): from sympy.utilities.randtest import _randrange if (not gate_ids): return circuit if isinstance(circuit, Mul): circuit = circuit.args ids = flatten_ids(gate_ids) randrange = _randrange(seed) while ids: i = randrange(len(ids)) id = ids.pop(i) if (find_subcircuit(circuit, id) != (-1)): break else: return circuit return replace_subcircuit(circuit, id)
null
null
null
What puts custom rich text message to the build pages and job main page ?
def rich_text_publisher(registry, xml_parent, data): parsers = ['HTML', 'Confluence', 'WikiText'] reporter = XML.SubElement(xml_parent, 'org.korosoft.jenkins.plugin.rtp.RichTextPublisher') reporter.set('plugin', 'rich-text-publisher-plugin') mappings = [('stable-text', 'stableText', None), ('unstable-text', 'unstableText', ''), ('failed-text', 'failedText', ''), ('unstable-as-stable', 'unstableAsStable', True), ('failed-as-stable', 'failedAsStable', True), ('parser-name', 'parserName', 'WikiText', parsers)] helpers.convert_mapping_to_xml(reporter, data, mappings, fail_required=True)
null
null
null
this plugin
codeqa
def rich text publisher registry xml parent data parsers ['HTML' ' Confluence' ' Wiki Text']reporter XML Sub Element xml parent 'org korosoft jenkins plugin rtp Rich Text Publisher' reporter set 'plugin' 'rich-text-publisher-plugin' mappings [ 'stable-text' 'stable Text' None 'unstable-text' 'unstable Text' '' 'failed-text' 'failed Text' '' 'unstable-as-stable' 'unstable As Stable' True 'failed-as-stable' 'failed As Stable' True 'parser-name' 'parser Name' ' Wiki Text' parsers ]helpers convert mapping to xml reporter data mappings fail required True
null
null
null
null
Question: What puts custom rich text message to the build pages and job main page ? Code: def rich_text_publisher(registry, xml_parent, data): parsers = ['HTML', 'Confluence', 'WikiText'] reporter = XML.SubElement(xml_parent, 'org.korosoft.jenkins.plugin.rtp.RichTextPublisher') reporter.set('plugin', 'rich-text-publisher-plugin') mappings = [('stable-text', 'stableText', None), ('unstable-text', 'unstableText', ''), ('failed-text', 'failedText', ''), ('unstable-as-stable', 'unstableAsStable', True), ('failed-as-stable', 'failedAsStable', True), ('parser-name', 'parserName', 'WikiText', parsers)] helpers.convert_mapping_to_xml(reporter, data, mappings, fail_required=True)
null
null
null
What does this plugin put to the build pages and job main page ?
def rich_text_publisher(registry, xml_parent, data): parsers = ['HTML', 'Confluence', 'WikiText'] reporter = XML.SubElement(xml_parent, 'org.korosoft.jenkins.plugin.rtp.RichTextPublisher') reporter.set('plugin', 'rich-text-publisher-plugin') mappings = [('stable-text', 'stableText', None), ('unstable-text', 'unstableText', ''), ('failed-text', 'failedText', ''), ('unstable-as-stable', 'unstableAsStable', True), ('failed-as-stable', 'failedAsStable', True), ('parser-name', 'parserName', 'WikiText', parsers)] helpers.convert_mapping_to_xml(reporter, data, mappings, fail_required=True)
null
null
null
custom rich text message
codeqa
def rich text publisher registry xml parent data parsers ['HTML' ' Confluence' ' Wiki Text']reporter XML Sub Element xml parent 'org korosoft jenkins plugin rtp Rich Text Publisher' reporter set 'plugin' 'rich-text-publisher-plugin' mappings [ 'stable-text' 'stable Text' None 'unstable-text' 'unstable Text' '' 'failed-text' 'failed Text' '' 'unstable-as-stable' 'unstable As Stable' True 'failed-as-stable' 'failed As Stable' True 'parser-name' 'parser Name' ' Wiki Text' parsers ]helpers convert mapping to xml reporter data mappings fail required True
null
null
null
null
Question: What does this plugin put to the build pages and job main page ? Code: def rich_text_publisher(registry, xml_parent, data): parsers = ['HTML', 'Confluence', 'WikiText'] reporter = XML.SubElement(xml_parent, 'org.korosoft.jenkins.plugin.rtp.RichTextPublisher') reporter.set('plugin', 'rich-text-publisher-plugin') mappings = [('stable-text', 'stableText', None), ('unstable-text', 'unstableText', ''), ('failed-text', 'failedText', ''), ('unstable-as-stable', 'unstableAsStable', True), ('failed-as-stable', 'failedAsStable', True), ('parser-name', 'parserName', 'WikiText', parsers)] helpers.convert_mapping_to_xml(reporter, data, mappings, fail_required=True)
null
null
null
What is sending handling ?
def sendMessage(qry): try: getUserName() except: return _skypeError() if (qry == 'skype update'): _writeFriends() _getAvatars() return (len(_readFriends()).__str__() + ' friends found and cached!') else: m = qry.partition(': ') ret = skype(((('MESSAGE ' + m[0]) + ' ') + m[2])) if ('SENDING' in ret): return ('Message sent to ' + m[0]) else: return ('ERROR sending message to: ' + m[0])
null
null
null
message
codeqa
def send Message qry try get User Name except return skype Error if qry 'skypeupdate' write Friends get Avatars return len read Friends str + 'friendsfoundandcached ' else m qry partition ' ' ret skype 'MESSAGE' + m[ 0 ] + '' + m[ 2 ] if 'SENDING' in ret return ' Messagesentto' + m[ 0 ] else return 'ERRO Rsendingmessageto ' + m[ 0 ]
null
null
null
null
Question: What is sending handling ? Code: def sendMessage(qry): try: getUserName() except: return _skypeError() if (qry == 'skype update'): _writeFriends() _getAvatars() return (len(_readFriends()).__str__() + ' friends found and cached!') else: m = qry.partition(': ') ret = skype(((('MESSAGE ' + m[0]) + ' ') + m[2])) if ('SENDING' in ret): return ('Message sent to ' + m[0]) else: return ('ERROR sending message to: ' + m[0])
null
null
null
What do message send ?
def sendMessage(qry): try: getUserName() except: return _skypeError() if (qry == 'skype update'): _writeFriends() _getAvatars() return (len(_readFriends()).__str__() + ' friends found and cached!') else: m = qry.partition(': ') ret = skype(((('MESSAGE ' + m[0]) + ' ') + m[2])) if ('SENDING' in ret): return ('Message sent to ' + m[0]) else: return ('ERROR sending message to: ' + m[0])
null
null
null
handling
codeqa
def send Message qry try get User Name except return skype Error if qry 'skypeupdate' write Friends get Avatars return len read Friends str + 'friendsfoundandcached ' else m qry partition ' ' ret skype 'MESSAGE' + m[ 0 ] + '' + m[ 2 ] if 'SENDING' in ret return ' Messagesentto' + m[ 0 ] else return 'ERRO Rsendingmessageto ' + m[ 0 ]
null
null
null
null
Question: What do message send ? Code: def sendMessage(qry): try: getUserName() except: return _skypeError() if (qry == 'skype update'): _writeFriends() _getAvatars() return (len(_readFriends()).__str__() + ' friends found and cached!') else: m = qry.partition(': ') ret = skype(((('MESSAGE ' + m[0]) + ' ') + m[2])) if ('SENDING' in ret): return ('Message sent to ' + m[0]) else: return ('ERROR sending message to: ' + m[0])
null
null
null
What does the code return ?
def decompress(fileobj, path): if path.endswith('.gz'): return gunzip_stream(fileobj) elif path.endswith('.bz2'): if (bz2 is None): raise Exception('bz2 module was not successfully imported (likely not installed).') else: return bunzip2_stream(fileobj) else: return fileobj
null
null
null
an iterator that yield chunks of bytes
codeqa
def decompress fileobj path if path endswith ' gz' return gunzip stream fileobj elif path endswith ' bz 2 ' if bz 2 is None raise Exception 'bz 2 modulewasnotsuccessfullyimported likelynotinstalled ' else return bunzip 2 stream fileobj else return fileobj
null
null
null
null
Question: What does the code return ? Code: def decompress(fileobj, path): if path.endswith('.gz'): return gunzip_stream(fileobj) elif path.endswith('.bz2'): if (bz2 is None): raise Exception('bz2 module was not successfully imported (likely not installed).') else: return bunzip2_stream(fileobj) else: return fileobj
null
null
null
What does the code get ?
def get_email_backend(real_email=False): if (real_email or settings.SEND_REAL_EMAIL): backend = None else: backend = 'olympia.amo.mail.DevEmailBackend' return django.core.mail.get_connection(backend)
null
null
null
a connection to an email backend
codeqa
def get email backend real email False if real email or settings SEND REAL EMAIL backend Noneelse backend 'olympia amo mail Dev Email Backend'return django core mail get connection backend
null
null
null
null
Question: What does the code get ? Code: def get_email_backend(real_email=False): if (real_email or settings.SEND_REAL_EMAIL): backend = None else: backend = 'olympia.amo.mail.DevEmailBackend' return django.core.mail.get_connection(backend)
null
null
null
When do course badges create ?
@receiver(COURSE_CERT_AWARDED, sender=GeneratedCertificate) def create_course_badge(sender, user, course_key, status, **kwargs): course_badge_check(user, course_key)
null
null
null
when a certificate has been generated
codeqa
@receiver COURSE CERT AWARDED sender Generated Certificate def create course badge sender user course key status **kwargs course badge check user course key
null
null
null
null
Question: When do course badges create ? Code: @receiver(COURSE_CERT_AWARDED, sender=GeneratedCertificate) def create_course_badge(sender, user, course_key, status, **kwargs): course_badge_check(user, course_key)
null
null
null
When were multiple shares configured per line ?
def _write_exports(exports, edict): with salt.utils.fopen(exports, 'w') as efh: for export in edict: line = export for perms in edict[export]: hosts = ','.join(perms['hosts']) options = ','.join(perms['options']) line += ' {0}({1})'.format(hosts, options) efh.write('{0}\n'.format(line))
null
null
null
initially
codeqa
def write exports exports edict with salt utils fopen exports 'w' as efh for export in edict line exportfor perms in edict[export] hosts ' ' join perms['hosts'] options ' ' join perms['options'] line + '{ 0 } {1 } ' format hosts options efh write '{ 0 }\n' format line
null
null
null
null
Question: When were multiple shares configured per line ? Code: def _write_exports(exports, edict): with salt.utils.fopen(exports, 'w') as efh: for export in edict: line = export for perms in edict[export]: hosts = ','.join(perms['hosts']) options = ','.join(perms['options']) line += ' {0}({1})'.format(hosts, options) efh.write('{0}\n'.format(line))
null
null
null
What does the code write to disk if multiple shares were initially configured per line ?
def _write_exports(exports, edict): with salt.utils.fopen(exports, 'w') as efh: for export in edict: line = export for perms in edict[export]: hosts = ','.join(perms['hosts']) options = ','.join(perms['options']) line += ' {0}({1})'.format(hosts, options) efh.write('{0}\n'.format(line))
null
null
null
an exports file
codeqa
def write exports exports edict with salt utils fopen exports 'w' as efh for export in edict line exportfor perms in edict[export] hosts ' ' join perms['hosts'] options ' ' join perms['options'] line + '{ 0 } {1 } ' format hosts options efh write '{ 0 }\n' format line
null
null
null
null
Question: What does the code write to disk if multiple shares were initially configured per line ? Code: def _write_exports(exports, edict): with salt.utils.fopen(exports, 'w') as efh: for export in edict: line = export for perms in edict[export]: hosts = ','.join(perms['hosts']) options = ','.join(perms['options']) line += ' {0}({1})'.format(hosts, options) efh.write('{0}\n'.format(line))
null
null
null
What provide a translation for some technical message i d to store partial date formats ?
def get_partial_date_formats(): warnings.warn("'django.utils.translation.get_partial_date_formats' is deprecated. Please update your code to use the new i18n aware formatting.", PendingDeprecationWarning) from django.conf import settings year_month_format = ugettext('YEAR_MONTH_FORMAT') month_day_format = ugettext('MONTH_DAY_FORMAT') if (year_month_format == 'YEAR_MONTH_FORMAT'): year_month_format = settings.YEAR_MONTH_FORMAT if (month_day_format == 'MONTH_DAY_FORMAT'): month_day_format = settings.MONTH_DAY_FORMAT return (year_month_format, month_day_format)
null
null
null
translation files
codeqa
def get partial date formats warnings warn "'django utils translation get partial date formats'isdeprecated Pleaseupdateyourcodetousethenewi 18 nawareformatting " Pending Deprecation Warning from django conf import settingsyear month format ugettext 'YEAR MONTH FORMAT' month day format ugettext 'MONTH DAY FORMAT' if year month format 'YEAR MONTH FORMAT' year month format settings YEAR MONTH FORMA Tif month day format 'MONTH DAY FORMAT' month day format settings MONTH DAY FORMA Treturn year month format month day format
null
null
null
null
Question: What provide a translation for some technical message i d to store partial date formats ? Code: def get_partial_date_formats(): warnings.warn("'django.utils.translation.get_partial_date_formats' is deprecated. Please update your code to use the new i18n aware formatting.", PendingDeprecationWarning) from django.conf import settings year_month_format = ugettext('YEAR_MONTH_FORMAT') month_day_format = ugettext('MONTH_DAY_FORMAT') if (year_month_format == 'YEAR_MONTH_FORMAT'): year_month_format = settings.YEAR_MONTH_FORMAT if (month_day_format == 'MONTH_DAY_FORMAT'): month_day_format = settings.MONTH_DAY_FORMAT return (year_month_format, month_day_format)
null
null
null
What does the code create if the path already exists ?
def mkdirP(path): assert (path is not None) try: os.makedirs(path) except OSError as exc: if ((exc.errno == errno.EEXIST) and os.path.isdir(path)): pass else: raise
null
null
null
a directory
codeqa
def mkdir P path assert path is not None try os makedirs path except OS Error as exc if exc errno errno EEXIST and os path isdir path passelse raise
null
null
null
null
Question: What does the code create if the path already exists ? Code: def mkdirP(path): assert (path is not None) try: os.makedirs(path) except OSError as exc: if ((exc.errno == errno.EEXIST) and os.path.isdir(path)): pass else: raise
null
null
null
How do additional minions matched on lower - level masters store ?
def store_minions(opts, jid, minions, mminion=None, syndic_id=None): if (mminion is None): mminion = salt.minion.MasterMinion(opts, states=False, rend=False) job_cache = opts['master_job_cache'] minions_fstr = '{0}.save_minions'.format(job_cache) try: mminion.returners[minions_fstr](jid, minions, syndic_id=syndic_id) except KeyError: raise KeyError("Returner '{0}' does not support function save_minions".format(job_cache))
null
null
null
using the configured master_job_cache
codeqa
def store minions opts jid minions mminion None syndic id None if mminion is None mminion salt minion Master Minion opts states False rend False job cache opts['master job cache']minions fstr '{ 0 } save minions' format job cache try mminion returners[minions fstr] jid minions syndic id syndic id except Key Error raise Key Error " Returner'{ 0 }'doesnotsupportfunctionsave minions" format job cache
null
null
null
null
Question: How do additional minions matched on lower - level masters store ? Code: def store_minions(opts, jid, minions, mminion=None, syndic_id=None): if (mminion is None): mminion = salt.minion.MasterMinion(opts, states=False, rend=False) job_cache = opts['master_job_cache'] minions_fstr = '{0}.save_minions'.format(job_cache) try: mminion.returners[minions_fstr](jid, minions, syndic_id=syndic_id) except KeyError: raise KeyError("Returner '{0}' does not support function save_minions".format(job_cache))
null
null
null
What matched on lower - level masters ?
def store_minions(opts, jid, minions, mminion=None, syndic_id=None): if (mminion is None): mminion = salt.minion.MasterMinion(opts, states=False, rend=False) job_cache = opts['master_job_cache'] minions_fstr = '{0}.save_minions'.format(job_cache) try: mminion.returners[minions_fstr](jid, minions, syndic_id=syndic_id) except KeyError: raise KeyError("Returner '{0}' does not support function save_minions".format(job_cache))
null
null
null
additional minions
codeqa
def store minions opts jid minions mminion None syndic id None if mminion is None mminion salt minion Master Minion opts states False rend False job cache opts['master job cache']minions fstr '{ 0 } save minions' format job cache try mminion returners[minions fstr] jid minions syndic id syndic id except Key Error raise Key Error " Returner'{ 0 }'doesnotsupportfunctionsave minions" format job cache
null
null
null
null
Question: What matched on lower - level masters ? Code: def store_minions(opts, jid, minions, mminion=None, syndic_id=None): if (mminion is None): mminion = salt.minion.MasterMinion(opts, states=False, rend=False) job_cache = opts['master_job_cache'] minions_fstr = '{0}.save_minions'.format(job_cache) try: mminion.returners[minions_fstr](jid, minions, syndic_id=syndic_id) except KeyError: raise KeyError("Returner '{0}' does not support function save_minions".format(job_cache))
null
null
null
Where did additional minions match ?
def store_minions(opts, jid, minions, mminion=None, syndic_id=None): if (mminion is None): mminion = salt.minion.MasterMinion(opts, states=False, rend=False) job_cache = opts['master_job_cache'] minions_fstr = '{0}.save_minions'.format(job_cache) try: mminion.returners[minions_fstr](jid, minions, syndic_id=syndic_id) except KeyError: raise KeyError("Returner '{0}' does not support function save_minions".format(job_cache))
null
null
null
on lower - level masters
codeqa
def store minions opts jid minions mminion None syndic id None if mminion is None mminion salt minion Master Minion opts states False rend False job cache opts['master job cache']minions fstr '{ 0 } save minions' format job cache try mminion returners[minions fstr] jid minions syndic id syndic id except Key Error raise Key Error " Returner'{ 0 }'doesnotsupportfunctionsave minions" format job cache
null
null
null
null
Question: Where did additional minions match ? Code: def store_minions(opts, jid, minions, mminion=None, syndic_id=None): if (mminion is None): mminion = salt.minion.MasterMinion(opts, states=False, rend=False) job_cache = opts['master_job_cache'] minions_fstr = '{0}.save_minions'.format(job_cache) try: mminion.returners[minions_fstr](jid, minions, syndic_id=syndic_id) except KeyError: raise KeyError("Returner '{0}' does not support function save_minions".format(job_cache))
null
null
null
What uses the information in the config file to rename an existing lineage ?
def rename(config, unused_plugins): cert_manager.rename_lineage(config)
null
null
null
a certificate
codeqa
def rename config unused plugins cert manager rename lineage config
null
null
null
null
Question: What uses the information in the config file to rename an existing lineage ? Code: def rename(config, unused_plugins): cert_manager.rename_lineage(config)
null
null
null
What did the code rename ?
def rename(config, unused_plugins): cert_manager.rename_lineage(config)
null
null
null
a certificate
codeqa
def rename config unused plugins cert manager rename lineage config
null
null
null
null
Question: What did the code rename ? Code: def rename(config, unused_plugins): cert_manager.rename_lineage(config)
null
null
null
What does the code look ?
def set_es_key(lookup_dict, term, value): (value_dict, value_key) = _find_es_dict_by_key(lookup_dict, term) if (value_dict is not None): value_dict[value_key] = value return True return False
null
null
null
the location that the term maps to
codeqa
def set es key lookup dict term value value dict value key find es dict by key lookup dict term if value dict is not None value dict[value key] valuereturn Truereturn False
null
null
null
null
Question: What does the code look ? Code: def set_es_key(lookup_dict, term, value): (value_dict, value_key) = _find_es_dict_by_key(lookup_dict, term) if (value_dict is not None): value_dict[value_key] = value return True return False
null
null
null
Till when be the storage format not be stable ?
def read_msgpack(path_or_buf, encoding='utf-8', iterator=False, **kwargs): (path_or_buf, _, _) = get_filepath_or_buffer(path_or_buf) if iterator: return Iterator(path_or_buf) def read(fh): l = list(unpack(fh, encoding=encoding, **kwargs)) if (len(l) == 1): return l[0] return l if isinstance(path_or_buf, compat.string_types): try: exists = os.path.exists(path_or_buf) except (TypeError, ValueError): exists = False if exists: with open(path_or_buf, 'rb') as fh: return read(fh) if isinstance(path_or_buf, compat.binary_type): fh = None try: fh = compat.BytesIO(path_or_buf) return read(fh) finally: if (fh is not None): fh.close() if (hasattr(path_or_buf, 'read') and compat.callable(path_or_buf.read)): return read(path_or_buf) raise ValueError('path_or_buf needs to be a string file path or file-like')
null
null
null
until a future release
codeqa
def read msgpack path or buf encoding 'utf- 8 ' iterator False **kwargs path or buf get filepath or buffer path or buf if iterator return Iterator path or buf def read fh l list unpack fh encoding encoding **kwargs if len l 1 return l[ 0 ]return lif isinstance path or buf compat string types try exists os path exists path or buf except Type Error Value Error exists Falseif exists with open path or buf 'rb' as fh return read fh if isinstance path or buf compat binary type fh Nonetry fh compat Bytes IO path or buf return read fh finally if fh is not None fh close if hasattr path or buf 'read' and compat callable path or buf read return read path or buf raise Value Error 'path or bufneedstobeastringfilepathorfile-like'
null
null
null
null
Question: Till when be the storage format not be stable ? Code: def read_msgpack(path_or_buf, encoding='utf-8', iterator=False, **kwargs): (path_or_buf, _, _) = get_filepath_or_buffer(path_or_buf) if iterator: return Iterator(path_or_buf) def read(fh): l = list(unpack(fh, encoding=encoding, **kwargs)) if (len(l) == 1): return l[0] return l if isinstance(path_or_buf, compat.string_types): try: exists = os.path.exists(path_or_buf) except (TypeError, ValueError): exists = False if exists: with open(path_or_buf, 'rb') as fh: return read(fh) if isinstance(path_or_buf, compat.binary_type): fh = None try: fh = compat.BytesIO(path_or_buf) return read(fh) finally: if (fh is not None): fh.close() if (hasattr(path_or_buf, 'read') and compat.callable(path_or_buf.read)): return read(path_or_buf) raise ValueError('path_or_buf needs to be a string file path or file-like')
null
null
null
For what purpose did the offset need ?
def _find_id3v1(fileobj): extra_read = 'APETAGEX'.index('TAG') try: fileobj.seek(((-128) - extra_read), 2) except IOError as e: if (e.errno == errno.EINVAL): fileobj.seek(0, 0) else: raise data = fileobj.read((128 + extra_read)) try: idx = data.index('TAG') except ValueError: return (None, 0) else: try: ape_idx = data.index('APETAGEX') except ValueError: pass else: if (idx == (ape_idx + extra_read)): return (None, 0) tag = ParseID3v1(data[idx:]) if (tag is None): return (None, 0) offset = (idx - len(data)) return (tag, offset)
null
null
null
to delete them
codeqa
def find id 3 v 1 fileobj extra read 'APETAGEX' index 'TAG' try fileobj seek -128 - extra read 2 except IO Error as e if e errno errno EINVAL fileobj seek 0 0 else raisedata fileobj read 128 + extra read try idx data index 'TAG' except Value Error return None 0 else try ape idx data index 'APETAGEX' except Value Error passelse if idx ape idx + extra read return None 0 tag Parse ID 3 v 1 data[idx ] if tag is None return None 0 offset idx - len data return tag offset
null
null
null
null
Question: For what purpose did the offset need ? Code: def _find_id3v1(fileobj): extra_read = 'APETAGEX'.index('TAG') try: fileobj.seek(((-128) - extra_read), 2) except IOError as e: if (e.errno == errno.EINVAL): fileobj.seek(0, 0) else: raise data = fileobj.read((128 + extra_read)) try: idx = data.index('TAG') except ValueError: return (None, 0) else: try: ape_idx = data.index('APETAGEX') except ValueError: pass else: if (idx == (ape_idx + extra_read)): return (None, 0) tag = ParseID3v1(data[idx:]) if (tag is None): return (None, 0) offset = (idx - len(data)) return (tag, offset)
null
null
null
What did we write in some cases ?
def _find_id3v1(fileobj): extra_read = 'APETAGEX'.index('TAG') try: fileobj.seek(((-128) - extra_read), 2) except IOError as e: if (e.errno == errno.EINVAL): fileobj.seek(0, 0) else: raise data = fileobj.read((128 + extra_read)) try: idx = data.index('TAG') except ValueError: return (None, 0) else: try: ape_idx = data.index('APETAGEX') except ValueError: pass else: if (idx == (ape_idx + extra_read)): return (None, 0) tag = ParseID3v1(data[idx:]) if (tag is None): return (None, 0) offset = (idx - len(data)) return (tag, offset)
null
null
null
too short tags
codeqa
def find id 3 v 1 fileobj extra read 'APETAGEX' index 'TAG' try fileobj seek -128 - extra read 2 except IO Error as e if e errno errno EINVAL fileobj seek 0 0 else raisedata fileobj read 128 + extra read try idx data index 'TAG' except Value Error return None 0 else try ape idx data index 'APETAGEX' except Value Error passelse if idx ape idx + extra read return None 0 tag Parse ID 3 v 1 data[idx ] if tag is None return None 0 offset idx - len data return tag offset
null
null
null
null
Question: What did we write in some cases ? Code: def _find_id3v1(fileobj): extra_read = 'APETAGEX'.index('TAG') try: fileobj.seek(((-128) - extra_read), 2) except IOError as e: if (e.errno == errno.EINVAL): fileobj.seek(0, 0) else: raise data = fileobj.read((128 + extra_read)) try: idx = data.index('TAG') except ValueError: return (None, 0) else: try: ape_idx = data.index('APETAGEX') except ValueError: pass else: if (idx == (ape_idx + extra_read)): return (None, 0) tag = ParseID3v1(data[idx:]) if (tag is None): return (None, 0) offset = (idx - len(data)) return (tag, offset)
null
null
null
Where did we write too short tags ?
def _find_id3v1(fileobj): extra_read = 'APETAGEX'.index('TAG') try: fileobj.seek(((-128) - extra_read), 2) except IOError as e: if (e.errno == errno.EINVAL): fileobj.seek(0, 0) else: raise data = fileobj.read((128 + extra_read)) try: idx = data.index('TAG') except ValueError: return (None, 0) else: try: ape_idx = data.index('APETAGEX') except ValueError: pass else: if (idx == (ape_idx + extra_read)): return (None, 0) tag = ParseID3v1(data[idx:]) if (tag is None): return (None, 0) offset = (idx - len(data)) return (tag, offset)
null
null
null
in some cases
codeqa
def find id 3 v 1 fileobj extra read 'APETAGEX' index 'TAG' try fileobj seek -128 - extra read 2 except IO Error as e if e errno errno EINVAL fileobj seek 0 0 else raisedata fileobj read 128 + extra read try idx data index 'TAG' except Value Error return None 0 else try ape idx data index 'APETAGEX' except Value Error passelse if idx ape idx + extra read return None 0 tag Parse ID 3 v 1 data[idx ] if tag is None return None 0 offset idx - len data return tag offset
null
null
null
null
Question: Where did we write too short tags ? Code: def _find_id3v1(fileobj): extra_read = 'APETAGEX'.index('TAG') try: fileobj.seek(((-128) - extra_read), 2) except IOError as e: if (e.errno == errno.EINVAL): fileobj.seek(0, 0) else: raise data = fileobj.read((128 + extra_read)) try: idx = data.index('TAG') except ValueError: return (None, 0) else: try: ape_idx = data.index('APETAGEX') except ValueError: pass else: if (idx == (ape_idx + extra_read)): return (None, 0) tag = ParseID3v1(data[idx:]) if (tag is None): return (None, 0) offset = (idx - len(data)) return (tag, offset)
null
null
null
What does the code ensure ?
def ensuredir(path): try: os.makedirs(path) except OSError as err: if (not (err.errno == 17)): raise
null
null
null
that a path exists
codeqa
def ensuredir path try os makedirs path except OS Error as err if not err errno 17 raise
null
null
null
null
Question: What does the code ensure ? Code: def ensuredir(path): try: os.makedirs(path) except OSError as err: if (not (err.errno == 17)): raise
null
null
null
How do a process start simply ?
@pytest.mark.qt_log_ignore('QIODevice::read.*: WriteOnly device') def test_start_mode(proc, qtbot, py_proc): with qtbot.waitSignals([proc.started, proc.finished], timeout=10000, order='strict'): argv = py_proc("import sys; print('test'); sys.exit(0)") proc.start(mode=QIODevice.NotOpen, *argv) assert (not proc._proc.readAll())
null
null
null
with mode parameter
codeqa
@pytest mark qt log ignore 'QIO Device read * Write Onlydevice' def test start mode proc qtbot py proc with qtbot wait Signals [proc started proc finished] timeout 10000 order 'strict' argv py proc "importsys print 'test' sys exit 0 " proc start mode QIO Device Not Open *argv assert not proc proc read All
null
null
null
null
Question: How do a process start simply ? Code: @pytest.mark.qt_log_ignore('QIODevice::read.*: WriteOnly device') def test_start_mode(proc, qtbot, py_proc): with qtbot.waitSignals([proc.started, proc.finished], timeout=10000, order='strict'): argv = py_proc("import sys; print('test'); sys.exit(0)") proc.start(mode=QIODevice.NotOpen, *argv) assert (not proc._proc.readAll())
null
null
null
How does the code get paths ?
def getPathsByKey(key, xmlElement): if (key not in xmlElement.attributeDictionary): return [] word = str(xmlElement.attributeDictionary[key]).strip() evaluatedLinkValue = getEvaluatedLinkValue(word, xmlElement) if ((evaluatedLinkValue.__class__ == dict) or (evaluatedLinkValue.__class__ == list)): convertToPaths(evaluatedLinkValue) return getPathsByLists(evaluatedLinkValue) xmlElementObject = getXMLElementObject(evaluatedLinkValue) if (xmlElementObject == None): return [] return xmlElementObject.getPaths()
null
null
null
by key
codeqa
def get Paths By Key key xml Element if key not in xml Element attribute Dictionary return []word str xml Element attribute Dictionary[key] strip evaluated Link Value get Evaluated Link Value word xml Element if evaluated Link Value class dict or evaluated Link Value class list convert To Paths evaluated Link Value return get Paths By Lists evaluated Link Value xml Element Object get XML Element Object evaluated Link Value if xml Element Object None return []return xml Element Object get Paths
null
null
null
null
Question: How does the code get paths ? Code: def getPathsByKey(key, xmlElement): if (key not in xmlElement.attributeDictionary): return [] word = str(xmlElement.attributeDictionary[key]).strip() evaluatedLinkValue = getEvaluatedLinkValue(word, xmlElement) if ((evaluatedLinkValue.__class__ == dict) or (evaluatedLinkValue.__class__ == list)): convertToPaths(evaluatedLinkValue) return getPathsByLists(evaluatedLinkValue) xmlElementObject = getXMLElementObject(evaluatedLinkValue) if (xmlElementObject == None): return [] return xmlElementObject.getPaths()
null
null
null
What does the code get by key ?
def getPathsByKey(key, xmlElement): if (key not in xmlElement.attributeDictionary): return [] word = str(xmlElement.attributeDictionary[key]).strip() evaluatedLinkValue = getEvaluatedLinkValue(word, xmlElement) if ((evaluatedLinkValue.__class__ == dict) or (evaluatedLinkValue.__class__ == list)): convertToPaths(evaluatedLinkValue) return getPathsByLists(evaluatedLinkValue) xmlElementObject = getXMLElementObject(evaluatedLinkValue) if (xmlElementObject == None): return [] return xmlElementObject.getPaths()
null
null
null
paths
codeqa
def get Paths By Key key xml Element if key not in xml Element attribute Dictionary return []word str xml Element attribute Dictionary[key] strip evaluated Link Value get Evaluated Link Value word xml Element if evaluated Link Value class dict or evaluated Link Value class list convert To Paths evaluated Link Value return get Paths By Lists evaluated Link Value xml Element Object get XML Element Object evaluated Link Value if xml Element Object None return []return xml Element Object get Paths
null
null
null
null
Question: What does the code get by key ? Code: def getPathsByKey(key, xmlElement): if (key not in xmlElement.attributeDictionary): return [] word = str(xmlElement.attributeDictionary[key]).strip() evaluatedLinkValue = getEvaluatedLinkValue(word, xmlElement) if ((evaluatedLinkValue.__class__ == dict) or (evaluatedLinkValue.__class__ == list)): convertToPaths(evaluatedLinkValue) return getPathsByLists(evaluatedLinkValue) xmlElementObject = getXMLElementObject(evaluatedLinkValue) if (xmlElementObject == None): return [] return xmlElementObject.getPaths()
null
null
null
What does the code convert to its boolean value ?
def asbool(s): if (s.lower() == 'true'): return True elif (s.lower() == 'false'): return False elif s.isdigit(): return bool(int(s)) else: raise ValueError(('must be integer or boolean: %r' % s))
null
null
null
a string
codeqa
def asbool s if s lower 'true' return Trueelif s lower 'false' return Falseelif s isdigit return bool int s else raise Value Error 'mustbeintegerorboolean %r' % s
null
null
null
null
Question: What does the code convert to its boolean value ? Code: def asbool(s): if (s.lower() == 'true'): return True elif (s.lower() == 'false'): return False elif s.isdigit(): return bool(int(s)) else: raise ValueError(('must be integer or boolean: %r' % s))
null
null
null
What does the code see ?
def _dict_object_help(object_name, path, parent_object_names): attributes = list(graph_reference.get_valid_attributes(object_name, parent_object_names)) attributes.sort() lines = textwrap.wrap(repr(list(attributes)), width=((LINE_SIZE - TAB_SIZE) - 1)) help_dict = {'object_name': object_name, 'path_string': (('[' + ']['.join((repr(k) for k in path))) + ']'), 'parent_object_names': parent_object_names, 'attributes_string': (' DCTB ' + '\n DCTB '.join(lines))} return "Valid attributes for '{object_name}' at path {path_string} under parents {parent_object_names}:\n\n{attributes_string}\n\nRun `<{object_name}-object>.help('attribute')` on any of the above.\n'<{object_name}-object>' is the object at {path_string}".format(**help_dict)
null
null
null
get_help
codeqa
def dict object help object name path parent object names attributes list graph reference get valid attributes object name parent object names attributes sort lines textwrap wrap repr list attributes width LINE SIZE - TAB SIZE - 1 help dict {'object name' object name 'path string' '[' + '][' join repr k for k in path + ']' 'parent object names' parent object names 'attributes string' ' DCTB ' + '\n DCTB ' join lines }return " Validattributesfor'{object name}'atpath{path string}underparents{parent object names} \n\n{attributes string}\n\n Run`<{object name}-object> help 'attribute' `onanyoftheabove \n'<{object name}-object>'istheobjectat{path string}" format **help dict
null
null
null
null
Question: What does the code see ? Code: def _dict_object_help(object_name, path, parent_object_names): attributes = list(graph_reference.get_valid_attributes(object_name, parent_object_names)) attributes.sort() lines = textwrap.wrap(repr(list(attributes)), width=((LINE_SIZE - TAB_SIZE) - 1)) help_dict = {'object_name': object_name, 'path_string': (('[' + ']['.join((repr(k) for k in path))) + ']'), 'parent_object_names': parent_object_names, 'attributes_string': (' DCTB ' + '\n DCTB '.join(lines))} return "Valid attributes for '{object_name}' at path {path_string} under parents {parent_object_names}:\n\n{attributes_string}\n\nRun `<{object_name}-object>.help('attribute')` on any of the above.\n'<{object_name}-object>' is the object at {path_string}".format(**help_dict)
null
null
null
How can by reference counting be freed an object ?
@contextmanager def assert_deallocated(func, *args, **kwargs): with gc_state(False): obj = func(*args, **kwargs) ref = weakref.ref(obj) (yield obj) del obj if (ref() is not None): raise ReferenceError('Remaining reference(s) to object')
null
null
null
directly
codeqa
@contextmanagerdef assert deallocated func *args **kwargs with gc state False obj func *args **kwargs ref weakref ref obj yield obj del objif ref is not None raise Reference Error ' Remainingreference s toobject'
null
null
null
null
Question: How can by reference counting be freed an object ? Code: @contextmanager def assert_deallocated(func, *args, **kwargs): with gc_state(False): obj = func(*args, **kwargs) ref = weakref.ref(obj) (yield obj) del obj if (ref() is not None): raise ReferenceError('Remaining reference(s) to object')
null
null
null
What does the code convert to string ?
def timestampMac32(value): if (not isinstance(value, (float, int, long))): raise TypeError('an integer or float is required') if (not (0 <= value <= 4294967295)): return (_('invalid Mac timestamp (%s)') % value) return (MAC_TIMESTAMP_T0 + timedelta(seconds=value))
null
null
null
an mac timestamp
codeqa
def timestamp Mac 32 value if not isinstance value float int long raise Type Error 'anintegerorfloatisrequired' if not 0 < value < 4294967295 return 'invalid Mactimestamp %s ' % value return MAC TIMESTAMP T0 + timedelta seconds value
null
null
null
null
Question: What does the code convert to string ? Code: def timestampMac32(value): if (not isinstance(value, (float, int, long))): raise TypeError('an integer or float is required') if (not (0 <= value <= 4294967295)): return (_('invalid Mac timestamp (%s)') % value) return (MAC_TIMESTAMP_T0 + timedelta(seconds=value))
null
null
null
What does the code create ?
def get_admin_context(show_deleted=False): return RequestContext(auth_token=None, tenant=None, is_admin=True, show_deleted=show_deleted, overwrite=False)
null
null
null
an administrator context
codeqa
def get admin context show deleted False return Request Context auth token None tenant None is admin True show deleted show deleted overwrite False
null
null
null
null
Question: What does the code create ? Code: def get_admin_context(show_deleted=False): return RequestContext(auth_token=None, tenant=None, is_admin=True, show_deleted=show_deleted, overwrite=False)
null
null
null
What does the code take ?
def convert_wo_prefix(string): factors = {'K': 1000, 'M': (1000 * 1000), 'G': ((1000 * 1000) * 1000), 'T': (((1000 * 1000) * 1000) * 1000), 'P': ((((1000 * 1000) * 1000) * 1000) * 1000), 'E': (((((1000 * 1000) * 1000) * 1000) * 1000) * 1000)} if (string == '-'): return (-1) for (f, fm) in factors.items(): if string.endswith(f): number = float(string[:(-1)]) number = (number * fm) return long(number) return long(string)
null
null
null
a string in the form 1234k
codeqa
def convert wo prefix string factors {'K' 1000 'M' 1000 * 1000 'G' 1000 * 1000 * 1000 'T' 1000 * 1000 * 1000 * 1000 'P' 1000 * 1000 * 1000 * 1000 * 1000 'E' 1000 * 1000 * 1000 * 1000 * 1000 * 1000 }if string '-' return -1 for f fm in factors items if string endswith f number float string[ -1 ] number number * fm return long number return long string
null
null
null
null
Question: What does the code take ? Code: def convert_wo_prefix(string): factors = {'K': 1000, 'M': (1000 * 1000), 'G': ((1000 * 1000) * 1000), 'T': (((1000 * 1000) * 1000) * 1000), 'P': ((((1000 * 1000) * 1000) * 1000) * 1000), 'E': (((((1000 * 1000) * 1000) * 1000) * 1000) * 1000)} if (string == '-'): return (-1) for (f, fm) in factors.items(): if string.endswith(f): number = float(string[:(-1)]) number = (number * fm) return long(number) return long(string)
null
null
null
What determines a list of packages ?
def get_parser(): parser = argparse.ArgumentParser(description='google-cloud tests runner.') help_msg = 'List of packages to be tested. If left blank, tests all packages.' parser.add_argument('packages', nargs='*', default=ALL_MODULES, help=help_msg) return parser
null
null
null
an argument parser
codeqa
def get parser parser argparse Argument Parser description 'google-cloudtestsrunner ' help msg ' Listofpackagestobetested Ifleftblank testsallpackages 'parser add argument 'packages' nargs '*' default ALL MODULES help help msg return parser
null
null
null
null
Question: What determines a list of packages ? Code: def get_parser(): parser = argparse.ArgumentParser(description='google-cloud tests runner.') help_msg = 'List of packages to be tested. If left blank, tests all packages.' parser.add_argument('packages', nargs='*', default=ALL_MODULES, help=help_msg) return parser
null
null
null
What do an argument parser determine ?
def get_parser(): parser = argparse.ArgumentParser(description='google-cloud tests runner.') help_msg = 'List of packages to be tested. If left blank, tests all packages.' parser.add_argument('packages', nargs='*', default=ALL_MODULES, help=help_msg) return parser
null
null
null
a list of packages
codeqa
def get parser parser argparse Argument Parser description 'google-cloudtestsrunner ' help msg ' Listofpackagestobetested Ifleftblank testsallpackages 'parser add argument 'packages' nargs '*' default ALL MODULES help help msg return parser
null
null
null
null
Question: What do an argument parser determine ? Code: def get_parser(): parser = argparse.ArgumentParser(description='google-cloud tests runner.') help_msg = 'List of packages to be tested. If left blank, tests all packages.' parser.add_argument('packages', nargs='*', default=ALL_MODULES, help=help_msg) return parser
null
null
null
What does the code get ?
def get_parser(): parser = argparse.ArgumentParser(description='google-cloud tests runner.') help_msg = 'List of packages to be tested. If left blank, tests all packages.' parser.add_argument('packages', nargs='*', default=ALL_MODULES, help=help_msg) return parser
null
null
null
an argument parser to determine a list of packages
codeqa
def get parser parser argparse Argument Parser description 'google-cloudtestsrunner ' help msg ' Listofpackagestobetested Ifleftblank testsallpackages 'parser add argument 'packages' nargs '*' default ALL MODULES help help msg return parser
null
null
null
null
Question: What does the code get ? Code: def get_parser(): parser = argparse.ArgumentParser(description='google-cloud tests runner.') help_msg = 'List of packages to be tested. If left blank, tests all packages.' parser.add_argument('packages', nargs='*', default=ALL_MODULES, help=help_msg) return parser
null
null
null
What needs to log in ?
@simple_decorator def check_login_required(view_func): def _check(*args, **kwargs): siteconfig = SiteConfiguration.objects.get_current() if siteconfig.get(u'auth_require_sitewide_login'): return login_required(view_func)(*args, **kwargs) else: return view_func(*args, **kwargs) return _check
null
null
null
the user
codeqa
@simple decoratordef check login required view func def check *args **kwargs siteconfig Site Configuration objects get current if siteconfig get u'auth require sitewide login' return login required view func *args **kwargs else return view func *args **kwargs return check
null
null
null
null
Question: What needs to log in ? Code: @simple_decorator def check_login_required(view_func): def _check(*args, **kwargs): siteconfig = SiteConfiguration.objects.get_current() if siteconfig.get(u'auth_require_sitewide_login'): return login_required(view_func)(*args, **kwargs) else: return view_func(*args, **kwargs) return _check
null
null
null
How does the code play the files in the path ?
def play_complicated(paths): my_paths = copy.copy(paths) def next_song(): my_paths.pop(0) p.play_file(my_paths[0]) p = GstPlayer(next_song) p.run() p.play_file(my_paths[0]) while my_paths: time.sleep(1)
null
null
null
one after the other
codeqa
def play complicated paths my paths copy copy paths def next song my paths pop 0 p play file my paths[ 0 ] p Gst Player next song p run p play file my paths[ 0 ] while my paths time sleep 1
null
null
null
null
Question: How does the code play the files in the path ? Code: def play_complicated(paths): my_paths = copy.copy(paths) def next_song(): my_paths.pop(0) p.play_file(my_paths[0]) p = GstPlayer(next_song) p.run() p.play_file(my_paths[0]) while my_paths: time.sleep(1)
null
null
null
What is using to advance to the next song ?
def play_complicated(paths): my_paths = copy.copy(paths) def next_song(): my_paths.pop(0) p.play_file(my_paths[0]) p = GstPlayer(next_song) p.run() p.play_file(my_paths[0]) while my_paths: time.sleep(1)
null
null
null
the callback function
codeqa
def play complicated paths my paths copy copy paths def next song my paths pop 0 p play file my paths[ 0 ] p Gst Player next song p run p play file my paths[ 0 ] while my paths time sleep 1
null
null
null
null
Question: What is using to advance to the next song ? Code: def play_complicated(paths): my_paths = copy.copy(paths) def next_song(): my_paths.pop(0) p.play_file(my_paths[0]) p = GstPlayer(next_song) p.run() p.play_file(my_paths[0]) while my_paths: time.sleep(1)
null
null
null
What converts into a method decorator ?
def method_decorator(decorator): def _dec(func): def _wrapper(self, *args, **kwargs): def bound_func(*args2, **kwargs2): return func(self, *args2, **kwargs2) return decorator(bound_func)(*args, **kwargs) return wraps(func)(_wrapper) update_wrapper(_dec, decorator) _dec.__name__ = ('method_decorator(%s)' % decorator.__name__) return _dec
null
null
null
a function decorator
codeqa
def method decorator decorator def dec func def wrapper self *args **kwargs def bound func *args 2 **kwargs 2 return func self *args 2 **kwargs 2 return decorator bound func *args **kwargs return wraps func wrapper update wrapper dec decorator dec name 'method decorator %s ' % decorator name return dec
null
null
null
null
Question: What converts into a method decorator ? Code: def method_decorator(decorator): def _dec(func): def _wrapper(self, *args, **kwargs): def bound_func(*args2, **kwargs2): return func(self, *args2, **kwargs2) return decorator(bound_func)(*args, **kwargs) return wraps(func)(_wrapper) update_wrapper(_dec, decorator) _dec.__name__ = ('method_decorator(%s)' % decorator.__name__) return _dec
null
null
null
What does a function decorator convert ?
def method_decorator(decorator): def _dec(func): def _wrapper(self, *args, **kwargs): def bound_func(*args2, **kwargs2): return func(self, *args2, **kwargs2) return decorator(bound_func)(*args, **kwargs) return wraps(func)(_wrapper) update_wrapper(_dec, decorator) _dec.__name__ = ('method_decorator(%s)' % decorator.__name__) return _dec
null
null
null
into a method decorator
codeqa
def method decorator decorator def dec func def wrapper self *args **kwargs def bound func *args 2 **kwargs 2 return func self *args 2 **kwargs 2 return decorator bound func *args **kwargs return wraps func wrapper update wrapper dec decorator dec name 'method decorator %s ' % decorator name return dec
null
null
null
null
Question: What does a function decorator convert ? Code: def method_decorator(decorator): def _dec(func): def _wrapper(self, *args, **kwargs): def bound_func(*args2, **kwargs2): return func(self, *args2, **kwargs2) return decorator(bound_func)(*args, **kwargs) return wraps(func)(_wrapper) update_wrapper(_dec, decorator) _dec.__name__ = ('method_decorator(%s)' % decorator.__name__) return _dec
null
null
null
What does the code clean ?
def metric_cleanup(): __worker__.shutdown()
null
null
null
the metric module
codeqa
def metric cleanup worker shutdown
null
null
null
null
Question: What does the code clean ? Code: def metric_cleanup(): __worker__.shutdown()
null
null
null
What does the code open ?
def OpenFileForRead(path, logtext): frame = None file = None if (not path): return (frame, file) try: if path.endswith('.gz'): frame = open(path, 'rb') file = gzip.GzipFile(fileobj=frame, mode='rt') else: file = open(path, 'rt') if logtext: output.Log(('Opened %s file: %s' % (logtext, path)), 1) else: output.Log(('Opened file: %s' % path), 1) except IOError: output.Error(('Can not open file: %s' % path)) return (frame, file)
null
null
null
a text file
codeqa
def Open File For Read path logtext frame Nonefile Noneif not path return frame file try if path endswith ' gz' frame open path 'rb' file gzip Gzip File fileobj frame mode 'rt' else file open path 'rt' if logtext output Log ' Opened%sfile %s' % logtext path 1 else output Log ' Openedfile %s' % path 1 except IO Error output Error ' Cannotopenfile %s' % path return frame file
null
null
null
null
Question: What does the code open ? Code: def OpenFileForRead(path, logtext): frame = None file = None if (not path): return (frame, file) try: if path.endswith('.gz'): frame = open(path, 'rb') file = gzip.GzipFile(fileobj=frame, mode='rt') else: file = open(path, 'rt') if logtext: output.Log(('Opened %s file: %s' % (logtext, path)), 1) else: output.Log(('Opened file: %s' % path), 1) except IOError: output.Error(('Can not open file: %s' % path)) return (frame, file)
null
null
null
Where did brute force ?
def constrainedAES(s): small_key = helpers.randomKey(26) real_key = (small_key + str(helpers.randomNumbers())) cipher = AES.new(real_key) encrypted = EncodeAES(cipher, s) return (encrypted, small_key, real_key)
null
null
null
in a loop
codeqa
def constrained AES s small key helpers random Key 26 real key small key + str helpers random Numbers cipher AES new real key encrypted Encode AES cipher s return encrypted small key real key
null
null
null
null
Question: Where did brute force ? Code: def constrainedAES(s): small_key = helpers.randomKey(26) real_key = (small_key + str(helpers.randomNumbers())) cipher = AES.new(real_key) encrypted = EncodeAES(cipher, s) return (encrypted, small_key, real_key)
null
null
null
What forced in a loop ?
def constrainedAES(s): small_key = helpers.randomKey(26) real_key = (small_key + str(helpers.randomNumbers())) cipher = AES.new(real_key) encrypted = EncodeAES(cipher, s) return (encrypted, small_key, real_key)
null
null
null
brute
codeqa
def constrained AES s small key helpers random Key 26 real key small key + str helpers random Numbers cipher AES new real key encrypted Encode AES cipher s return encrypted small key real key
null
null
null
null
Question: What forced in a loop ? Code: def constrainedAES(s): small_key = helpers.randomKey(26) real_key = (small_key + str(helpers.randomNumbers())) cipher = AES.new(real_key) encrypted = EncodeAES(cipher, s) return (encrypted, small_key, real_key)
null
null
null
What does the code create ?
def BetaPrime(name, alpha, beta): return rv(name, BetaPrimeDistribution, (alpha, beta))
null
null
null
a continuous random variable with a beta prime distribution
codeqa
def Beta Prime name alpha beta return rv name Beta Prime Distribution alpha beta
null
null
null
null
Question: What does the code create ? Code: def BetaPrime(name, alpha, beta): return rv(name, BetaPrimeDistribution, (alpha, beta))
null
null
null
What does the code delete from a queue ?
def delete(queue, items): with _conn(commit=True) as cur: if isinstance(items, dict): cmd = "DELETE FROM {0} WHERE data = '{1}'".format(queue, json.dumps(items)) log.debug('SQL Query: {0}'.format(cmd)) cur.execute(cmd) return True if isinstance(items, list): items = [json.dumps(el) for el in items] cmd = 'DELETE FROM {0} WHERE data = %s'.format(queue) log.debug('SQL Query: {0}'.format(cmd)) newitems = [] for item in items: newitems.append((item,)) cur.executemany(cmd, newitems) return True
null
null
null
an item or items
codeqa
def delete queue items with conn commit True as cur if isinstance items dict cmd "DELETEFROM{ 0 }WHER Edata '{ 1 }'" format queue json dumps items log debug 'SQL Query {0 }' format cmd cur execute cmd return Trueif isinstance items list items [json dumps el for el in items]cmd 'DELETEFROM{ 0 }WHER Edata %s' format queue log debug 'SQL Query {0 }' format cmd newitems []for item in items newitems append item cur executemany cmd newitems return True
null
null
null
null
Question: What does the code delete from a queue ? Code: def delete(queue, items): with _conn(commit=True) as cur: if isinstance(items, dict): cmd = "DELETE FROM {0} WHERE data = '{1}'".format(queue, json.dumps(items)) log.debug('SQL Query: {0}'.format(cmd)) cur.execute(cmd) return True if isinstance(items, list): items = [json.dumps(el) for el in items] cmd = 'DELETE FROM {0} WHERE data = %s'.format(queue) log.debug('SQL Query: {0}'.format(cmd)) newitems = [] for item in items: newitems.append((item,)) cur.executemany(cmd, newitems) return True
null
null
null
What does context - manager select ?
@contextlib.contextmanager def stream(stream): if (stream is None): (yield) return prev_stream = current_stream() torch._C._cuda_setStream(stream._cdata) try: (yield) finally: torch._C._cuda_setStream(prev_stream._cdata)
null
null
null
a given stream
codeqa
@contextlib contextmanagerdef stream stream if stream is None yield returnprev stream current stream torch C cuda set Stream stream cdata try yield finally torch C cuda set Stream prev stream cdata
null
null
null
null
Question: What does context - manager select ? Code: @contextlib.contextmanager def stream(stream): if (stream is None): (yield) return prev_stream = current_stream() torch._C._cuda_setStream(stream._cdata) try: (yield) finally: torch._C._cuda_setStream(prev_stream._cdata)
null
null
null
What selects a given stream ?
@contextlib.contextmanager def stream(stream): if (stream is None): (yield) return prev_stream = current_stream() torch._C._cuda_setStream(stream._cdata) try: (yield) finally: torch._C._cuda_setStream(prev_stream._cdata)
null
null
null
context - manager
codeqa
@contextlib contextmanagerdef stream stream if stream is None yield returnprev stream current stream torch C cuda set Stream stream cdata try yield finally torch C cuda set Stream prev stream cdata
null
null
null
null
Question: What selects a given stream ? Code: @contextlib.contextmanager def stream(stream): if (stream is None): (yield) return prev_stream = current_stream() torch._C._cuda_setStream(stream._cdata) try: (yield) finally: torch._C._cuda_setStream(prev_stream._cdata)
null
null
null
When did date modify ?
def calc_last_modified(request, *args, **kwargs): assert ('cache_name' in kwargs), 'Must specify cache_name as a keyword arg.' try: cache = get_cache(kwargs['cache_name']) assert (isinstance(cache, FileBasedCache) or isinstance(cache, LocMemCache)), 'requires file-based or mem-based cache.' except InvalidCacheBackendError: return None key = django_get_cache_key(request, cache=cache) if ((key is None) or (not cache.has_key(key))): return None if isinstance(cache, FileBasedCache): fname = cache._key_to_file(cache.make_key(key)) if (not os.path.exists(fname)): return None last_modified = datetime.datetime.fromtimestamp(os.path.getmtime(fname)) elif isinstance(cache, LocMemCache): creation_time = (cache._expire_info[cache.make_key(key)] - settings.CACHE_TIME) last_modified = datetime.datetime.fromtimestamp(creation_time) return last_modified
null
null
null
last
codeqa
def calc last modified request *args **kwargs assert 'cache name' in kwargs ' Mustspecifycache nameasakeywordarg 'try cache get cache kwargs['cache name'] assert isinstance cache File Based Cache or isinstance cache Loc Mem Cache 'requiresfile-basedormem-basedcache 'except Invalid Cache Backend Error return Nonekey django get cache key request cache cache if key is None or not cache has key key return Noneif isinstance cache File Based Cache fname cache key to file cache make key key if not os path exists fname return Nonelast modified datetime datetime fromtimestamp os path getmtime fname elif isinstance cache Loc Mem Cache creation time cache expire info[cache make key key ] - settings CACHE TIME last modified datetime datetime fromtimestamp creation time return last modified
null
null
null
null
Question: When did date modify ? Code: def calc_last_modified(request, *args, **kwargs): assert ('cache_name' in kwargs), 'Must specify cache_name as a keyword arg.' try: cache = get_cache(kwargs['cache_name']) assert (isinstance(cache, FileBasedCache) or isinstance(cache, LocMemCache)), 'requires file-based or mem-based cache.' except InvalidCacheBackendError: return None key = django_get_cache_key(request, cache=cache) if ((key is None) or (not cache.has_key(key))): return None if isinstance(cache, FileBasedCache): fname = cache._key_to_file(cache.make_key(key)) if (not os.path.exists(fname)): return None last_modified = datetime.datetime.fromtimestamp(os.path.getmtime(fname)) elif isinstance(cache, LocMemCache): creation_time = (cache._expire_info[cache.make_key(key)] - settings.CACHE_TIME) last_modified = datetime.datetime.fromtimestamp(creation_time) return last_modified
null
null
null
What does the code compute ?
def sparse_block_dot(W, h, inputIdx, b, outputIdx): assert (inputIdx.ndim == (h.ndim - 1)) assert (outputIdx.ndim == inputIdx.ndim) if (h.ndim == 2): h = h.dimshuffle('x', 0, 1) inputIdx = inputIdx.dimshuffle('x', 0) outputIdx = outputIdx.dimshuffle('x', 0) return SparseBlockGemv()(b.take(outputIdx, axis=0), W, h, inputIdx, outputIdx)
null
null
null
the dot product of the specified pieces of vectors and matrices
codeqa
def sparse block dot W h input Idx b output Idx assert input Idx ndim h ndim - 1 assert output Idx ndim input Idx ndim if h ndim 2 h h dimshuffle 'x' 0 1 input Idx input Idx dimshuffle 'x' 0 output Idx output Idx dimshuffle 'x' 0 return Sparse Block Gemv b take output Idx axis 0 W h input Idx output Idx
null
null
null
null
Question: What does the code compute ? Code: def sparse_block_dot(W, h, inputIdx, b, outputIdx): assert (inputIdx.ndim == (h.ndim - 1)) assert (outputIdx.ndim == inputIdx.ndim) if (h.ndim == 2): h = h.dimshuffle('x', 0, 1) inputIdx = inputIdx.dimshuffle('x', 0) outputIdx = outputIdx.dimshuffle('x', 0) return SparseBlockGemv()(b.take(outputIdx, axis=0), W, h, inputIdx, outputIdx)
null
null
null
Who earned it ?
@task() @timeit def maybe_award_badge(badge_template, year, user): badge = get_or_create_badge(badge_template, year) if badge.is_awarded_to(user): return qs = Revision.objects.filter(creator=user, is_approved=True, created__gte=date(year, 1, 1), created__lt=date((year + 1), 1, 1)) if (badge_template['slug'] == WIKI_BADGES['kb-badge']['slug']): qs = qs.filter(document__locale=settings.WIKI_DEFAULT_LANGUAGE) else: qs = qs.exclude(document__locale=settings.WIKI_DEFAULT_LANGUAGE) if (qs.count() >= 10): badge.award_to(user) return True
null
null
null
they
codeqa
@task @timeitdef maybe award badge badge template year user badge get or create badge badge template year if badge is awarded to user returnqs Revision objects filter creator user is approved True created gte date year 1 1 created lt date year + 1 1 1 if badge template['slug'] WIKI BADGES['kb-badge']['slug'] qs qs filter document locale settings WIKI DEFAULT LANGUAGE else qs qs exclude document locale settings WIKI DEFAULT LANGUAGE if qs count > 10 badge award to user return True
null
null
null
null
Question: Who earned it ? Code: @task() @timeit def maybe_award_badge(badge_template, year, user): badge = get_or_create_badge(badge_template, year) if badge.is_awarded_to(user): return qs = Revision.objects.filter(creator=user, is_approved=True, created__gte=date(year, 1, 1), created__lt=date((year + 1), 1, 1)) if (badge_template['slug'] == WIKI_BADGES['kb-badge']['slug']): qs = qs.filter(document__locale=settings.WIKI_DEFAULT_LANGUAGE) else: qs = qs.exclude(document__locale=settings.WIKI_DEFAULT_LANGUAGE) if (qs.count() >= 10): badge.award_to(user) return True
null
null
null
which organization % u encoding ?
def msu_encoding(t): full = (c.encode('hex_codec').zfill(4) for c in t.decode('utf8')) uppr = (x.upper() for x in full) return ('%U' + '%U'.join(uppr))
null
null
null
microsoft
codeqa
def msu encoding t full c encode 'hex codec' zfill 4 for c in t decode 'utf 8 ' uppr x upper for x in full return '%U' + '%U' join uppr
null
null
null
null
Question: which organization % u encoding ? Code: def msu_encoding(t): full = (c.encode('hex_codec').zfill(4) for c in t.decode('utf8')) uppr = (x.upper() for x in full) return ('%U' + '%U'.join(uppr))
null
null
null
How do a backup - list latest on an empty prefix list ?
@pytest.mark.skipif('no_real_wabs_credentials()') def test_empty_latest_listing(): container_name = 'wal-e-test-empty-listing' layout = storage.StorageLayout('wabs://{0}/test-prefix'.format(container_name)) with FreshContainer(container_name) as fb: fb.create() bl = BackupList(fb.conn, layout, False) found = list(bl.find_all('LATEST')) assert (len(found) == 0)
null
null
null
test
codeqa
@pytest mark skipif 'no real wabs credentials ' def test empty latest listing container name 'wal-e-test-empty-listing'layout storage Storage Layout 'wabs //{ 0 }/test-prefix' format container name with Fresh Container container name as fb fb create bl Backup List fb conn layout False found list bl find all 'LATEST' assert len found 0
null
null
null
null
Question: How do a backup - list latest on an empty prefix list ? Code: @pytest.mark.skipif('no_real_wabs_credentials()') def test_empty_latest_listing(): container_name = 'wal-e-test-empty-listing' layout = storage.StorageLayout('wabs://{0}/test-prefix'.format(container_name)) with FreshContainer(container_name) as fb: fb.create() bl = BackupList(fb.conn, layout, False) found = list(bl.find_all('LATEST')) assert (len(found) == 0)
null
null
null
What do a counter return by suffixing always ?
def dedup(l, suffix='__'): new_l = [] seen = {} for s in l: if (s in seen): seen[s] += 1 s += (suffix + str(seen[s])) else: seen[s] = 0 new_l.append(s) return new_l
null
null
null
the same number of entries as provided
codeqa
def dedup l suffix ' ' new l []seen {}for s in l if s in seen seen[s] + 1s + suffix + str seen[s] else seen[s] 0new l append s return new l
null
null
null
null
Question: What do a counter return by suffixing always ? Code: def dedup(l, suffix='__'): new_l = [] seen = {} for s in l: if (s in seen): seen[s] += 1 s += (suffix + str(seen[s])) else: seen[s] = 0 new_l.append(s) return new_l
null
null
null
What returns the same number of entries as provided by suffixing always ?
def dedup(l, suffix='__'): new_l = [] seen = {} for s in l: if (s in seen): seen[s] += 1 s += (suffix + str(seen[s])) else: seen[s] = 0 new_l.append(s) return new_l
null
null
null
a counter
codeqa
def dedup l suffix ' ' new l []seen {}for s in l if s in seen seen[s] + 1s + suffix + str seen[s] else seen[s] 0new l append s return new l
null
null
null
null
Question: What returns the same number of entries as provided by suffixing always ? Code: def dedup(l, suffix='__'): new_l = [] seen = {} for s in l: if (s in seen): seen[s] += 1 s += (suffix + str(seen[s])) else: seen[s] = 0 new_l.append(s) return new_l
null
null
null
What does the code list ?
def list_entries(logger_name): logging_client = logging.Client() logger = logging_client.logger(logger_name) print 'Listing entries for logger {}:'.format(logger.name) for entry in logger.list_entries(): timestamp = entry.timestamp.isoformat() print '* {}: {}'.format(timestamp, entry.payload)
null
null
null
the most recent entries for a given logger
codeqa
def list entries logger name logging client logging Client logger logging client logger logger name print ' Listingentriesforlogger{} ' format logger name for entry in logger list entries timestamp entry timestamp isoformat print '*{} {}' format timestamp entry payload
null
null
null
null
Question: What does the code list ? Code: def list_entries(logger_name): logging_client = logging.Client() logger = logging_client.logger(logger_name) print 'Listing entries for logger {}:'.format(logger.name) for entry in logger.list_entries(): timestamp = entry.timestamp.isoformat() print '* {}: {}'.format(timestamp, entry.payload)