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
For what purpose does the table object return ?
def get_images_table(meta): images = Table('images', meta, Column('id', Integer(), primary_key=True, nullable=False), Column('name', String(255)), Column('disk_format', String(20)), Column('container_format', String(20)), Column('size', Integer()), Column('status', String(30), nullable=False), Column('is_public', Boolean(), nullable=False, default=False, index=True), Column('location', Text()), Column('created_at', DateTime(), nullable=False), Column('updated_at', DateTime()), Column('deleted_at', DateTime()), Column('deleted', Boolean(), nullable=False, default=False, index=True), Column('checksum', String(32)), mysql_engine='InnoDB', extend_existing=True) return images
null
null
null
for the images table that corresponds to the images table definition of this version
codeqa
def get images table meta images Table 'images' meta Column 'id' Integer primary key True nullable False Column 'name' String 255 Column 'disk format' String 20 Column 'container format' String 20 Column 'size' Integer Column 'status' String 30 nullable False Column 'is public' Boolean nullable False default False index True Column 'location' Text Column 'created at' Date Time nullable False Column 'updated at' Date Time Column 'deleted at' Date Time Column 'deleted' Boolean nullable False default False index True Column 'checksum' String 32 mysql engine ' Inno DB' extend existing True return images
null
null
null
null
Question: For what purpose does the table object return ? Code: def get_images_table(meta): images = Table('images', meta, Column('id', Integer(), primary_key=True, nullable=False), Column('name', String(255)), Column('disk_format', String(20)), Column('container_format', String(20)), Column('size', Integer()), Column('status', String(30), nullable=False), Column('is_public', Boolean(), nullable=False, default=False, index=True), Column('location', Text()), Column('created_at', DateTime(), nullable=False), Column('updated_at', DateTime()), Column('deleted_at', DateTime()), Column('deleted', Boolean(), nullable=False, default=False, index=True), Column('checksum', String(32)), mysql_engine='InnoDB', extend_existing=True) return images
null
null
null
Do spaces use around the = sign in function arguments ?
def whitespace_around_named_parameter_equals(logical_line, tokens): parens = 0 no_space = False prev_end = None annotated_func_arg = False in_def = logical_line.startswith(('def', 'async def')) message = 'E251 unexpected spaces around keyword / parameter equals' for (token_type, text, start, end, line) in tokens: if (token_type == tokenize.NL): continue if no_space: no_space = False if (start != prev_end): (yield (prev_end, message)) if (token_type == tokenize.OP): if (text in '(['): parens += 1 elif (text in ')]'): parens -= 1 elif (in_def and (text == ':') and (parens == 1)): annotated_func_arg = True elif (parens and (text == ',') and (parens == 1)): annotated_func_arg = False elif (parens and (text == '=') and (not annotated_func_arg)): no_space = True if (start != prev_end): (yield (prev_end, message)) if (not parens): annotated_func_arg = False prev_end = end
null
null
null
No
codeqa
def whitespace around named parameter equals logical line tokens parens 0no space Falseprev end Noneannotated func arg Falsein def logical line startswith 'def' 'asyncdef' message 'E 251 unexpectedspacesaroundkeyword/parameterequals'for token type text start end line in tokens if token type tokenize NL continueif no space no space Falseif start prev end yield prev end message if token type tokenize OP if text in ' [' parens + 1elif text in ' ]' parens - 1elif in def and text ' ' and parens 1 annotated func arg Trueelif parens and text ' ' and parens 1 annotated func arg Falseelif parens and text ' ' and not annotated func arg no space Trueif start prev end yield prev end message if not parens annotated func arg Falseprev end end
null
null
null
null
Question: Do spaces use around the = sign in function arguments ? Code: def whitespace_around_named_parameter_equals(logical_line, tokens): parens = 0 no_space = False prev_end = None annotated_func_arg = False in_def = logical_line.startswith(('def', 'async def')) message = 'E251 unexpected spaces around keyword / parameter equals' for (token_type, text, start, end, line) in tokens: if (token_type == tokenize.NL): continue if no_space: no_space = False if (start != prev_end): (yield (prev_end, message)) if (token_type == tokenize.OP): if (text in '(['): parens += 1 elif (text in ')]'): parens -= 1 elif (in_def and (text == ':') and (parens == 1)): annotated_func_arg = True elif (parens and (text == ',') and (parens == 1)): annotated_func_arg = False elif (parens and (text == '=') and (not annotated_func_arg)): no_space = True if (start != prev_end): (yield (prev_end, message)) if (not parens): annotated_func_arg = False prev_end = end
null
null
null
What defines the accuracy of the test ?
def is_probable_prime(n, k=7): if (n < 6): return [False, False, True, True, False, True][n] if ((n & 1) == 0): return False else: (s, d) = (0, (n - 1)) while ((d & 1) == 0): (s, d) = ((s + 1), (d >> 1)) for a in random.sample(xrange(2, min((n - 2), sys.maxint)), min((n - 4), k)): x = pow(a, d, n) if ((x != 1) and ((x + 1) != n)): for r in xrange(1, s): x = pow(x, 2, n) if (x == 1): return False elif (x == (n - 1)): a = 0 break if a: return False return True
null
null
null
the parameter k
codeqa
def is probable prime n k 7 if n < 6 return [ False False True True False True][n]if n & 1 0 return Falseelse s d 0 n - 1 while d & 1 0 s d s + 1 d >> 1 for a in random sample xrange 2 min n - 2 sys maxint min n - 4 k x pow a d n if x 1 and x + 1 n for r in xrange 1 s x pow x 2 n if x 1 return Falseelif x n - 1 a 0breakif a return Falsereturn True
null
null
null
null
Question: What defines the accuracy of the test ? Code: def is_probable_prime(n, k=7): if (n < 6): return [False, False, True, True, False, True][n] if ((n & 1) == 0): return False else: (s, d) = (0, (n - 1)) while ((d & 1) == 0): (s, d) = ((s + 1), (d >> 1)) for a in random.sample(xrange(2, min((n - 2), sys.maxint)), min((n - 4), k)): x = pow(a, d, n) if ((x != 1) and ((x + 1) != n)): for r in xrange(1, s): x = pow(x, 2, n) if (x == 1): return False elif (x == (n - 1)): a = 0 break if a: return False return True
null
null
null
What use to return true or false ?
def is_probable_prime(n, k=7): if (n < 6): return [False, False, True, True, False, True][n] if ((n & 1) == 0): return False else: (s, d) = (0, (n - 1)) while ((d & 1) == 0): (s, d) = ((s + 1), (d >> 1)) for a in random.sample(xrange(2, min((n - 2), sys.maxint)), min((n - 4), k)): x = pow(a, d, n) if ((x != 1) and ((x + 1) != n)): for r in xrange(1, s): x = pow(x, 2, n) if (x == 1): return False elif (x == (n - 1)): a = 0 break if a: return False return True
null
null
null
rabin - miller algorithm
codeqa
def is probable prime n k 7 if n < 6 return [ False False True True False True][n]if n & 1 0 return Falseelse s d 0 n - 1 while d & 1 0 s d s + 1 d >> 1 for a in random sample xrange 2 min n - 2 sys maxint min n - 4 k x pow a d n if x 1 and x + 1 n for r in xrange 1 s x pow x 2 n if x 1 return Falseelif x n - 1 a 0breakif a return Falsereturn True
null
null
null
null
Question: What use to return true or false ? Code: def is_probable_prime(n, k=7): if (n < 6): return [False, False, True, True, False, True][n] if ((n & 1) == 0): return False else: (s, d) = (0, (n - 1)) while ((d & 1) == 0): (s, d) = ((s + 1), (d >> 1)) for a in random.sample(xrange(2, min((n - 2), sys.maxint)), min((n - 4), k)): x = pow(a, d, n) if ((x != 1) and ((x + 1) != n)): for r in xrange(1, s): x = pow(x, 2, n) if (x == 1): return False elif (x == (n - 1)): a = 0 break if a: return False return True
null
null
null
What do the parameter k define ?
def is_probable_prime(n, k=7): if (n < 6): return [False, False, True, True, False, True][n] if ((n & 1) == 0): return False else: (s, d) = (0, (n - 1)) while ((d & 1) == 0): (s, d) = ((s + 1), (d >> 1)) for a in random.sample(xrange(2, min((n - 2), sys.maxint)), min((n - 4), k)): x = pow(a, d, n) if ((x != 1) and ((x + 1) != n)): for r in xrange(1, s): x = pow(x, 2, n) if (x == 1): return False elif (x == (n - 1)): a = 0 break if a: return False return True
null
null
null
the accuracy of the test
codeqa
def is probable prime n k 7 if n < 6 return [ False False True True False True][n]if n & 1 0 return Falseelse s d 0 n - 1 while d & 1 0 s d s + 1 d >> 1 for a in random sample xrange 2 min n - 2 sys maxint min n - 4 k x pow a d n if x 1 and x + 1 n for r in xrange 1 s x pow x 2 n if x 1 return Falseelif x n - 1 a 0breakif a return Falsereturn True
null
null
null
null
Question: What do the parameter k define ? Code: def is_probable_prime(n, k=7): if (n < 6): return [False, False, True, True, False, True][n] if ((n & 1) == 0): return False else: (s, d) = (0, (n - 1)) while ((d & 1) == 0): (s, d) = ((s + 1), (d >> 1)) for a in random.sample(xrange(2, min((n - 2), sys.maxint)), min((n - 4), k)): x = pow(a, d, n) if ((x != 1) and ((x + 1) != n)): for r in xrange(1, s): x = pow(x, 2, n) if (x == 1): return False elif (x == (n - 1)): a = 0 break if a: return False return True
null
null
null
How do command execute ?
def sh(cmd): return subprocess.check_call(cmd, shell=True)
null
null
null
in a subshell
codeqa
def sh cmd return subprocess check call cmd shell True
null
null
null
null
Question: How do command execute ? Code: def sh(cmd): return subprocess.check_call(cmd, shell=True)
null
null
null
What does the code setup ?
def setup(hass, config): conf = config[DOMAIN] host = conf.get(CONF_HOST) prefix = conf.get(CONF_PREFIX) port = conf.get(CONF_PORT) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.connect((host, port)) sock.shutdown(2) _LOGGER.debug('Connection to Graphite possible') except socket.error: _LOGGER.error('Not able to connect to Graphite') return False GraphiteFeeder(hass, host, port, prefix) return True
null
null
null
the graphite feeder
codeqa
def setup hass config conf config[DOMAIN]host conf get CONF HOST prefix conf get CONF PREFIX port conf get CONF PORT sock socket socket socket AF INET socket SOCK STREAM try sock connect host port sock shutdown 2 LOGGER debug ' Connectionto Graphitepossible' except socket error LOGGER error ' Notabletoconnectto Graphite' return False Graphite Feeder hass host port prefix return True
null
null
null
null
Question: What does the code setup ? Code: def setup(hass, config): conf = config[DOMAIN] host = conf.get(CONF_HOST) prefix = conf.get(CONF_PREFIX) port = conf.get(CONF_PORT) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.connect((host, port)) sock.shutdown(2) _LOGGER.debug('Connection to Graphite possible') except socket.error: _LOGGER.error('Not able to connect to Graphite') return False GraphiteFeeder(hass, host, port, prefix) return True
null
null
null
What does the code verify ?
@task def code_verify(revision=None): if is_old_code(): fprint('installed code is in the old style (directory instead of symlink). Manual intervention required') return False rev = (revision or hg_revision()) if exists(('~/viewfinder.%s' % rev)): fprint(('Code at revision %s is installed' % rev)) return True else: fprint(('Code at revision %s is not installed' % rev)) return False
null
null
null
the code for a given revision
codeqa
@taskdef code verify revision None if is old code fprint 'installedcodeisintheoldstyle directoryinsteadofsymlink Manualinterventionrequired' return Falserev revision or hg revision if exists '~/viewfinder %s' % rev fprint ' Codeatrevision%sisinstalled' % rev return Trueelse fprint ' Codeatrevision%sisnotinstalled' % rev return False
null
null
null
null
Question: What does the code verify ? Code: @task def code_verify(revision=None): if is_old_code(): fprint('installed code is in the old style (directory instead of symlink). Manual intervention required') return False rev = (revision or hg_revision()) if exists(('~/viewfinder.%s' % rev)): fprint(('Code at revision %s is installed' % rev)) return True else: fprint(('Code at revision %s is not installed' % rev)) return False
null
null
null
What does the code remove ?
def removeZip(): zipName = 'reprap_python_beanshell' zipNameExtension = (zipName + '.zip') if (zipNameExtension in os.listdir(os.getcwd())): os.remove(zipNameExtension) shellCommand = ('zip -r %s * -x \\*.pyc \\*~' % zipName) commandResult = os.system(shellCommand) if (commandResult != 0): print 'Failed to execute the following command in removeZip in prepare.' print shellCommand
null
null
null
the zip file
codeqa
def remove Zip zip Name 'reprap python beanshell'zip Name Extension zip Name + ' zip' if zip Name Extension in os listdir os getcwd os remove zip Name Extension shell Command 'zip-r%s*-x\\* pyc\\*~' % zip Name command Result os system shell Command if command Result 0 print ' Failedtoexecutethefollowingcommandinremove Zipinprepare 'print shell Command
null
null
null
null
Question: What does the code remove ? Code: def removeZip(): zipName = 'reprap_python_beanshell' zipNameExtension = (zipName + '.zip') if (zipNameExtension in os.listdir(os.getcwd())): os.remove(zipNameExtension) shellCommand = ('zip -r %s * -x \\*.pyc \\*~' % zipName) commandResult = os.system(shellCommand) if (commandResult != 0): print 'Failed to execute the following command in removeZip in prepare.' print shellCommand
null
null
null
What does the code add ?
def add_alias(alias, canonical): ALIASES[alias] = canonical
null
null
null
a character set alias
codeqa
def add alias alias canonical ALIASES[alias] canonical
null
null
null
null
Question: What does the code add ? Code: def add_alias(alias, canonical): ALIASES[alias] = canonical
null
null
null
What does the code find ?
def find_data_files(): manpagebase = pjoin('share', 'man', 'man1') manpages = [f for f in glob(pjoin('docs', 'man', '*.1.gz')) if isfile(f)] if (not manpages): manpages = [f for f in glob(pjoin('docs', 'man', '*.1')) if isfile(f)] data_files = [(manpagebase, manpages)] return data_files
null
null
null
ipythons data_files
codeqa
def find data files manpagebase pjoin 'share' 'man' 'man 1 ' manpages [f for f in glob pjoin 'docs' 'man' '* 1 gz' if isfile f ]if not manpages manpages [f for f in glob pjoin 'docs' 'man' '* 1' if isfile f ]data files [ manpagebase manpages ]return data files
null
null
null
null
Question: What does the code find ? Code: def find_data_files(): manpagebase = pjoin('share', 'man', 'man1') manpages = [f for f in glob(pjoin('docs', 'man', '*.1.gz')) if isfile(f)] if (not manpages): manpages = [f for f in glob(pjoin('docs', 'man', '*.1')) if isfile(f)] data_files = [(manpagebase, manpages)] return data_files
null
null
null
What do we have ?
@verbose def _ensure_src(src, kind=None, verbose=None): if isinstance(src, string_types): if (not op.isfile(src)): raise IOError(('Source space file "%s" not found' % src)) logger.info(('Reading %s...' % src)) src = read_source_spaces(src, verbose=False) if (not isinstance(src, SourceSpaces)): raise ValueError('src must be a string or instance of SourceSpaces') if (kind is not None): if (kind == 'surf'): surf = [s for s in src if (s['type'] == 'surf')] if ((len(surf) != 2) or (len(src) != 2)): raise ValueError('Source space must contain exactly two surfaces.') src = surf return src
null
null
null
a source space
codeqa
@verbosedef ensure src src kind None verbose None if isinstance src string types if not op isfile src raise IO Error ' Sourcespacefile"%s"notfound' % src logger info ' Reading%s ' % src src read source spaces src verbose False if not isinstance src Source Spaces raise Value Error 'srcmustbeastringorinstanceof Source Spaces' if kind is not None if kind 'surf' surf [s for s in src if s['type'] 'surf' ]if len surf 2 or len src 2 raise Value Error ' Sourcespacemustcontainexactlytwosurfaces ' src surfreturn src
null
null
null
null
Question: What do we have ? Code: @verbose def _ensure_src(src, kind=None, verbose=None): if isinstance(src, string_types): if (not op.isfile(src)): raise IOError(('Source space file "%s" not found' % src)) logger.info(('Reading %s...' % src)) src = read_source_spaces(src, verbose=False) if (not isinstance(src, SourceSpaces)): raise ValueError('src must be a string or instance of SourceSpaces') if (kind is not None): if (kind == 'surf'): surf = [s for s in src if (s['type'] == 'surf')] if ((len(surf) != 2) or (len(src) != 2)): raise ValueError('Source space must contain exactly two surfaces.') src = surf return src
null
null
null
What contains exactly one command and check attributes ?
def lint_command(tool_xml, lint_ctx): root = tool_xml.getroot() commands = root.findall('command') if (len(commands) > 1): lint_ctx.error('More than one command tag found, behavior undefined.') return if (len(commands) == 0): lint_ctx.error('No command tag found, must specify a command template to execute.') return command = get_command(tool_xml) if ('TODO' in command): lint_ctx.warn('Command template contains TODO text.') command_attrib = command.attrib interpreter_type = None for (key, value) in command_attrib.items(): if (key == 'interpreter'): interpreter_type = value elif (key == 'detect_errors'): detect_errors = value if (detect_errors not in ['default', 'exit_code', 'aggressive']): lint_ctx.warn(('Unknown detect_errors attribute [%s]' % detect_errors)) else: lint_ctx.warn(('Unknown attribute [%s] encountered on command tag.' % key)) interpreter_info = '' if interpreter_type: interpreter_info = (' with interpreter of type [%s]' % interpreter_type) if interpreter_type: lint_ctx.info("Command uses deprecated 'interpreter' attribute.") lint_ctx.info(('Tool contains a command%s.' % interpreter_info))
null
null
null
the code ensure tool
codeqa
def lint command tool xml lint ctx root tool xml getroot commands root findall 'command' if len commands > 1 lint ctx error ' Morethanonecommandtagfound behaviorundefined ' returnif len commands 0 lint ctx error ' Nocommandtagfound mustspecifyacommandtemplatetoexecute ' returncommand get command tool xml if 'TODO' in command lint ctx warn ' Commandtemplatecontains TOD Otext ' command attrib command attribinterpreter type Nonefor key value in command attrib items if key 'interpreter' interpreter type valueelif key 'detect errors' detect errors valueif detect errors not in ['default' 'exit code' 'aggressive'] lint ctx warn ' Unknowndetect errorsattribute[%s]' % detect errors else lint ctx warn ' Unknownattribute[%s]encounteredoncommandtag ' % key interpreter info ''if interpreter type interpreter info 'withinterpreteroftype[%s]' % interpreter type if interpreter type lint ctx info " Commandusesdeprecated'interpreter'attribute " lint ctx info ' Toolcontainsacommand%s ' % interpreter info
null
null
null
null
Question: What contains exactly one command and check attributes ? Code: def lint_command(tool_xml, lint_ctx): root = tool_xml.getroot() commands = root.findall('command') if (len(commands) > 1): lint_ctx.error('More than one command tag found, behavior undefined.') return if (len(commands) == 0): lint_ctx.error('No command tag found, must specify a command template to execute.') return command = get_command(tool_xml) if ('TODO' in command): lint_ctx.warn('Command template contains TODO text.') command_attrib = command.attrib interpreter_type = None for (key, value) in command_attrib.items(): if (key == 'interpreter'): interpreter_type = value elif (key == 'detect_errors'): detect_errors = value if (detect_errors not in ['default', 'exit_code', 'aggressive']): lint_ctx.warn(('Unknown detect_errors attribute [%s]' % detect_errors)) else: lint_ctx.warn(('Unknown attribute [%s] encountered on command tag.' % key)) interpreter_info = '' if interpreter_type: interpreter_info = (' with interpreter of type [%s]' % interpreter_type) if interpreter_type: lint_ctx.info("Command uses deprecated 'interpreter' attribute.") lint_ctx.info(('Tool contains a command%s.' % interpreter_info))
null
null
null
What does the code ensure tool contain ?
def lint_command(tool_xml, lint_ctx): root = tool_xml.getroot() commands = root.findall('command') if (len(commands) > 1): lint_ctx.error('More than one command tag found, behavior undefined.') return if (len(commands) == 0): lint_ctx.error('No command tag found, must specify a command template to execute.') return command = get_command(tool_xml) if ('TODO' in command): lint_ctx.warn('Command template contains TODO text.') command_attrib = command.attrib interpreter_type = None for (key, value) in command_attrib.items(): if (key == 'interpreter'): interpreter_type = value elif (key == 'detect_errors'): detect_errors = value if (detect_errors not in ['default', 'exit_code', 'aggressive']): lint_ctx.warn(('Unknown detect_errors attribute [%s]' % detect_errors)) else: lint_ctx.warn(('Unknown attribute [%s] encountered on command tag.' % key)) interpreter_info = '' if interpreter_type: interpreter_info = (' with interpreter of type [%s]' % interpreter_type) if interpreter_type: lint_ctx.info("Command uses deprecated 'interpreter' attribute.") lint_ctx.info(('Tool contains a command%s.' % interpreter_info))
null
null
null
exactly one command and check attributes
codeqa
def lint command tool xml lint ctx root tool xml getroot commands root findall 'command' if len commands > 1 lint ctx error ' Morethanonecommandtagfound behaviorundefined ' returnif len commands 0 lint ctx error ' Nocommandtagfound mustspecifyacommandtemplatetoexecute ' returncommand get command tool xml if 'TODO' in command lint ctx warn ' Commandtemplatecontains TOD Otext ' command attrib command attribinterpreter type Nonefor key value in command attrib items if key 'interpreter' interpreter type valueelif key 'detect errors' detect errors valueif detect errors not in ['default' 'exit code' 'aggressive'] lint ctx warn ' Unknowndetect errorsattribute[%s]' % detect errors else lint ctx warn ' Unknownattribute[%s]encounteredoncommandtag ' % key interpreter info ''if interpreter type interpreter info 'withinterpreteroftype[%s]' % interpreter type if interpreter type lint ctx info " Commandusesdeprecated'interpreter'attribute " lint ctx info ' Toolcontainsacommand%s ' % interpreter info
null
null
null
null
Question: What does the code ensure tool contain ? Code: def lint_command(tool_xml, lint_ctx): root = tool_xml.getroot() commands = root.findall('command') if (len(commands) > 1): lint_ctx.error('More than one command tag found, behavior undefined.') return if (len(commands) == 0): lint_ctx.error('No command tag found, must specify a command template to execute.') return command = get_command(tool_xml) if ('TODO' in command): lint_ctx.warn('Command template contains TODO text.') command_attrib = command.attrib interpreter_type = None for (key, value) in command_attrib.items(): if (key == 'interpreter'): interpreter_type = value elif (key == 'detect_errors'): detect_errors = value if (detect_errors not in ['default', 'exit_code', 'aggressive']): lint_ctx.warn(('Unknown detect_errors attribute [%s]' % detect_errors)) else: lint_ctx.warn(('Unknown attribute [%s] encountered on command tag.' % key)) interpreter_info = '' if interpreter_type: interpreter_info = (' with interpreter of type [%s]' % interpreter_type) if interpreter_type: lint_ctx.info("Command uses deprecated 'interpreter' attribute.") lint_ctx.info(('Tool contains a command%s.' % interpreter_info))
null
null
null
What indicate columns alignment ?
def _pipe_segment_with_colons(align, colwidth): w = colwidth if (align in [u'right', u'decimal']): return ((u'-' * (w - 1)) + u':') elif (align == u'center'): return ((u':' + (u'-' * (w - 2))) + u':') elif (align == u'left'): return (u':' + (u'-' * (w - 1))) else: return (u'-' * w)
null
null
null
optional colons
codeqa
def pipe segment with colons align colwidth w colwidthif align in [u'right' u'decimal'] return u'-' * w - 1 + u' ' elif align u'center' return u' ' + u'-' * w - 2 + u' ' elif align u'left' return u' ' + u'-' * w - 1 else return u'-' * w
null
null
null
null
Question: What indicate columns alignment ? Code: def _pipe_segment_with_colons(align, colwidth): w = colwidth if (align in [u'right', u'decimal']): return ((u'-' * (w - 1)) + u':') elif (align == u'center'): return ((u':' + (u'-' * (w - 2))) + u':') elif (align == u'left'): return (u':' + (u'-' * (w - 1))) else: return (u'-' * w)
null
null
null
What do optional colons indicate ?
def _pipe_segment_with_colons(align, colwidth): w = colwidth if (align in [u'right', u'decimal']): return ((u'-' * (w - 1)) + u':') elif (align == u'center'): return ((u':' + (u'-' * (w - 2))) + u':') elif (align == u'left'): return (u':' + (u'-' * (w - 1))) else: return (u'-' * w)
null
null
null
columns alignment
codeqa
def pipe segment with colons align colwidth w colwidthif align in [u'right' u'decimal'] return u'-' * w - 1 + u' ' elif align u'center' return u' ' + u'-' * w - 2 + u' ' elif align u'left' return u' ' + u'-' * w - 1 else return u'-' * w
null
null
null
null
Question: What do optional colons indicate ? Code: def _pipe_segment_with_colons(align, colwidth): w = colwidth if (align in [u'right', u'decimal']): return ((u'-' * (w - 1)) + u':') elif (align == u'center'): return ((u':' + (u'-' * (w - 2))) + u':') elif (align == u'left'): return (u':' + (u'-' * (w - 1))) else: return (u'-' * w)
null
null
null
Where do only the edges exist ?
def intersection_all(graphs): graphs = iter(graphs) R = next(graphs) for H in graphs: R = nx.intersection(R, H) return R
null
null
null
in all graphs
codeqa
def intersection all graphs graphs iter graphs R next graphs for H in graphs R nx intersection R H return R
null
null
null
null
Question: Where do only the edges exist ? Code: def intersection_all(graphs): graphs = iter(graphs) R = next(graphs) for H in graphs: R = nx.intersection(R, H) return R
null
null
null
When do plain directory exist ?
def bzr_wc_target_exists_plain_no_force(): test = 'bzr_wc_target_exists_plain_no_force' wt = ('%s-test-%s' % (DIR, test)) puts(magenta(('Executing test: %s' % test))) from fabric.api import run from fabtools.files import is_dir from fabtools import require run(('mkdir %s' % wt)) assert (not is_dir(path.join(wt, '.bzr'))) try: require.bazaar.working_copy(REMOTE_URL, wt) except SystemExit: pass else: assert False, "working_copy didn't raise exception" assert (not is_dir(path.join(wt, '.bzr')))
null
null
null
already
codeqa
def bzr wc target exists plain no force test 'bzr wc target exists plain no force'wt '%s-test-%s' % DIR test puts magenta ' Executingtest %s' % test from fabric api import runfrom fabtools files import is dirfrom fabtools import requirerun 'mkdir%s' % wt assert not is dir path join wt ' bzr' try require bazaar working copy REMOTE URL wt except System Exit passelse assert False "working copydidn'traiseexception"assert not is dir path join wt ' bzr'
null
null
null
null
Question: When do plain directory exist ? Code: def bzr_wc_target_exists_plain_no_force(): test = 'bzr_wc_target_exists_plain_no_force' wt = ('%s-test-%s' % (DIR, test)) puts(magenta(('Executing test: %s' % test))) from fabric.api import run from fabtools.files import is_dir from fabtools import require run(('mkdir %s' % wt)) assert (not is_dir(path.join(wt, '.bzr'))) try: require.bazaar.working_copy(REMOTE_URL, wt) except SystemExit: pass else: assert False, "working_copy didn't raise exception" assert (not is_dir(path.join(wt, '.bzr')))
null
null
null
What does the code create ?
def _checkbox(cls, text, tooltip, checked): widget = cls() if text: widget.setText(text) if tooltip: widget.setToolTip(tooltip) if (checked is not None): widget.setChecked(checked) return widget
null
null
null
a widget
codeqa
def checkbox cls text tooltip checked widget cls if text widget set Text text if tooltip widget set Tool Tip tooltip if checked is not None widget set Checked checked return widget
null
null
null
null
Question: What does the code create ? Code: def _checkbox(cls, text, tooltip, checked): widget = cls() if text: widget.setText(text) if tooltip: widget.setToolTip(tooltip) if (checked is not None): widget.setChecked(checked) return widget
null
null
null
What does the code apply ?
def _checkbox(cls, text, tooltip, checked): widget = cls() if text: widget.setText(text) if tooltip: widget.setToolTip(tooltip) if (checked is not None): widget.setChecked(checked) return widget
null
null
null
properties
codeqa
def checkbox cls text tooltip checked widget cls if text widget set Text text if tooltip widget set Tool Tip tooltip if checked is not None widget set Checked checked return widget
null
null
null
null
Question: What does the code apply ? Code: def _checkbox(cls, text, tooltip, checked): widget = cls() if text: widget.setText(text) if tooltip: widget.setToolTip(tooltip) if (checked is not None): widget.setChecked(checked) return widget
null
null
null
When does the code move a file ?
def mv_file_s3(s3_connection, src_path, dst_path): (src_bucket_name, src_key_name) = _from_path(src_path) (dst_bucket_name, dst_key_name) = _from_path(dst_path) src_bucket = s3_connection.get_bucket(src_bucket_name) k = boto.s3.Key(src_bucket) k.key = src_key_name k.copy(dst_bucket_name, dst_key_name) k.delete()
null
null
null
within s3
codeqa
def mv file s3 s3 connection src path dst path src bucket name src key name from path src path dst bucket name dst key name from path dst path src bucket s3 connection get bucket src bucket name k boto s3 Key src bucket k key src key namek copy dst bucket name dst key name k delete
null
null
null
null
Question: When does the code move a file ? Code: def mv_file_s3(s3_connection, src_path, dst_path): (src_bucket_name, src_key_name) = _from_path(src_path) (dst_bucket_name, dst_key_name) = _from_path(dst_path) src_bucket = s3_connection.get_bucket(src_bucket_name) k = boto.s3.Key(src_bucket) k.key = src_key_name k.copy(dst_bucket_name, dst_key_name) k.delete()
null
null
null
What does the code move within s3 ?
def mv_file_s3(s3_connection, src_path, dst_path): (src_bucket_name, src_key_name) = _from_path(src_path) (dst_bucket_name, dst_key_name) = _from_path(dst_path) src_bucket = s3_connection.get_bucket(src_bucket_name) k = boto.s3.Key(src_bucket) k.key = src_key_name k.copy(dst_bucket_name, dst_key_name) k.delete()
null
null
null
a file
codeqa
def mv file s3 s3 connection src path dst path src bucket name src key name from path src path dst bucket name dst key name from path dst path src bucket s3 connection get bucket src bucket name k boto s3 Key src bucket k key src key namek copy dst bucket name dst key name k delete
null
null
null
null
Question: What does the code move within s3 ? Code: def mv_file_s3(s3_connection, src_path, dst_path): (src_bucket_name, src_key_name) = _from_path(src_path) (dst_bucket_name, dst_key_name) = _from_path(dst_path) src_bucket = s3_connection.get_bucket(src_bucket_name) k = boto.s3.Key(src_bucket) k.key = src_key_name k.copy(dst_bucket_name, dst_key_name) k.delete()
null
null
null
What does the code handle ?
def _pairwise_callable(X, Y, metric, **kwds): (X, Y) = check_pairwise_arrays(X, Y) if (X is Y): out = np.zeros((X.shape[0], Y.shape[0]), dtype='float') iterator = itertools.combinations(range(X.shape[0]), 2) for (i, j) in iterator: out[(i, j)] = metric(X[i], Y[j], **kwds) out = (out + out.T) for i in range(X.shape[0]): x = X[i] out[(i, i)] = metric(x, x, **kwds) else: out = np.empty((X.shape[0], Y.shape[0]), dtype='float') iterator = itertools.product(range(X.shape[0]), range(Y.shape[0])) for (i, j) in iterator: out[(i, j)] = metric(X[i], Y[j], **kwds) return out
null
null
null
the callable case for pairwise_{distances
codeqa
def pairwise callable X Y metric **kwds X Y check pairwise arrays X Y if X is Y out np zeros X shape[ 0 ] Y shape[ 0 ] dtype 'float' iterator itertools combinations range X shape[ 0 ] 2 for i j in iterator out[ i j ] metric X[i] Y[j] **kwds out out + out T for i in range X shape[ 0 ] x X[i]out[ i i ] metric x x **kwds else out np empty X shape[ 0 ] Y shape[ 0 ] dtype 'float' iterator itertools product range X shape[ 0 ] range Y shape[ 0 ] for i j in iterator out[ i j ] metric X[i] Y[j] **kwds return out
null
null
null
null
Question: What does the code handle ? Code: def _pairwise_callable(X, Y, metric, **kwds): (X, Y) = check_pairwise_arrays(X, Y) if (X is Y): out = np.zeros((X.shape[0], Y.shape[0]), dtype='float') iterator = itertools.combinations(range(X.shape[0]), 2) for (i, j) in iterator: out[(i, j)] = metric(X[i], Y[j], **kwds) out = (out + out.T) for i in range(X.shape[0]): x = X[i] out[(i, i)] = metric(x, x, **kwds) else: out = np.empty((X.shape[0], Y.shape[0]), dtype='float') iterator = itertools.product(range(X.shape[0]), range(Y.shape[0])) for (i, j) in iterator: out[(i, j)] = metric(X[i], Y[j], **kwds) return out
null
null
null
What does this return ?
def grading_context(course_structure): all_graded_blocks = [] all_graded_subsections_by_type = OrderedDict() for chapter_key in course_structure.get_children(course_structure.root_block_usage_key): for subsection_key in course_structure.get_children(chapter_key): subsection = course_structure[subsection_key] scored_descendants_of_subsection = [] if subsection.graded: for descendant_key in course_structure.post_order_traversal(filter_func=possibly_scored, start_node=subsection_key): scored_descendants_of_subsection.append(course_structure[descendant_key]) subsection_info = {'subsection_block': subsection, 'scored_descendants': [child for child in scored_descendants_of_subsection if getattr(child, 'has_score', None)]} subsection_format = getattr(subsection, 'format', '') if (subsection_format not in all_graded_subsections_by_type): all_graded_subsections_by_type[subsection_format] = [] all_graded_subsections_by_type[subsection_format].append(subsection_info) all_graded_blocks.extend(scored_descendants_of_subsection) return {'all_graded_subsections_by_type': all_graded_subsections_by_type, 'all_graded_blocks': all_graded_blocks}
null
null
null
a dictionary with keys necessary for quickly grading a student
codeqa
def grading context course structure all graded blocks []all graded subsections by type Ordered Dict for chapter key in course structure get children course structure root block usage key for subsection key in course structure get children chapter key subsection course structure[subsection key]scored descendants of subsection []if subsection graded for descendant key in course structure post order traversal filter func possibly scored start node subsection key scored descendants of subsection append course structure[descendant key] subsection info {'subsection block' subsection 'scored descendants' [child for child in scored descendants of subsection if getattr child 'has score' None ]}subsection format getattr subsection 'format' '' if subsection format not in all graded subsections by type all graded subsections by type[subsection format] []all graded subsections by type[subsection format] append subsection info all graded blocks extend scored descendants of subsection return {'all graded subsections by type' all graded subsections by type 'all graded blocks' all graded blocks}
null
null
null
null
Question: What does this return ? Code: def grading_context(course_structure): all_graded_blocks = [] all_graded_subsections_by_type = OrderedDict() for chapter_key in course_structure.get_children(course_structure.root_block_usage_key): for subsection_key in course_structure.get_children(chapter_key): subsection = course_structure[subsection_key] scored_descendants_of_subsection = [] if subsection.graded: for descendant_key in course_structure.post_order_traversal(filter_func=possibly_scored, start_node=subsection_key): scored_descendants_of_subsection.append(course_structure[descendant_key]) subsection_info = {'subsection_block': subsection, 'scored_descendants': [child for child in scored_descendants_of_subsection if getattr(child, 'has_score', None)]} subsection_format = getattr(subsection, 'format', '') if (subsection_format not in all_graded_subsections_by_type): all_graded_subsections_by_type[subsection_format] = [] all_graded_subsections_by_type[subsection_format].append(subsection_info) all_graded_blocks.extend(scored_descendants_of_subsection) return {'all_graded_subsections_by_type': all_graded_subsections_by_type, 'all_graded_blocks': all_graded_blocks}
null
null
null
How do a student grade ?
def grading_context(course_structure): all_graded_blocks = [] all_graded_subsections_by_type = OrderedDict() for chapter_key in course_structure.get_children(course_structure.root_block_usage_key): for subsection_key in course_structure.get_children(chapter_key): subsection = course_structure[subsection_key] scored_descendants_of_subsection = [] if subsection.graded: for descendant_key in course_structure.post_order_traversal(filter_func=possibly_scored, start_node=subsection_key): scored_descendants_of_subsection.append(course_structure[descendant_key]) subsection_info = {'subsection_block': subsection, 'scored_descendants': [child for child in scored_descendants_of_subsection if getattr(child, 'has_score', None)]} subsection_format = getattr(subsection, 'format', '') if (subsection_format not in all_graded_subsections_by_type): all_graded_subsections_by_type[subsection_format] = [] all_graded_subsections_by_type[subsection_format].append(subsection_info) all_graded_blocks.extend(scored_descendants_of_subsection) return {'all_graded_subsections_by_type': all_graded_subsections_by_type, 'all_graded_blocks': all_graded_blocks}
null
null
null
quickly
codeqa
def grading context course structure all graded blocks []all graded subsections by type Ordered Dict for chapter key in course structure get children course structure root block usage key for subsection key in course structure get children chapter key subsection course structure[subsection key]scored descendants of subsection []if subsection graded for descendant key in course structure post order traversal filter func possibly scored start node subsection key scored descendants of subsection append course structure[descendant key] subsection info {'subsection block' subsection 'scored descendants' [child for child in scored descendants of subsection if getattr child 'has score' None ]}subsection format getattr subsection 'format' '' if subsection format not in all graded subsections by type all graded subsections by type[subsection format] []all graded subsections by type[subsection format] append subsection info all graded blocks extend scored descendants of subsection return {'all graded subsections by type' all graded subsections by type 'all graded blocks' all graded blocks}
null
null
null
null
Question: How do a student grade ? Code: def grading_context(course_structure): all_graded_blocks = [] all_graded_subsections_by_type = OrderedDict() for chapter_key in course_structure.get_children(course_structure.root_block_usage_key): for subsection_key in course_structure.get_children(chapter_key): subsection = course_structure[subsection_key] scored_descendants_of_subsection = [] if subsection.graded: for descendant_key in course_structure.post_order_traversal(filter_func=possibly_scored, start_node=subsection_key): scored_descendants_of_subsection.append(course_structure[descendant_key]) subsection_info = {'subsection_block': subsection, 'scored_descendants': [child for child in scored_descendants_of_subsection if getattr(child, 'has_score', None)]} subsection_format = getattr(subsection, 'format', '') if (subsection_format not in all_graded_subsections_by_type): all_graded_subsections_by_type[subsection_format] = [] all_graded_subsections_by_type[subsection_format].append(subsection_info) all_graded_blocks.extend(scored_descendants_of_subsection) return {'all_graded_subsections_by_type': all_graded_subsections_by_type, 'all_graded_blocks': all_graded_blocks}
null
null
null
What returns a dictionary with keys necessary for quickly grading a student ?
def grading_context(course_structure): all_graded_blocks = [] all_graded_subsections_by_type = OrderedDict() for chapter_key in course_structure.get_children(course_structure.root_block_usage_key): for subsection_key in course_structure.get_children(chapter_key): subsection = course_structure[subsection_key] scored_descendants_of_subsection = [] if subsection.graded: for descendant_key in course_structure.post_order_traversal(filter_func=possibly_scored, start_node=subsection_key): scored_descendants_of_subsection.append(course_structure[descendant_key]) subsection_info = {'subsection_block': subsection, 'scored_descendants': [child for child in scored_descendants_of_subsection if getattr(child, 'has_score', None)]} subsection_format = getattr(subsection, 'format', '') if (subsection_format not in all_graded_subsections_by_type): all_graded_subsections_by_type[subsection_format] = [] all_graded_subsections_by_type[subsection_format].append(subsection_info) all_graded_blocks.extend(scored_descendants_of_subsection) return {'all_graded_subsections_by_type': all_graded_subsections_by_type, 'all_graded_blocks': all_graded_blocks}
null
null
null
this
codeqa
def grading context course structure all graded blocks []all graded subsections by type Ordered Dict for chapter key in course structure get children course structure root block usage key for subsection key in course structure get children chapter key subsection course structure[subsection key]scored descendants of subsection []if subsection graded for descendant key in course structure post order traversal filter func possibly scored start node subsection key scored descendants of subsection append course structure[descendant key] subsection info {'subsection block' subsection 'scored descendants' [child for child in scored descendants of subsection if getattr child 'has score' None ]}subsection format getattr subsection 'format' '' if subsection format not in all graded subsections by type all graded subsections by type[subsection format] []all graded subsections by type[subsection format] append subsection info all graded blocks extend scored descendants of subsection return {'all graded subsections by type' all graded subsections by type 'all graded blocks' all graded blocks}
null
null
null
null
Question: What returns a dictionary with keys necessary for quickly grading a student ? Code: def grading_context(course_structure): all_graded_blocks = [] all_graded_subsections_by_type = OrderedDict() for chapter_key in course_structure.get_children(course_structure.root_block_usage_key): for subsection_key in course_structure.get_children(chapter_key): subsection = course_structure[subsection_key] scored_descendants_of_subsection = [] if subsection.graded: for descendant_key in course_structure.post_order_traversal(filter_func=possibly_scored, start_node=subsection_key): scored_descendants_of_subsection.append(course_structure[descendant_key]) subsection_info = {'subsection_block': subsection, 'scored_descendants': [child for child in scored_descendants_of_subsection if getattr(child, 'has_score', None)]} subsection_format = getattr(subsection, 'format', '') if (subsection_format not in all_graded_subsections_by_type): all_graded_subsections_by_type[subsection_format] = [] all_graded_subsections_by_type[subsection_format].append(subsection_info) all_graded_blocks.extend(scored_descendants_of_subsection) return {'all_graded_subsections_by_type': all_graded_subsections_by_type, 'all_graded_blocks': all_graded_blocks}
null
null
null
What does the code give ?
def GetEnabledInterfaces(): interfaces = [] show_args = ['/c', 'netsh', 'show', 'interface'] res = client_utils_common.Execute('cmd', show_args, time_limit=(-1), bypass_whitelist=True) pattern = re.compile('\\s*') for line in res[0].split('\r\n'): interface_info = pattern.split(line) if ('Enabled' in interface_info): interfaces.extend(interface_info[(-1):]) return interfaces
null
null
null
a list of enabled interfaces
codeqa
def Get Enabled Interfaces interfaces []show args ['/c' 'netsh' 'show' 'interface']res client utils common Execute 'cmd' show args time limit -1 bypass whitelist True pattern re compile '\\s*' for line in res[ 0 ] split '\r\n' interface info pattern split line if ' Enabled' in interface info interfaces extend interface info[ -1 ] return interfaces
null
null
null
null
Question: What does the code give ? Code: def GetEnabledInterfaces(): interfaces = [] show_args = ['/c', 'netsh', 'show', 'interface'] res = client_utils_common.Execute('cmd', show_args, time_limit=(-1), bypass_whitelist=True) pattern = re.compile('\\s*') for line in res[0].split('\r\n'): interface_info = pattern.split(line) if ('Enabled' in interface_info): interfaces.extend(interface_info[(-1):]) return interfaces
null
null
null
How do string return ?
def force_unicode(string): if (sys.version_info[0] == 2): if isinstance(string, unicode): return string.encode('utf-8') return string
null
null
null
as a native string
codeqa
def force unicode string if sys version info[ 0 ] 2 if isinstance string unicode return string encode 'utf- 8 ' return string
null
null
null
null
Question: How do string return ? Code: def force_unicode(string): if (sys.version_info[0] == 2): if isinstance(string, unicode): return string.encode('utf-8') return string
null
null
null
Who d compute to a specified relative precision using random matrix - vector multiplication ?
def iddp_rid(eps, m, n, matvect): proj = np.empty(((m + 1) + ((2 * n) * (min(m, n) + 1))), order='F') (k, idx, proj, ier) = _id.iddp_rid(eps, m, n, matvect, proj) if (ier != 0): raise _RETCODE_ERROR proj = proj[:(k * (n - k))].reshape((k, (n - k)), order='F') return (k, idx, proj)
null
null
null
i d of a real matrix
codeqa
def iddp rid eps m n matvect proj np empty m + 1 + 2 * n * min m n + 1 order 'F' k idx proj ier id iddp rid eps m n matvect proj if ier 0 raise RETCODE ERRO Rproj proj[ k * n - k ] reshape k n - k order 'F' return k idx proj
null
null
null
null
Question: Who d compute to a specified relative precision using random matrix - vector multiplication ? Code: def iddp_rid(eps, m, n, matvect): proj = np.empty(((m + 1) + ((2 * n) * (min(m, n) + 1))), order='F') (k, idx, proj, ier) = _id.iddp_rid(eps, m, n, matvect, proj) if (ier != 0): raise _RETCODE_ERROR proj = proj[:(k * (n - k))].reshape((k, (n - k)), order='F') return (k, idx, proj)
null
null
null
What d i d of a real matrix compute using random matrix - vector multiplication ?
def iddp_rid(eps, m, n, matvect): proj = np.empty(((m + 1) + ((2 * n) * (min(m, n) + 1))), order='F') (k, idx, proj, ier) = _id.iddp_rid(eps, m, n, matvect, proj) if (ier != 0): raise _RETCODE_ERROR proj = proj[:(k * (n - k))].reshape((k, (n - k)), order='F') return (k, idx, proj)
null
null
null
to a specified relative precision
codeqa
def iddp rid eps m n matvect proj np empty m + 1 + 2 * n * min m n + 1 order 'F' k idx proj ier id iddp rid eps m n matvect proj if ier 0 raise RETCODE ERRO Rproj proj[ k * n - k ] reshape k n - k order 'F' return k idx proj
null
null
null
null
Question: What d i d of a real matrix compute using random matrix - vector multiplication ? Code: def iddp_rid(eps, m, n, matvect): proj = np.empty(((m + 1) + ((2 * n) * (min(m, n) + 1))), order='F') (k, idx, proj, ier) = _id.iddp_rid(eps, m, n, matvect, proj) if (ier != 0): raise _RETCODE_ERROR proj = proj[:(k * (n - k))].reshape((k, (n - k)), order='F') return (k, idx, proj)
null
null
null
What returns along an axis ?
def argmax(x, axis=(-1)): if (axis < 0): axis = (axis % len(x.get_shape())) return tf.argmax(x, axis)
null
null
null
the index of the maximum value
codeqa
def argmax x axis -1 if axis < 0 axis axis % len x get shape return tf argmax x axis
null
null
null
null
Question: What returns along an axis ? Code: def argmax(x, axis=(-1)): if (axis < 0): axis = (axis % len(x.get_shape())) return tf.argmax(x, axis)
null
null
null
Where does the index of the maximum value return ?
def argmax(x, axis=(-1)): if (axis < 0): axis = (axis % len(x.get_shape())) return tf.argmax(x, axis)
null
null
null
along an axis
codeqa
def argmax x axis -1 if axis < 0 axis axis % len x get shape return tf argmax x axis
null
null
null
null
Question: Where does the index of the maximum value return ? Code: def argmax(x, axis=(-1)): if (axis < 0): axis = (axis % len(x.get_shape())) return tf.argmax(x, axis)
null
null
null
What do anonymous users access ?
def login_forbidden(view_func, template_name='login_forbidden.html', status=403): @wraps(view_func) def _checklogin(request, *args, **kwargs): if (not request.user.is_authenticated()): return view_func(request, *args, **kwargs) return render(request, template_name, status=status) return _checklogin
null
null
null
this view
codeqa
def login forbidden view func template name 'login forbidden html' status 403 @wraps view func def checklogin request *args **kwargs if not request user is authenticated return view func request *args **kwargs return render request template name status status return checklogin
null
null
null
null
Question: What do anonymous users access ? Code: def login_forbidden(view_func, template_name='login_forbidden.html', status=403): @wraps(view_func) def _checklogin(request, *args, **kwargs): if (not request.user.is_authenticated()): return view_func(request, *args, **kwargs) return render(request, template_name, status=status) return _checklogin
null
null
null
What does the code ensure ?
def validate_type(magic_kind): if (magic_kind not in magic_spec): raise ValueError(('magic_kind must be one of %s, %s given' % magic_kinds), magic_kind)
null
null
null
that the given magic_kind is valid
codeqa
def validate type magic kind if magic kind not in magic spec raise Value Error 'magic kindmustbeoneof%s %sgiven' % magic kinds magic kind
null
null
null
null
Question: What does the code ensure ? Code: def validate_type(magic_kind): if (magic_kind not in magic_spec): raise ValueError(('magic_kind must be one of %s, %s given' % magic_kinds), magic_kind)
null
null
null
How did method name ?
def deprecatedWorkerClassMethod(scope, method, compat_name=None): method_name = method.__name__ compat_name = _compat_name(method_name, compat_name=compat_name) assert (compat_name not in scope) def old_method(self, *args, **kwargs): reportDeprecatedWorkerNameUsage("'{old}' method is deprecated, use '{new}' instead.".format(new=method_name, old=compat_name)) return getattr(self, method_name)(*args, **kwargs) functools.update_wrapper(old_method, method) scope[compat_name] = old_method
null
null
null
old
codeqa
def deprecated Worker Class Method scope method compat name None method name method name compat name compat name method name compat name compat name assert compat name not in scope def old method self *args **kwargs report Deprecated Worker Name Usage "'{old}'methodisdeprecated use'{new}'instead " format new method name old compat name return getattr self method name *args **kwargs functools update wrapper old method method scope[compat name] old method
null
null
null
null
Question: How did method name ? Code: def deprecatedWorkerClassMethod(scope, method, compat_name=None): method_name = method.__name__ compat_name = _compat_name(method_name, compat_name=compat_name) assert (compat_name not in scope) def old_method(self, *args, **kwargs): reportDeprecatedWorkerNameUsage("'{old}' method is deprecated, use '{new}' instead.".format(new=method_name, old=compat_name)) return getattr(self, method_name)(*args, **kwargs) functools.update_wrapper(old_method, method) scope[compat_name] = old_method
null
null
null
What defines inside class ?
def deprecatedWorkerClassMethod(scope, method, compat_name=None): method_name = method.__name__ compat_name = _compat_name(method_name, compat_name=compat_name) assert (compat_name not in scope) def old_method(self, *args, **kwargs): reportDeprecatedWorkerNameUsage("'{old}' method is deprecated, use '{new}' instead.".format(new=method_name, old=compat_name)) return getattr(self, method_name)(*args, **kwargs) functools.update_wrapper(old_method, method) scope[compat_name] = old_method
null
null
null
old - named method
codeqa
def deprecated Worker Class Method scope method compat name None method name method name compat name compat name method name compat name compat name assert compat name not in scope def old method self *args **kwargs report Deprecated Worker Name Usage "'{old}'methodisdeprecated use'{new}'instead " format new method name old compat name return getattr self method name *args **kwargs functools update wrapper old method method scope[compat name] old method
null
null
null
null
Question: What defines inside class ? Code: def deprecatedWorkerClassMethod(scope, method, compat_name=None): method_name = method.__name__ compat_name = _compat_name(method_name, compat_name=compat_name) assert (compat_name not in scope) def old_method(self, *args, **kwargs): reportDeprecatedWorkerNameUsage("'{old}' method is deprecated, use '{new}' instead.".format(new=method_name, old=compat_name)) return getattr(self, method_name)(*args, **kwargs) functools.update_wrapper(old_method, method) scope[compat_name] = old_method
null
null
null
Where do old - named method define ?
def deprecatedWorkerClassMethod(scope, method, compat_name=None): method_name = method.__name__ compat_name = _compat_name(method_name, compat_name=compat_name) assert (compat_name not in scope) def old_method(self, *args, **kwargs): reportDeprecatedWorkerNameUsage("'{old}' method is deprecated, use '{new}' instead.".format(new=method_name, old=compat_name)) return getattr(self, method_name)(*args, **kwargs) functools.update_wrapper(old_method, method) scope[compat_name] = old_method
null
null
null
inside class
codeqa
def deprecated Worker Class Method scope method compat name None method name method name compat name compat name method name compat name compat name assert compat name not in scope def old method self *args **kwargs report Deprecated Worker Name Usage "'{old}'methodisdeprecated use'{new}'instead " format new method name old compat name return getattr self method name *args **kwargs functools update wrapper old method method scope[compat name] old method
null
null
null
null
Question: Where do old - named method define ? Code: def deprecatedWorkerClassMethod(scope, method, compat_name=None): method_name = method.__name__ compat_name = _compat_name(method_name, compat_name=compat_name) assert (compat_name not in scope) def old_method(self, *args, **kwargs): reportDeprecatedWorkerNameUsage("'{old}' method is deprecated, use '{new}' instead.".format(new=method_name, old=compat_name)) return getattr(self, method_name)(*args, **kwargs) functools.update_wrapper(old_method, method) scope[compat_name] = old_method
null
null
null
What does the code get ?
def volume_type_get_all_by_group(context, group_id): return IMPL.volume_type_get_all_by_group(context, group_id)
null
null
null
all volumes in a group
codeqa
def volume type get all by group context group id return IMPL volume type get all by group context group id
null
null
null
null
Question: What does the code get ? Code: def volume_type_get_all_by_group(context, group_id): return IMPL.volume_type_get_all_by_group(context, group_id)
null
null
null
What does the code get ?
def getCraftPreferences(pluginName): return settings.getReadRepository(getCraftModule(pluginName).getNewRepository()).preferences
null
null
null
craft preferences
codeqa
def get Craft Preferences plugin Name return settings get Read Repository get Craft Module plugin Name get New Repository preferences
null
null
null
null
Question: What does the code get ? Code: def getCraftPreferences(pluginName): return settings.getReadRepository(getCraftModule(pluginName).getNewRepository()).preferences
null
null
null
What does the code apply to vm from the cloud profile ?
def _override_size(vm_): vm_size = get_size(vm_) if ('cores' in vm_): vm_size['cores'] = vm_['cores'] if ('ram' in vm_): vm_size['ram'] = vm_['ram'] return vm_size
null
null
null
any extra component overrides
codeqa
def override size vm vm size get size vm if 'cores' in vm vm size['cores'] vm ['cores']if 'ram' in vm vm size['ram'] vm ['ram']return vm size
null
null
null
null
Question: What does the code apply to vm from the cloud profile ? Code: def _override_size(vm_): vm_size = get_size(vm_) if ('cores' in vm_): vm_size['cores'] = vm_['cores'] if ('ram' in vm_): vm_size['ram'] = vm_['ram'] return vm_size
null
null
null
What does the code make on a counter dict ?
def _reduce_dict(count_dict, partial_key): L = len(partial_key) count = sum((v for (k, v) in iteritems(count_dict) if (k[:L] == partial_key))) return count
null
null
null
partial sum
codeqa
def reduce dict count dict partial key L len partial key count sum v for k v in iteritems count dict if k[ L] partial key return count
null
null
null
null
Question: What does the code make on a counter dict ? Code: def _reduce_dict(count_dict, partial_key): L = len(partial_key) count = sum((v for (k, v) in iteritems(count_dict) if (k[:L] == partial_key))) return count
null
null
null
Where does the code make partial sum ?
def _reduce_dict(count_dict, partial_key): L = len(partial_key) count = sum((v for (k, v) in iteritems(count_dict) if (k[:L] == partial_key))) return count
null
null
null
on a counter dict
codeqa
def reduce dict count dict partial key L len partial key count sum v for k v in iteritems count dict if k[ L] partial key return count
null
null
null
null
Question: Where does the code make partial sum ? Code: def _reduce_dict(count_dict, partial_key): L = len(partial_key) count = sum((v for (k, v) in iteritems(count_dict) if (k[:L] == partial_key))) return count
null
null
null
What do several none contain ?
def test_no_data_with_lists_of_nones(Chart): chart = Chart() chart.add('Serie1', [None, None, None, None]) chart.add('Serie2', [None, None, None]) q = chart.render_pyquery() assert (q('.text-overlay text').text() == 'No data')
null
null
null
series
codeqa
def test no data with lists of nones Chart chart Chart chart add ' Serie 1 ' [ None None None None] chart add ' Serie 2 ' [ None None None] q chart render pyquery assert q ' text-overlaytext' text ' Nodata'
null
null
null
null
Question: What do several none contain ? Code: def test_no_data_with_lists_of_nones(Chart): chart = Chart() chart.add('Serie1', [None, None, None, None]) chart.add('Serie2', [None, None, None]) q = chart.render_pyquery() assert (q('.text-overlay text').text() == 'No data')
null
null
null
What is containing series ?
def test_no_data_with_lists_of_nones(Chart): chart = Chart() chart.add('Serie1', [None, None, None, None]) chart.add('Serie2', [None, None, None]) q = chart.render_pyquery() assert (q('.text-overlay text').text() == 'No data')
null
null
null
several none
codeqa
def test no data with lists of nones Chart chart Chart chart add ' Serie 1 ' [ None None None None] chart add ' Serie 2 ' [ None None None] q chart render pyquery assert q ' text-overlaytext' text ' Nodata'
null
null
null
null
Question: What is containing series ? Code: def test_no_data_with_lists_of_nones(Chart): chart = Chart() chart.add('Serie1', [None, None, None, None]) chart.add('Serie2', [None, None, None]) q = chart.render_pyquery() assert (q('.text-overlay text').text() == 'No data')
null
null
null
What does the code copy from host to device optionally ?
def auto_device(obj, stream=0, copy=True): if _driver.is_device_memory(obj): return (obj, False) else: sentry_contiguous(obj) if isinstance(obj, np.void): devobj = from_record_like(obj, stream=stream) else: devobj = from_array_like(obj, stream=stream) if copy: devobj.copy_to_device(obj, stream=stream) return (devobj, True)
null
null
null
data
codeqa
def auto device obj stream 0 copy True if driver is device memory obj return obj False else sentry contiguous obj if isinstance obj np void devobj from record like obj stream stream else devobj from array like obj stream stream if copy devobj copy to device obj stream stream return devobj True
null
null
null
null
Question: What does the code copy from host to device optionally ? Code: def auto_device(obj, stream=0, copy=True): if _driver.is_device_memory(obj): return (obj, False) else: sentry_contiguous(obj) if isinstance(obj, np.void): devobj = from_record_like(obj, stream=stream) else: devobj = from_array_like(obj, stream=stream) if copy: devobj.copy_to_device(obj, stream=stream) return (devobj, True)
null
null
null
What does different condition types convert ?
def condition2checker(condition): if (type(condition) in [str, unicode]): def smatcher(info): return fnmatch.fnmatch(info.filename, condition) return smatcher elif ((type(condition) in [list, tuple]) and (type(condition[0]) in [int, long])): def imatcher(info): return (info.index in condition) return imatcher elif callable(condition): return condition else: raise TypeError
null
null
null
to callback
codeqa
def condition 2 checker condition if type condition in [str unicode] def smatcher info return fnmatch fnmatch info filename condition return smatcherelif type condition in [list tuple] and type condition[ 0 ] in [int long] def imatcher info return info index in condition return imatcherelif callable condition return conditionelse raise Type Error
null
null
null
null
Question: What does different condition types convert ? Code: def condition2checker(condition): if (type(condition) in [str, unicode]): def smatcher(info): return fnmatch.fnmatch(info.filename, condition) return smatcher elif ((type(condition) in [list, tuple]) and (type(condition[0]) in [int, long])): def imatcher(info): return (info.index in condition) return imatcher elif callable(condition): return condition else: raise TypeError
null
null
null
What converts to callback ?
def condition2checker(condition): if (type(condition) in [str, unicode]): def smatcher(info): return fnmatch.fnmatch(info.filename, condition) return smatcher elif ((type(condition) in [list, tuple]) and (type(condition[0]) in [int, long])): def imatcher(info): return (info.index in condition) return imatcher elif callable(condition): return condition else: raise TypeError
null
null
null
different condition types
codeqa
def condition 2 checker condition if type condition in [str unicode] def smatcher info return fnmatch fnmatch info filename condition return smatcherelif type condition in [list tuple] and type condition[ 0 ] in [int long] def imatcher info return info index in condition return imatcherelif callable condition return conditionelse raise Type Error
null
null
null
null
Question: What converts to callback ? Code: def condition2checker(condition): if (type(condition) in [str, unicode]): def smatcher(info): return fnmatch.fnmatch(info.filename, condition) return smatcher elif ((type(condition) in [list, tuple]) and (type(condition[0]) in [int, long])): def imatcher(info): return (info.index in condition) return imatcher elif callable(condition): return condition else: raise TypeError
null
null
null
By how much does the code activate a theme ?
def set_current_theme(identifier): cache.bump_version(THEME_CACHE_KEY) theme = get_theme_by_identifier(identifier) if (not theme): raise ValueError('Invalid theme identifier') theme.set_current() cache.set(THEME_CACHE_KEY, theme) return theme
null
null
null
based on identifier
codeqa
def set current theme identifier cache bump version THEME CACHE KEY theme get theme by identifier identifier if not theme raise Value Error ' Invalidthemeidentifier' theme set current cache set THEME CACHE KEY theme return theme
null
null
null
null
Question: By how much does the code activate a theme ? Code: def set_current_theme(identifier): cache.bump_version(THEME_CACHE_KEY) theme = get_theme_by_identifier(identifier) if (not theme): raise ValueError('Invalid theme identifier') theme.set_current() cache.set(THEME_CACHE_KEY, theme) return theme
null
null
null
What does the code activate based on identifier ?
def set_current_theme(identifier): cache.bump_version(THEME_CACHE_KEY) theme = get_theme_by_identifier(identifier) if (not theme): raise ValueError('Invalid theme identifier') theme.set_current() cache.set(THEME_CACHE_KEY, theme) return theme
null
null
null
a theme
codeqa
def set current theme identifier cache bump version THEME CACHE KEY theme get theme by identifier identifier if not theme raise Value Error ' Invalidthemeidentifier' theme set current cache set THEME CACHE KEY theme return theme
null
null
null
null
Question: What does the code activate based on identifier ? Code: def set_current_theme(identifier): cache.bump_version(THEME_CACHE_KEY) theme = get_theme_by_identifier(identifier) if (not theme): raise ValueError('Invalid theme identifier') theme.set_current() cache.set(THEME_CACHE_KEY, theme) return theme
null
null
null
What does the code close ?
def closeDumper(status, msg=''): if (hasattr(conf, 'dumper') and hasattr(conf.dumper, 'finish')): conf.dumper.finish(status, msg)
null
null
null
the dumper of the session
codeqa
def close Dumper status msg '' if hasattr conf 'dumper' and hasattr conf dumper 'finish' conf dumper finish status msg
null
null
null
null
Question: What does the code close ? Code: def closeDumper(status, msg=''): if (hasattr(conf, 'dumper') and hasattr(conf.dumper, 'finish')): conf.dumper.finish(status, msg)
null
null
null
What does the code append ?
def get_footer(email_account, footer=None): footer = (footer or u'') if (email_account and email_account.footer): footer += u'<div style="margin: 15px auto;">{0}</div>'.format(email_account.footer) footer += u'<!--unsubscribe link here-->' company_address = frappe.db.get_default(u'email_footer_address') if company_address: footer += u'<div style="margin: 15px auto; text-align: center; color: #8d99a6">{0}</div>'.format(company_address.replace(u'\n', u'<br>')) if (not cint(frappe.db.get_default(u'disable_standard_email_footer'))): for default_mail_footer in frappe.get_hooks(u'default_mail_footer'): footer += u'<div style="margin: 15px auto;">{0}</div>'.format(default_mail_footer) return footer
null
null
null
a footer
codeqa
def get footer email account footer None footer footer or u'' if email account and email account footer footer + u'<divstyle "margin 15 pxauto ">{ 0 }</div>' format email account footer footer + u'< --unsubscribelinkhere-->'company address frappe db get default u'email footer address' if company address footer + u'<divstyle "margin 15 pxauto text-align center color #8 d 99 a 6 ">{ 0 }</div>' format company address replace u'\n' u'<br>' if not cint frappe db get default u'disable standard email footer' for default mail footer in frappe get hooks u'default mail footer' footer + u'<divstyle "margin 15 pxauto ">{ 0 }</div>' format default mail footer return footer
null
null
null
null
Question: What does the code append ? Code: def get_footer(email_account, footer=None): footer = (footer or u'') if (email_account and email_account.footer): footer += u'<div style="margin: 15px auto;">{0}</div>'.format(email_account.footer) footer += u'<!--unsubscribe link here-->' company_address = frappe.db.get_default(u'email_footer_address') if company_address: footer += u'<div style="margin: 15px auto; text-align: center; color: #8d99a6">{0}</div>'.format(company_address.replace(u'\n', u'<br>')) if (not cint(frappe.db.get_default(u'disable_standard_email_footer'))): for default_mail_footer in frappe.get_hooks(u'default_mail_footer'): footer += u'<div style="margin: 15px auto;">{0}</div>'.format(default_mail_footer) return footer
null
null
null
What does the code ensure ?
def clean_image_extension(form_field): if form_field: if ('.' not in form_field.name): raise ValidationError(MSG_IMAGE_EXTENSION) (_, ext) = form_field.name.rsplit('.', 1) if (ext.lower() not in ALLOWED_IMAGE_EXTENSIONS): raise ValidationError(MSG_IMAGE_EXTENSION)
null
null
null
only images of certain extensions can be uploaded
codeqa
def clean image extension form field if form field if ' ' not in form field name raise Validation Error MSG IMAGE EXTENSION ext form field name rsplit ' ' 1 if ext lower not in ALLOWED IMAGE EXTENSIONS raise Validation Error MSG IMAGE EXTENSION
null
null
null
null
Question: What does the code ensure ? Code: def clean_image_extension(form_field): if form_field: if ('.' not in form_field.name): raise ValidationError(MSG_IMAGE_EXTENSION) (_, ext) = form_field.name.rsplit('.', 1) if (ext.lower() not in ALLOWED_IMAGE_EXTENSIONS): raise ValidationError(MSG_IMAGE_EXTENSION)
null
null
null
What does the code remove ?
def remove(target, identifier, fn): _event_key(target, identifier, fn).remove()
null
null
null
an event listener
codeqa
def remove target identifier fn event key target identifier fn remove
null
null
null
null
Question: What does the code remove ? Code: def remove(target, identifier, fn): _event_key(target, identifier, fn).remove()
null
null
null
For what purpose do export job create ?
def create_export_job(task_id, event_id): export_job = ExportJob.query.filter_by(event_id=event_id).first() task_url = url_for('api.extras_celery_task', task_id=task_id) if export_job: export_job.task = task_url export_job.user_email = g.user.email export_job.event = EventModel.query.get(event_id) export_job.start_time = datetime.now() else: export_job = ExportJob(task=task_url, user_email=g.user.email, event=EventModel.query.get(event_id)) save_to_db(export_job, 'ExportJob saved')
null
null
null
for an export that is going to start
codeqa
def create export job task id event id export job Export Job query filter by event id event id first task url url for 'api extras celery task' task id task id if export job export job task task urlexport job user email g user emailexport job event Event Model query get event id export job start time datetime now else export job Export Job task task url user email g user email event Event Model query get event id save to db export job ' Export Jobsaved'
null
null
null
null
Question: For what purpose do export job create ? Code: def create_export_job(task_id, event_id): export_job = ExportJob.query.filter_by(event_id=event_id).first() task_url = url_for('api.extras_celery_task', task_id=task_id) if export_job: export_job.task = task_url export_job.user_email = g.user.email export_job.event = EventModel.query.get(event_id) export_job.start_time = datetime.now() else: export_job = ExportJob(task=task_url, user_email=g.user.email, event=EventModel.query.get(event_id)) save_to_db(export_job, 'ExportJob saved')
null
null
null
What does the code add to the query queue ?
def add_queries(queries, insert_items=None, delete_items=None): for q in queries: if (insert_items and q.can_insert()): g.log.debug(('Inserting %s into query %s' % (insert_items, q))) with g.stats.get_timer('permacache.foreground.insert'): q.insert(insert_items) elif (delete_items and q.can_delete()): g.log.debug(('Deleting %s from query %s' % (delete_items, q))) with g.stats.get_timer('permacache.foreground.delete'): q.delete(delete_items) else: raise Exception(('Cannot update query %r!' % (q,))) with CachedQueryMutator() as m: new_queries = [getattr(q, 'new_query') for q in queries if hasattr(q, 'new_query')] if insert_items: for query in new_queries: m.insert(query, tup(insert_items)) if delete_items: for query in new_queries: m.delete(query, tup(delete_items))
null
null
null
multiple queries
codeqa
def add queries queries insert items None delete items None for q in queries if insert items and q can insert g log debug ' Inserting%sintoquery%s' % insert items q with g stats get timer 'permacache foreground insert' q insert insert items elif delete items and q can delete g log debug ' Deleting%sfromquery%s' % delete items q with g stats get timer 'permacache foreground delete' q delete delete items else raise Exception ' Cannotupdatequery%r ' % q with Cached Query Mutator as m new queries [getattr q 'new query' for q in queries if hasattr q 'new query' ]if insert items for query in new queries m insert query tup insert items if delete items for query in new queries m delete query tup delete items
null
null
null
null
Question: What does the code add to the query queue ? Code: def add_queries(queries, insert_items=None, delete_items=None): for q in queries: if (insert_items and q.can_insert()): g.log.debug(('Inserting %s into query %s' % (insert_items, q))) with g.stats.get_timer('permacache.foreground.insert'): q.insert(insert_items) elif (delete_items and q.can_delete()): g.log.debug(('Deleting %s from query %s' % (delete_items, q))) with g.stats.get_timer('permacache.foreground.delete'): q.delete(delete_items) else: raise Exception(('Cannot update query %r!' % (q,))) with CachedQueryMutator() as m: new_queries = [getattr(q, 'new_query') for q in queries if hasattr(q, 'new_query')] if insert_items: for query in new_queries: m.insert(query, tup(insert_items)) if delete_items: for query in new_queries: m.delete(query, tup(delete_items))
null
null
null
How does a list rotate ?
def rotate_right(x, y): if (len(x) == 0): return [] y = (len(x) - (y % len(x))) return (x[y:] + x[:y])
null
null
null
by the number of steps specified in y
codeqa
def rotate right x y if len x 0 return []y len x - y % len x return x[y ] + x[ y]
null
null
null
null
Question: How does a list rotate ? Code: def rotate_right(x, y): if (len(x) == 0): return [] y = (len(x) - (y % len(x))) return (x[y:] + x[:y])
null
null
null
What does the code ensure ?
def test_lex_exception(): try: tokenize('(foo') assert (True is False) except PrematureEndOfInput: pass try: tokenize('{foo bar') assert (True is False) except PrematureEndOfInput: pass try: tokenize('(defn foo [bar]') assert (True is False) except PrematureEndOfInput: pass try: tokenize('(foo "bar') assert (True is False) except PrematureEndOfInput: pass
null
null
null
tokenize throws a fit on a partial input
codeqa
def test lex exception try tokenize ' foo' assert True is False except Premature End Of Input passtry tokenize '{foobar' assert True is False except Premature End Of Input passtry tokenize ' defnfoo[bar]' assert True is False except Premature End Of Input passtry tokenize ' foo"bar' assert True is False except Premature End Of Input pass
null
null
null
null
Question: What does the code ensure ? Code: def test_lex_exception(): try: tokenize('(foo') assert (True is False) except PrematureEndOfInput: pass try: tokenize('{foo bar') assert (True is False) except PrematureEndOfInput: pass try: tokenize('(defn foo [bar]') assert (True is False) except PrematureEndOfInput: pass try: tokenize('(foo "bar') assert (True is False) except PrematureEndOfInput: pass
null
null
null
What do tokenize throw ?
def test_lex_exception(): try: tokenize('(foo') assert (True is False) except PrematureEndOfInput: pass try: tokenize('{foo bar') assert (True is False) except PrematureEndOfInput: pass try: tokenize('(defn foo [bar]') assert (True is False) except PrematureEndOfInput: pass try: tokenize('(foo "bar') assert (True is False) except PrematureEndOfInput: pass
null
null
null
a fit on a partial input
codeqa
def test lex exception try tokenize ' foo' assert True is False except Premature End Of Input passtry tokenize '{foobar' assert True is False except Premature End Of Input passtry tokenize ' defnfoo[bar]' assert True is False except Premature End Of Input passtry tokenize ' foo"bar' assert True is False except Premature End Of Input pass
null
null
null
null
Question: What do tokenize throw ? Code: def test_lex_exception(): try: tokenize('(foo') assert (True is False) except PrematureEndOfInput: pass try: tokenize('{foo bar') assert (True is False) except PrematureEndOfInput: pass try: tokenize('(defn foo [bar]') assert (True is False) except PrematureEndOfInput: pass try: tokenize('(foo "bar') assert (True is False) except PrematureEndOfInput: pass
null
null
null
What throws a fit on a partial input ?
def test_lex_exception(): try: tokenize('(foo') assert (True is False) except PrematureEndOfInput: pass try: tokenize('{foo bar') assert (True is False) except PrematureEndOfInput: pass try: tokenize('(defn foo [bar]') assert (True is False) except PrematureEndOfInput: pass try: tokenize('(foo "bar') assert (True is False) except PrematureEndOfInput: pass
null
null
null
tokenize
codeqa
def test lex exception try tokenize ' foo' assert True is False except Premature End Of Input passtry tokenize '{foobar' assert True is False except Premature End Of Input passtry tokenize ' defnfoo[bar]' assert True is False except Premature End Of Input passtry tokenize ' foo"bar' assert True is False except Premature End Of Input pass
null
null
null
null
Question: What throws a fit on a partial input ? Code: def test_lex_exception(): try: tokenize('(foo') assert (True is False) except PrematureEndOfInput: pass try: tokenize('{foo bar') assert (True is False) except PrematureEndOfInput: pass try: tokenize('(defn foo [bar]') assert (True is False) except PrematureEndOfInput: pass try: tokenize('(foo "bar') assert (True is False) except PrematureEndOfInput: pass
null
null
null
How did whitespace normalize ?
def normalize(str): return whitespace.sub(' ', str).strip()
null
null
null
by stripping leading and trailing whitespace and replacing sequences of whitespace characters by a single space
codeqa
def normalize str return whitespace sub '' str strip
null
null
null
null
Question: How did whitespace normalize ? Code: def normalize(str): return whitespace.sub(' ', str).strip()
null
null
null
What returns the argument string with whitespace normalized by stripping leading and trailing whitespace and replacing sequences of whitespace characters by a single space ?
def normalize(str): return whitespace.sub(' ', str).strip()
null
null
null
the normalize - space function
codeqa
def normalize str return whitespace sub '' str strip
null
null
null
null
Question: What returns the argument string with whitespace normalized by stripping leading and trailing whitespace and replacing sequences of whitespace characters by a single space ? Code: def normalize(str): return whitespace.sub(' ', str).strip()
null
null
null
What does the code delete ?
def do_ScpDelete(po): sc = _get_option(po, 'service_class') try: ScpDelete(sc) except adsi.error as details: if (details[0] != winerror.ERROR_DS_OBJ_NOT_FOUND): raise log(2, "ScpDelete ignoring ERROR_DS_OBJ_NOT_FOUND for service-class '%s'", sc) return sc
null
null
null
a service connection point
codeqa
def do Scp Delete po sc get option po 'service class' try Scp Delete sc except adsi error as details if details[ 0 ] winerror ERROR DS OBJ NOT FOUND raiselog 2 " Scp Deleteignoring ERROR DS OBJ NOT FOUN Dforservice-class'%s'" sc return sc
null
null
null
null
Question: What does the code delete ? Code: def do_ScpDelete(po): sc = _get_option(po, 'service_class') try: ScpDelete(sc) except adsi.error as details: if (details[0] != winerror.ERROR_DS_OBJ_NOT_FOUND): raise log(2, "ScpDelete ignoring ERROR_DS_OBJ_NOT_FOUND for service-class '%s'", sc) return sc
null
null
null
What will a reactor resolve deterministically ?
def deterministicResolvingReactor(reactor, expectedAddresses=(), hostMap=None): if (hostMap is None): hostMap = {} hostMap = hostMap.copy() @provider(IHostnameResolver) class SimpleNameResolver(object, ): @staticmethod def resolveHostName(resolutionReceiver, hostName, portNumber=0, addressTypes=None, transportSemantics='TCP'): resolutionReceiver.resolutionBegan(None) for expectedAddress in hostMap.get(hostName, expectedAddresses): if isinstance(expectedAddress, str): expectedAddress = [IPv4Address, IPv6Address][isIPv6Address(expectedAddress)]('TCP', expectedAddress, portNumber) resolutionReceiver.addressResolved(expectedAddress) resolutionReceiver.resolutionComplete() @provider(IReactorPluggableNameResolver) class WithResolver(proxyForInterface(InterfaceClass('*', tuple(providedBy(reactor)))), ): nameResolver = SimpleNameResolver() return WithResolver(reactor)
null
null
null
all hostnames
codeqa
def deterministic Resolving Reactor reactor expected Addresses host Map None if host Map is None host Map {}host Map host Map copy @provider I Hostname Resolver class Simple Name Resolver object @staticmethoddef resolve Host Name resolution Receiver host Name port Number 0 address Types None transport Semantics 'TCP' resolution Receiver resolution Began None for expected Address in host Map get host Name expected Addresses if isinstance expected Address str expected Address [I Pv 4 Address I Pv 6 Address][is I Pv 6 Address expected Address ] 'TCP' expected Address port Number resolution Receiver address Resolved expected Address resolution Receiver resolution Complete @provider I Reactor Pluggable Name Resolver class With Resolver proxy For Interface Interface Class '*' tuple provided By reactor name Resolver Simple Name Resolver return With Resolver reactor
null
null
null
null
Question: What will a reactor resolve deterministically ? Code: def deterministicResolvingReactor(reactor, expectedAddresses=(), hostMap=None): if (hostMap is None): hostMap = {} hostMap = hostMap.copy() @provider(IHostnameResolver) class SimpleNameResolver(object, ): @staticmethod def resolveHostName(resolutionReceiver, hostName, portNumber=0, addressTypes=None, transportSemantics='TCP'): resolutionReceiver.resolutionBegan(None) for expectedAddress in hostMap.get(hostName, expectedAddresses): if isinstance(expectedAddress, str): expectedAddress = [IPv4Address, IPv6Address][isIPv6Address(expectedAddress)]('TCP', expectedAddress, portNumber) resolutionReceiver.addressResolved(expectedAddress) resolutionReceiver.resolutionComplete() @provider(IReactorPluggableNameResolver) class WithResolver(proxyForInterface(InterfaceClass('*', tuple(providedBy(reactor)))), ): nameResolver = SimpleNameResolver() return WithResolver(reactor)
null
null
null
What does the code create ?
def deterministicResolvingReactor(reactor, expectedAddresses=(), hostMap=None): if (hostMap is None): hostMap = {} hostMap = hostMap.copy() @provider(IHostnameResolver) class SimpleNameResolver(object, ): @staticmethod def resolveHostName(resolutionReceiver, hostName, portNumber=0, addressTypes=None, transportSemantics='TCP'): resolutionReceiver.resolutionBegan(None) for expectedAddress in hostMap.get(hostName, expectedAddresses): if isinstance(expectedAddress, str): expectedAddress = [IPv4Address, IPv6Address][isIPv6Address(expectedAddress)]('TCP', expectedAddress, portNumber) resolutionReceiver.addressResolved(expectedAddress) resolutionReceiver.resolutionComplete() @provider(IReactorPluggableNameResolver) class WithResolver(proxyForInterface(InterfaceClass('*', tuple(providedBy(reactor)))), ): nameResolver = SimpleNameResolver() return WithResolver(reactor)
null
null
null
a reactor that will deterministically resolve all hostnames it is passed to the list of addresses given
codeqa
def deterministic Resolving Reactor reactor expected Addresses host Map None if host Map is None host Map {}host Map host Map copy @provider I Hostname Resolver class Simple Name Resolver object @staticmethoddef resolve Host Name resolution Receiver host Name port Number 0 address Types None transport Semantics 'TCP' resolution Receiver resolution Began None for expected Address in host Map get host Name expected Addresses if isinstance expected Address str expected Address [I Pv 4 Address I Pv 6 Address][is I Pv 6 Address expected Address ] 'TCP' expected Address port Number resolution Receiver address Resolved expected Address resolution Receiver resolution Complete @provider I Reactor Pluggable Name Resolver class With Resolver proxy For Interface Interface Class '*' tuple provided By reactor name Resolver Simple Name Resolver return With Resolver reactor
null
null
null
null
Question: What does the code create ? Code: def deterministicResolvingReactor(reactor, expectedAddresses=(), hostMap=None): if (hostMap is None): hostMap = {} hostMap = hostMap.copy() @provider(IHostnameResolver) class SimpleNameResolver(object, ): @staticmethod def resolveHostName(resolutionReceiver, hostName, portNumber=0, addressTypes=None, transportSemantics='TCP'): resolutionReceiver.resolutionBegan(None) for expectedAddress in hostMap.get(hostName, expectedAddresses): if isinstance(expectedAddress, str): expectedAddress = [IPv4Address, IPv6Address][isIPv6Address(expectedAddress)]('TCP', expectedAddress, portNumber) resolutionReceiver.addressResolved(expectedAddress) resolutionReceiver.resolutionComplete() @provider(IReactorPluggableNameResolver) class WithResolver(proxyForInterface(InterfaceClass('*', tuple(providedBy(reactor)))), ): nameResolver = SimpleNameResolver() return WithResolver(reactor)
null
null
null
How will a reactor resolve all hostnames ?
def deterministicResolvingReactor(reactor, expectedAddresses=(), hostMap=None): if (hostMap is None): hostMap = {} hostMap = hostMap.copy() @provider(IHostnameResolver) class SimpleNameResolver(object, ): @staticmethod def resolveHostName(resolutionReceiver, hostName, portNumber=0, addressTypes=None, transportSemantics='TCP'): resolutionReceiver.resolutionBegan(None) for expectedAddress in hostMap.get(hostName, expectedAddresses): if isinstance(expectedAddress, str): expectedAddress = [IPv4Address, IPv6Address][isIPv6Address(expectedAddress)]('TCP', expectedAddress, portNumber) resolutionReceiver.addressResolved(expectedAddress) resolutionReceiver.resolutionComplete() @provider(IReactorPluggableNameResolver) class WithResolver(proxyForInterface(InterfaceClass('*', tuple(providedBy(reactor)))), ): nameResolver = SimpleNameResolver() return WithResolver(reactor)
null
null
null
deterministically
codeqa
def deterministic Resolving Reactor reactor expected Addresses host Map None if host Map is None host Map {}host Map host Map copy @provider I Hostname Resolver class Simple Name Resolver object @staticmethoddef resolve Host Name resolution Receiver host Name port Number 0 address Types None transport Semantics 'TCP' resolution Receiver resolution Began None for expected Address in host Map get host Name expected Addresses if isinstance expected Address str expected Address [I Pv 4 Address I Pv 6 Address][is I Pv 6 Address expected Address ] 'TCP' expected Address port Number resolution Receiver address Resolved expected Address resolution Receiver resolution Complete @provider I Reactor Pluggable Name Resolver class With Resolver proxy For Interface Interface Class '*' tuple provided By reactor name Resolver Simple Name Resolver return With Resolver reactor
null
null
null
null
Question: How will a reactor resolve all hostnames ? Code: def deterministicResolvingReactor(reactor, expectedAddresses=(), hostMap=None): if (hostMap is None): hostMap = {} hostMap = hostMap.copy() @provider(IHostnameResolver) class SimpleNameResolver(object, ): @staticmethod def resolveHostName(resolutionReceiver, hostName, portNumber=0, addressTypes=None, transportSemantics='TCP'): resolutionReceiver.resolutionBegan(None) for expectedAddress in hostMap.get(hostName, expectedAddresses): if isinstance(expectedAddress, str): expectedAddress = [IPv4Address, IPv6Address][isIPv6Address(expectedAddress)]('TCP', expectedAddress, portNumber) resolutionReceiver.addressResolved(expectedAddress) resolutionReceiver.resolutionComplete() @provider(IReactorPluggableNameResolver) class WithResolver(proxyForInterface(InterfaceClass('*', tuple(providedBy(reactor)))), ): nameResolver = SimpleNameResolver() return WithResolver(reactor)
null
null
null
What will resolve all hostnames deterministically ?
def deterministicResolvingReactor(reactor, expectedAddresses=(), hostMap=None): if (hostMap is None): hostMap = {} hostMap = hostMap.copy() @provider(IHostnameResolver) class SimpleNameResolver(object, ): @staticmethod def resolveHostName(resolutionReceiver, hostName, portNumber=0, addressTypes=None, transportSemantics='TCP'): resolutionReceiver.resolutionBegan(None) for expectedAddress in hostMap.get(hostName, expectedAddresses): if isinstance(expectedAddress, str): expectedAddress = [IPv4Address, IPv6Address][isIPv6Address(expectedAddress)]('TCP', expectedAddress, portNumber) resolutionReceiver.addressResolved(expectedAddress) resolutionReceiver.resolutionComplete() @provider(IReactorPluggableNameResolver) class WithResolver(proxyForInterface(InterfaceClass('*', tuple(providedBy(reactor)))), ): nameResolver = SimpleNameResolver() return WithResolver(reactor)
null
null
null
a reactor
codeqa
def deterministic Resolving Reactor reactor expected Addresses host Map None if host Map is None host Map {}host Map host Map copy @provider I Hostname Resolver class Simple Name Resolver object @staticmethoddef resolve Host Name resolution Receiver host Name port Number 0 address Types None transport Semantics 'TCP' resolution Receiver resolution Began None for expected Address in host Map get host Name expected Addresses if isinstance expected Address str expected Address [I Pv 4 Address I Pv 6 Address][is I Pv 6 Address expected Address ] 'TCP' expected Address port Number resolution Receiver address Resolved expected Address resolution Receiver resolution Complete @provider I Reactor Pluggable Name Resolver class With Resolver proxy For Interface Interface Class '*' tuple provided By reactor name Resolver Simple Name Resolver return With Resolver reactor
null
null
null
null
Question: What will resolve all hostnames deterministically ? Code: def deterministicResolvingReactor(reactor, expectedAddresses=(), hostMap=None): if (hostMap is None): hostMap = {} hostMap = hostMap.copy() @provider(IHostnameResolver) class SimpleNameResolver(object, ): @staticmethod def resolveHostName(resolutionReceiver, hostName, portNumber=0, addressTypes=None, transportSemantics='TCP'): resolutionReceiver.resolutionBegan(None) for expectedAddress in hostMap.get(hostName, expectedAddresses): if isinstance(expectedAddress, str): expectedAddress = [IPv4Address, IPv6Address][isIPv6Address(expectedAddress)]('TCP', expectedAddress, portNumber) resolutionReceiver.addressResolved(expectedAddress) resolutionReceiver.resolutionComplete() @provider(IReactorPluggableNameResolver) class WithResolver(proxyForInterface(InterfaceClass('*', tuple(providedBy(reactor)))), ): nameResolver = SimpleNameResolver() return WithResolver(reactor)
null
null
null
What does the code ensure ?
def ValidateTargetType(target, target_dict): VALID_TARGET_TYPES = ('executable', 'loadable_module', 'static_library', 'shared_library', 'mac_kernel_extension', 'none') target_type = target_dict.get('type', None) if (target_type not in VALID_TARGET_TYPES): raise GypError(("Target %s has an invalid target type '%s'. Must be one of %s." % (target, target_type, '/'.join(VALID_TARGET_TYPES)))) if (target_dict.get('standalone_static_library', 0) and (not (target_type == 'static_library'))): raise GypError(('Target %s has type %s but standalone_static_library flag is only valid for static_library type.' % (target, target_type)))
null
null
null
the type field on the target is one of the known types
codeqa
def Validate Target Type target target dict VALID TARGET TYPES 'executable' 'loadable module' 'static library' 'shared library' 'mac kernel extension' 'none' target type target dict get 'type' None if target type not in VALID TARGET TYPES raise Gyp Error " Target%shasaninvalidtargettype'%s' Mustbeoneof%s " % target target type '/' join VALID TARGET TYPES if target dict get 'standalone static library' 0 and not target type 'static library' raise Gyp Error ' Target%shastype%sbutstandalone static libraryflagisonlyvalidforstatic librarytype ' % target target type
null
null
null
null
Question: What does the code ensure ? Code: def ValidateTargetType(target, target_dict): VALID_TARGET_TYPES = ('executable', 'loadable_module', 'static_library', 'shared_library', 'mac_kernel_extension', 'none') target_type = target_dict.get('type', None) if (target_type not in VALID_TARGET_TYPES): raise GypError(("Target %s has an invalid target type '%s'. Must be one of %s." % (target, target_type, '/'.join(VALID_TARGET_TYPES)))) if (target_dict.get('standalone_static_library', 0) and (not (target_type == 'static_library'))): raise GypError(('Target %s has type %s but standalone_static_library flag is only valid for static_library type.' % (target, target_type)))
null
null
null
What do all attributes match in match ?
def finddir(o, match, case=False): if case: names = [(name, name) for name in dir(o) if is_string_like(name)] else: names = [(name.lower(), name) for name in dir(o) if is_string_like(name)] match = match.lower() return [orig for (name, orig) in names if (name.find(match) >= 0)]
null
null
null
string
codeqa
def finddir o match case False if case names [ name name for name in dir o if is string like name ]else names [ name lower name for name in dir o if is string like name ]match match lower return [orig for name orig in names if name find match > 0 ]
null
null
null
null
Question: What do all attributes match in match ? Code: def finddir(o, match, case=False): if case: names = [(name, name) for name in dir(o) if is_string_like(name)] else: names = [(name.lower(), name) for name in dir(o) if is_string_like(name)] match = match.lower() return [orig for (name, orig) in names if (name.find(match) >= 0)]
null
null
null
What match string in match ?
def finddir(o, match, case=False): if case: names = [(name, name) for name in dir(o) if is_string_like(name)] else: names = [(name.lower(), name) for name in dir(o) if is_string_like(name)] match = match.lower() return [orig for (name, orig) in names if (name.find(match) >= 0)]
null
null
null
all attributes
codeqa
def finddir o match case False if case names [ name name for name in dir o if is string like name ]else names [ name lower name for name in dir o if is string like name ]match match lower return [orig for name orig in names if name find match > 0 ]
null
null
null
null
Question: What match string in match ? Code: def finddir(o, match, case=False): if case: names = [(name, name) for name in dir(o) if is_string_like(name)] else: names = [(name.lower(), name) for name in dir(o) if is_string_like(name)] match = match.lower() return [orig for (name, orig) in names if (name.find(match) >= 0)]
null
null
null
How do all attributes match string ?
def finddir(o, match, case=False): if case: names = [(name, name) for name in dir(o) if is_string_like(name)] else: names = [(name.lower(), name) for name in dir(o) if is_string_like(name)] match = match.lower() return [orig for (name, orig) in names if (name.find(match) >= 0)]
null
null
null
in match
codeqa
def finddir o match case False if case names [ name name for name in dir o if is string like name ]else names [ name lower name for name in dir o if is string like name ]match match lower return [orig for name orig in names if name find match > 0 ]
null
null
null
null
Question: How do all attributes match string ? Code: def finddir(o, match, case=False): if case: names = [(name, name) for name in dir(o) if is_string_like(name)] else: names = [(name.lower(), name) for name in dir(o) if is_string_like(name)] match = match.lower() return [orig for (name, orig) in names if (name.find(match) >= 0)]
null
null
null
What do recursive helper convert to an entity ?
def _message_to_entity(msg, modelclass): ent = modelclass() for (prop_name, prop) in modelclass._properties.iteritems(): if (prop._code_name == 'blob_'): continue value = getattr(msg, prop_name) if ((value is not None) and isinstance(prop, model.StructuredProperty)): if prop._repeated: value = [_message_to_entity(v, prop._modelclass) for v in value] else: value = _message_to_entity(value, prop._modelclass) setattr(ent, prop_name, value) return ent
null
null
null
a message
codeqa
def message to entity msg modelclass ent modelclass for prop name prop in modelclass properties iteritems if prop code name 'blob ' continuevalue getattr msg prop name if value is not None and isinstance prop model Structured Property if prop repeated value [ message to entity v prop modelclass for v in value]else value message to entity value prop modelclass setattr ent prop name value return ent
null
null
null
null
Question: What do recursive helper convert to an entity ? Code: def _message_to_entity(msg, modelclass): ent = modelclass() for (prop_name, prop) in modelclass._properties.iteritems(): if (prop._code_name == 'blob_'): continue value = getattr(msg, prop_name) if ((value is not None) and isinstance(prop, model.StructuredProperty)): if prop._repeated: value = [_message_to_entity(v, prop._modelclass) for v in value] else: value = _message_to_entity(value, prop._modelclass) setattr(ent, prop_name, value) return ent
null
null
null
What converts a message to an entity ?
def _message_to_entity(msg, modelclass): ent = modelclass() for (prop_name, prop) in modelclass._properties.iteritems(): if (prop._code_name == 'blob_'): continue value = getattr(msg, prop_name) if ((value is not None) and isinstance(prop, model.StructuredProperty)): if prop._repeated: value = [_message_to_entity(v, prop._modelclass) for v in value] else: value = _message_to_entity(value, prop._modelclass) setattr(ent, prop_name, value) return ent
null
null
null
recursive helper
codeqa
def message to entity msg modelclass ent modelclass for prop name prop in modelclass properties iteritems if prop code name 'blob ' continuevalue getattr msg prop name if value is not None and isinstance prop model Structured Property if prop repeated value [ message to entity v prop modelclass for v in value]else value message to entity value prop modelclass setattr ent prop name value return ent
null
null
null
null
Question: What converts a message to an entity ? Code: def _message_to_entity(msg, modelclass): ent = modelclass() for (prop_name, prop) in modelclass._properties.iteritems(): if (prop._code_name == 'blob_'): continue value = getattr(msg, prop_name) if ((value is not None) and isinstance(prop, model.StructuredProperty)): if prop._repeated: value = [_message_to_entity(v, prop._modelclass) for v in value] else: value = _message_to_entity(value, prop._modelclass) setattr(ent, prop_name, value) return ent
null
null
null
When did callback invoke ?
def cbExamineMbox(result, proto): return proto.fetchSpecific('1:*', headerType='HEADER.FIELDS', headerArgs=['SUBJECT']).addCallback(cbFetch, proto)
null
null
null
when examine command completes
codeqa
def cb Examine Mbox result proto return proto fetch Specific '1 *' header Type 'HEADER FIELDS' header Args ['SUBJECT'] add Callback cb Fetch proto
null
null
null
null
Question: When did callback invoke ? Code: def cbExamineMbox(result, proto): return proto.fetchSpecific('1:*', headerType='HEADER.FIELDS', headerArgs=['SUBJECT']).addCallback(cbFetch, proto)
null
null
null
What did information use ?
def get_footer(is_secure=True): return {'copyright': _footer_copyright(), 'logo_image': _footer_logo_img(is_secure), 'social_links': _footer_social_links(), 'navigation_links': _footer_navigation_links(), 'mobile_links': _footer_mobile_links(is_secure), 'legal_links': _footer_legal_links(), 'openedx_link': _footer_openedx_link()}
null
null
null
to render the footer
codeqa
def get footer is secure True return {'copyright' footer copyright 'logo image' footer logo img is secure 'social links' footer social links 'navigation links' footer navigation links 'mobile links' footer mobile links is secure 'legal links' footer legal links 'openedx link' footer openedx link }
null
null
null
null
Question: What did information use ? Code: def get_footer(is_secure=True): return {'copyright': _footer_copyright(), 'logo_image': _footer_logo_img(is_secure), 'social_links': _footer_social_links(), 'navigation_links': _footer_navigation_links(), 'mobile_links': _footer_mobile_links(is_secure), 'legal_links': _footer_legal_links(), 'openedx_link': _footer_openedx_link()}
null
null
null
What used to render the footer ?
def get_footer(is_secure=True): return {'copyright': _footer_copyright(), 'logo_image': _footer_logo_img(is_secure), 'social_links': _footer_social_links(), 'navigation_links': _footer_navigation_links(), 'mobile_links': _footer_mobile_links(is_secure), 'legal_links': _footer_legal_links(), 'openedx_link': _footer_openedx_link()}
null
null
null
information
codeqa
def get footer is secure True return {'copyright' footer copyright 'logo image' footer logo img is secure 'social links' footer social links 'navigation links' footer navigation links 'mobile links' footer mobile links is secure 'legal links' footer legal links 'openedx link' footer openedx link }
null
null
null
null
Question: What used to render the footer ? Code: def get_footer(is_secure=True): return {'copyright': _footer_copyright(), 'logo_image': _footer_logo_img(is_secure), 'social_links': _footer_social_links(), 'navigation_links': _footer_navigation_links(), 'mobile_links': _footer_mobile_links(is_secure), 'legal_links': _footer_legal_links(), 'openedx_link': _footer_openedx_link()}
null
null
null
What set on a monitor ?
@utils.arg('monitor', metavar='<monitor>', help='ID of the monitor to update metadata on.') @utils.arg('action', metavar='<action>', choices=['set', 'unset'], help="Actions: 'set' or 'unset'") @utils.arg('metadata', metavar='<key=value>', nargs='+', default=[], help='Metadata to set/unset (only key is necessary on unset)') @utils.service_type('monitor') def do_metadata(cs, args): monitor = _find_monitor(cs, args.monitor) metadata = _extract_metadata(args) if (args.action == 'set'): cs.monitors.set_metadata(monitor, metadata) elif (args.action == 'unset'): cs.monitors.delete_metadata(monitor, metadata.keys())
null
null
null
metadata
codeqa
@utils arg 'monitor' metavar '<monitor>' help 'I Dofthemonitortoupdatemetadataon ' @utils arg 'action' metavar '<action>' choices ['set' 'unset'] help " Actions 'set'or'unset'" @utils arg 'metadata' metavar '<key value>' nargs '+' default [] help ' Metadatatoset/unset onlykeyisnecessaryonunset ' @utils service type 'monitor' def do metadata cs args monitor find monitor cs args monitor metadata extract metadata args if args action 'set' cs monitors set metadata monitor metadata elif args action 'unset' cs monitors delete metadata monitor metadata keys
null
null
null
null
Question: What set on a monitor ? Code: @utils.arg('monitor', metavar='<monitor>', help='ID of the monitor to update metadata on.') @utils.arg('action', metavar='<action>', choices=['set', 'unset'], help="Actions: 'set' or 'unset'") @utils.arg('metadata', metavar='<key=value>', nargs='+', default=[], help='Metadata to set/unset (only key is necessary on unset)') @utils.service_type('monitor') def do_metadata(cs, args): monitor = _find_monitor(cs, args.monitor) metadata = _extract_metadata(args) if (args.action == 'set'): cs.monitors.set_metadata(monitor, metadata) elif (args.action == 'unset'): cs.monitors.delete_metadata(monitor, metadata.keys())
null
null
null
Where did metadata set ?
@utils.arg('monitor', metavar='<monitor>', help='ID of the monitor to update metadata on.') @utils.arg('action', metavar='<action>', choices=['set', 'unset'], help="Actions: 'set' or 'unset'") @utils.arg('metadata', metavar='<key=value>', nargs='+', default=[], help='Metadata to set/unset (only key is necessary on unset)') @utils.service_type('monitor') def do_metadata(cs, args): monitor = _find_monitor(cs, args.monitor) metadata = _extract_metadata(args) if (args.action == 'set'): cs.monitors.set_metadata(monitor, metadata) elif (args.action == 'unset'): cs.monitors.delete_metadata(monitor, metadata.keys())
null
null
null
on a monitor
codeqa
@utils arg 'monitor' metavar '<monitor>' help 'I Dofthemonitortoupdatemetadataon ' @utils arg 'action' metavar '<action>' choices ['set' 'unset'] help " Actions 'set'or'unset'" @utils arg 'metadata' metavar '<key value>' nargs '+' default [] help ' Metadatatoset/unset onlykeyisnecessaryonunset ' @utils service type 'monitor' def do metadata cs args monitor find monitor cs args monitor metadata extract metadata args if args action 'set' cs monitors set metadata monitor metadata elif args action 'unset' cs monitors delete metadata monitor metadata keys
null
null
null
null
Question: Where did metadata set ? Code: @utils.arg('monitor', metavar='<monitor>', help='ID of the monitor to update metadata on.') @utils.arg('action', metavar='<action>', choices=['set', 'unset'], help="Actions: 'set' or 'unset'") @utils.arg('metadata', metavar='<key=value>', nargs='+', default=[], help='Metadata to set/unset (only key is necessary on unset)') @utils.service_type('monitor') def do_metadata(cs, args): monitor = _find_monitor(cs, args.monitor) metadata = _extract_metadata(args) if (args.action == 'set'): cs.monitors.set_metadata(monitor, metadata) elif (args.action == 'unset'): cs.monitors.delete_metadata(monitor, metadata.keys())
null
null
null
For what purpose does the code replace contents with xxx ?
def mute_string(text): start = 1 end = (len(text) - 1) if text.endswith('"'): start += text.index('"') elif text.endswith("'"): start += text.index("'") if (text.endswith('"""') or text.endswith("'''")): start += 2 end -= 2 return ((text[:start] + ('x' * (end - start))) + text[end:])
null
null
null
to prevent syntax matching
codeqa
def mute string text start 1end len text - 1 if text endswith '"' start + text index '"' elif text endswith "'" start + text index "'" if text endswith '"""' or text endswith "'''" start + 2end - 2return text[ start] + 'x' * end - start + text[end ]
null
null
null
null
Question: For what purpose does the code replace contents with xxx ? Code: def mute_string(text): start = 1 end = (len(text) - 1) if text.endswith('"'): start += text.index('"') elif text.endswith("'"): start += text.index("'") if (text.endswith('"""') or text.endswith("'''")): start += 2 end -= 2 return ((text[:start] + ('x' * (end - start))) + text[end:])
null
null
null
How does the code replace contents to prevent syntax matching ?
def mute_string(text): start = 1 end = (len(text) - 1) if text.endswith('"'): start += text.index('"') elif text.endswith("'"): start += text.index("'") if (text.endswith('"""') or text.endswith("'''")): start += 2 end -= 2 return ((text[:start] + ('x' * (end - start))) + text[end:])
null
null
null
with xxx
codeqa
def mute string text start 1end len text - 1 if text endswith '"' start + text index '"' elif text endswith "'" start + text index "'" if text endswith '"""' or text endswith "'''" start + 2end - 2return text[ start] + 'x' * end - start + text[end ]
null
null
null
null
Question: How does the code replace contents to prevent syntax matching ? Code: def mute_string(text): start = 1 end = (len(text) - 1) if text.endswith('"'): start += text.index('"') elif text.endswith("'"): start += text.index("'") if (text.endswith('"""') or text.endswith("'''")): start += 2 end -= 2 return ((text[:start] + ('x' * (end - start))) + text[end:])
null
null
null
What does the code replace with xxx to prevent syntax matching ?
def mute_string(text): start = 1 end = (len(text) - 1) if text.endswith('"'): start += text.index('"') elif text.endswith("'"): start += text.index("'") if (text.endswith('"""') or text.endswith("'''")): start += 2 end -= 2 return ((text[:start] + ('x' * (end - start))) + text[end:])
null
null
null
contents
codeqa
def mute string text start 1end len text - 1 if text endswith '"' start + text index '"' elif text endswith "'" start + text index "'" if text endswith '"""' or text endswith "'''" start + 2end - 2return text[ start] + 'x' * end - start + text[end ]
null
null
null
null
Question: What does the code replace with xxx to prevent syntax matching ? Code: def mute_string(text): start = 1 end = (len(text) - 1) if text.endswith('"'): start += text.index('"') elif text.endswith("'"): start += text.index("'") if (text.endswith('"""') or text.endswith("'''")): start += 2 end -= 2 return ((text[:start] + ('x' * (end - start))) + text[end:])
null
null
null
What converts to underscores in a string ?
def to_safe(word): return re.sub('[^A-Za-z0-9\\-]', '_', word)
null
null
null
bad characters
codeqa
def to safe word return re sub '[^A- Za-z 0 - 9 \\-]' ' ' word
null
null
null
null
Question: What converts to underscores in a string ? Code: def to_safe(word): return re.sub('[^A-Za-z0-9\\-]', '_', word)
null
null
null
What does the code generate ?
def random_code_generator(): code_length = getattr(settings, 'REGISTRATION_CODE_LENGTH', 8) return generate_random_string(code_length)
null
null
null
a random alphanumeric code of length defined in registration_code_length settings
codeqa
def random code generator code length getattr settings 'REGISTRATION CODE LENGTH' 8 return generate random string code length
null
null
null
null
Question: What does the code generate ? Code: def random_code_generator(): code_length = getattr(settings, 'REGISTRATION_CODE_LENGTH', 8) return generate_random_string(code_length)
null
null
null
What defined in registration_code_length settings ?
def random_code_generator(): code_length = getattr(settings, 'REGISTRATION_CODE_LENGTH', 8) return generate_random_string(code_length)
null
null
null
a random alphanumeric code
codeqa
def random code generator code length getattr settings 'REGISTRATION CODE LENGTH' 8 return generate random string code length
null
null
null
null
Question: What defined in registration_code_length settings ? Code: def random_code_generator(): code_length = getattr(settings, 'REGISTRATION_CODE_LENGTH', 8) return generate_random_string(code_length)
null
null
null
Where did a random alphanumeric code define ?
def random_code_generator(): code_length = getattr(settings, 'REGISTRATION_CODE_LENGTH', 8) return generate_random_string(code_length)
null
null
null
in registration_code_length settings
codeqa
def random code generator code length getattr settings 'REGISTRATION CODE LENGTH' 8 return generate random string code length
null
null
null
null
Question: Where did a random alphanumeric code define ? Code: def random_code_generator(): code_length = getattr(settings, 'REGISTRATION_CODE_LENGTH', 8) return generate_random_string(code_length)
null
null
null
What does the code use ?
@world.absorb def wait_for_js_variable_truthy(variable): javascript = '\n var callback = arguments[arguments.length - 1];\n var unloadHandler = function() {{\n callback("unload");\n }}\n addEventListener("beforeunload", unloadHandler);\n addEventListener("unload", unloadHandler);\n var intervalID = setInterval(function() {{\n try {{\n if({variable}) {{\n clearInterval(intervalID);\n removeEventListener("beforeunload", unloadHandler);\n removeEventListener("unload", unloadHandler);\n callback(true);\n }}\n }} catch (e) {{}}\n }}, 10);\n '.format(variable=variable) for _ in range(5): try: result = world.browser.driver.execute_async_script(dedent(javascript)) except WebDriverException as wde: if ('document unloaded while waiting for result' in wde.msg): result = 'unload' else: raise if (result == 'unload'): world.wait(1) continue else: return result
null
null
null
seleniums execute_async_script function
codeqa
@world absorbdef wait for js variable truthy variable javascript '\nvarcallback arguments[arguments length- 1 ] \nvarunload Handler function {{\ncallback "unload" \n}}\nadd Event Listener "beforeunload" unload Handler \nadd Event Listener "unload" unload Handler \nvarinterval ID set Interval function {{\ntry{{\nif {variable} {{\nclear Interval interval ID \nremove Event Listener "beforeunload" unload Handler \nremove Event Listener "unload" unload Handler \ncallback true \n}}\n}}catch e {{}}\n}} 10 \n' format variable variable for in range 5 try result world browser driver execute async script dedent javascript except Web Driver Exception as wde if 'documentunloadedwhilewaitingforresult' in wde msg result 'unload'else raiseif result 'unload' world wait 1 continueelse return result
null
null
null
null
Question: What does the code use ? Code: @world.absorb def wait_for_js_variable_truthy(variable): javascript = '\n var callback = arguments[arguments.length - 1];\n var unloadHandler = function() {{\n callback("unload");\n }}\n addEventListener("beforeunload", unloadHandler);\n addEventListener("unload", unloadHandler);\n var intervalID = setInterval(function() {{\n try {{\n if({variable}) {{\n clearInterval(intervalID);\n removeEventListener("beforeunload", unloadHandler);\n removeEventListener("unload", unloadHandler);\n callback(true);\n }}\n }} catch (e) {{}}\n }}, 10);\n '.format(variable=variable) for _ in range(5): try: result = world.browser.driver.execute_async_script(dedent(javascript)) except WebDriverException as wde: if ('document unloaded while waiting for result' in wde.msg): result = 'unload' else: raise if (result == 'unload'): world.wait(1) continue else: return result
null
null
null
What does the code create ?
def create_node(args): node = query(method='droplets', args=args, http_method='post') return node
null
null
null
a node
codeqa
def create node args node query method 'droplets' args args http method 'post' return node
null
null
null
null
Question: What does the code create ? Code: def create_node(args): node = query(method='droplets', args=args, http_method='post') return node
null
null
null
What did temporary files use ?
def _clean_up_temporary_files(dataset_dir): filename = _DATA_URL.split('/')[(-1)] filepath = os.path.join(dataset_dir, filename) tf.gfile.Remove(filepath) tmp_dir = os.path.join(dataset_dir, 'cifar-10-batches-py') tf.gfile.DeleteRecursively(tmp_dir)
null
null
null
to create the dataset
codeqa
def clean up temporary files dataset dir filename DATA URL split '/' [ -1 ]filepath os path join dataset dir filename tf gfile Remove filepath tmp dir os path join dataset dir 'cifar- 10 -batches-py' tf gfile Delete Recursively tmp dir
null
null
null
null
Question: What did temporary files use ? Code: def _clean_up_temporary_files(dataset_dir): filename = _DATA_URL.split('/')[(-1)] filepath = os.path.join(dataset_dir, filename) tf.gfile.Remove(filepath) tmp_dir = os.path.join(dataset_dir, 'cifar-10-batches-py') tf.gfile.DeleteRecursively(tmp_dir)
null
null
null
What used to create the dataset ?
def _clean_up_temporary_files(dataset_dir): filename = _DATA_URL.split('/')[(-1)] filepath = os.path.join(dataset_dir, filename) tf.gfile.Remove(filepath) tmp_dir = os.path.join(dataset_dir, 'cifar-10-batches-py') tf.gfile.DeleteRecursively(tmp_dir)
null
null
null
temporary files
codeqa
def clean up temporary files dataset dir filename DATA URL split '/' [ -1 ]filepath os path join dataset dir filename tf gfile Remove filepath tmp dir os path join dataset dir 'cifar- 10 -batches-py' tf gfile Delete Recursively tmp dir
null
null
null
null
Question: What used to create the dataset ? Code: def _clean_up_temporary_files(dataset_dir): filename = _DATA_URL.split('/')[(-1)] filepath = os.path.join(dataset_dir, filename) tf.gfile.Remove(filepath) tmp_dir = os.path.join(dataset_dir, 'cifar-10-batches-py') tf.gfile.DeleteRecursively(tmp_dir)
null
null
null
What does the code find ?
def _runscript(scriptname, sandbox=False): namespace = {'__name__': '__main__'} namespace['sys'] = globals()['sys'] try: pkg_resources.get_distribution('khmer').run_script(scriptname, namespace) return 0 except pkg_resources.ResolutionError: pass if sandbox: path = os.path.join(os.path.dirname(__file__), '../sandbox') else: path = scriptpath() scriptfile = os.path.join(path, scriptname) if os.path.isfile(scriptfile): if os.path.isfile(scriptfile): exec compile(open(scriptfile).read(), scriptfile, 'exec') in namespace return 0 elif sandbox: pytest.skip('sandbox tests are only run in a repository.') return (-1)
null
null
null
a script with exec
codeqa
def runscript scriptname sandbox False namespace {' name ' ' main '}namespace['sys'] globals ['sys']try pkg resources get distribution 'khmer' run script scriptname namespace return 0except pkg resources Resolution Error passif sandbox path os path join os path dirname file ' /sandbox' else path scriptpath scriptfile os path join path scriptname if os path isfile scriptfile if os path isfile scriptfile exec compile open scriptfile read scriptfile 'exec' in namespacereturn 0elif sandbox pytest skip 'sandboxtestsareonlyruninarepository ' return -1
null
null
null
null
Question: What does the code find ? Code: def _runscript(scriptname, sandbox=False): namespace = {'__name__': '__main__'} namespace['sys'] = globals()['sys'] try: pkg_resources.get_distribution('khmer').run_script(scriptname, namespace) return 0 except pkg_resources.ResolutionError: pass if sandbox: path = os.path.join(os.path.dirname(__file__), '../sandbox') else: path = scriptpath() scriptfile = os.path.join(path, scriptname) if os.path.isfile(scriptfile): if os.path.isfile(scriptfile): exec compile(open(scriptfile).read(), scriptfile, 'exec') in namespace return 0 elif sandbox: pytest.skip('sandbox tests are only run in a repository.') return (-1)
null
null
null
How do a config value change ?
@contextlib.contextmanager def changed_config(key, value): _original_config = config.copy() config[key] = value try: (yield) finally: config.clear() config.update(_original_config)
null
null
null
temporarily
codeqa
@contextlib contextmanagerdef changed config key value original config config copy config[key] valuetry yield finally config clear config update original config
null
null
null
null
Question: How do a config value change ? Code: @contextlib.contextmanager def changed_config(key, value): _original_config = config.copy() config[key] = value try: (yield) finally: config.clear() config.update(_original_config)
null
null
null
What does the code get from settings ?
def _get_spider_loader(settings): if settings.get('SPIDER_MANAGER_CLASS'): warnings.warn('SPIDER_MANAGER_CLASS option is deprecated. Please use SPIDER_LOADER_CLASS.', category=ScrapyDeprecationWarning, stacklevel=2) cls_path = settings.get('SPIDER_MANAGER_CLASS', settings.get('SPIDER_LOADER_CLASS')) loader_cls = load_object(cls_path) try: verifyClass(ISpiderLoader, loader_cls) except DoesNotImplement: warnings.warn('SPIDER_LOADER_CLASS (previously named SPIDER_MANAGER_CLASS) does not fully implement scrapy.interfaces.ISpiderLoader interface. Please add all missing methods to avoid unexpected runtime errors.', category=ScrapyDeprecationWarning, stacklevel=2) return loader_cls.from_settings(settings.frozencopy())
null
null
null
spiderloader instance
codeqa
def get spider loader settings if settings get 'SPIDER MANAGER CLASS' warnings warn 'SPIDER MANAGER CLAS Soptionisdeprecated Pleaseuse SPIDER LOADER CLASS ' category Scrapy Deprecation Warning stacklevel 2 cls path settings get 'SPIDER MANAGER CLASS' settings get 'SPIDER LOADER CLASS' loader cls load object cls path try verify Class I Spider Loader loader cls except Does Not Implement warnings warn 'SPIDER LOADER CLASS previouslynamed SPIDER MANAGER CLASS doesnotfullyimplementscrapy interfaces I Spider Loaderinterface Pleaseaddallmissingmethodstoavoidunexpectedruntimeerrors ' category Scrapy Deprecation Warning stacklevel 2 return loader cls from settings settings frozencopy
null
null
null
null
Question: What does the code get from settings ? Code: def _get_spider_loader(settings): if settings.get('SPIDER_MANAGER_CLASS'): warnings.warn('SPIDER_MANAGER_CLASS option is deprecated. Please use SPIDER_LOADER_CLASS.', category=ScrapyDeprecationWarning, stacklevel=2) cls_path = settings.get('SPIDER_MANAGER_CLASS', settings.get('SPIDER_LOADER_CLASS')) loader_cls = load_object(cls_path) try: verifyClass(ISpiderLoader, loader_cls) except DoesNotImplement: warnings.warn('SPIDER_LOADER_CLASS (previously named SPIDER_MANAGER_CLASS) does not fully implement scrapy.interfaces.ISpiderLoader interface. Please add all missing methods to avoid unexpected runtime errors.', category=ScrapyDeprecationWarning, stacklevel=2) return loader_cls.from_settings(settings.frozencopy())
null
null
null
What does the system understand ?
def validate_encoding(encoding): try: codecs.lookup(encoding) return True except LookupError: return False
null
null
null
this encoding
codeqa
def validate encoding encoding try codecs lookup encoding return Trueexcept Lookup Error return False
null
null
null
null
Question: What does the system understand ? Code: def validate_encoding(encoding): try: codecs.lookup(encoding) return True except LookupError: return False
null
null
null
What understands this encoding ?
def validate_encoding(encoding): try: codecs.lookup(encoding) return True except LookupError: return False
null
null
null
the system
codeqa
def validate encoding encoding try codecs lookup encoding return Trueexcept Lookup Error return False
null
null
null
null
Question: What understands this encoding ? Code: def validate_encoding(encoding): try: codecs.lookup(encoding) return True except LookupError: return False
null
null
null
What does the code get ?
def getLoopLength(polygon): polygonLength = 0.0 for pointIndex in xrange(len(polygon)): point = polygon[pointIndex] secondPoint = polygon[((pointIndex + 1) % len(polygon))] polygonLength += abs((point - secondPoint)) return polygonLength
null
null
null
the length of a polygon perimeter
codeqa
def get Loop Length polygon polygon Length 0 0for point Index in xrange len polygon point polygon[point Index]second Point polygon[ point Index + 1 % len polygon ]polygon Length + abs point - second Point return polygon Length
null
null
null
null
Question: What does the code get ? Code: def getLoopLength(polygon): polygonLength = 0.0 for pointIndex in xrange(len(polygon)): point = polygon[pointIndex] secondPoint = polygon[((pointIndex + 1) % len(polygon))] polygonLength += abs((point - secondPoint)) return polygonLength
null
null
null
What does this function determine ?
def __virtual__(): if (not HAS_VBOX): return (False, "The virtualbox driver cannot be loaded: 'vboxapi' is not installed.") if (get_configured_provider() is False): return (False, "The virtualbox driver cannot be loaded: 'virtualbox' provider is not configured.") return __virtualname__
null
null
null
whether or not to make this cloud module available upon execution
codeqa
def virtual if not HAS VBOX return False " Thevirtualboxdrivercannotbeloaded 'vboxapi'isnotinstalled " if get configured provider is False return False " Thevirtualboxdrivercannotbeloaded 'virtualbox'providerisnotconfigured " return virtualname
null
null
null
null
Question: What does this function determine ? Code: def __virtual__(): if (not HAS_VBOX): return (False, "The virtualbox driver cannot be loaded: 'vboxapi' is not installed.") if (get_configured_provider() is False): return (False, "The virtualbox driver cannot be loaded: 'virtualbox' provider is not configured.") return __virtualname__
null
null
null
How do so say ?
def forward_drop(): run(settings.iptables, '-P', 'FORWARD', 'DROP')
null
null
null
explicitly
codeqa
def forward drop run settings iptables '-P' 'FORWARD' 'DROP'
null
null
null
null
Question: How do so say ? Code: def forward_drop(): run(settings.iptables, '-P', 'FORWARD', 'DROP')
null
null
null
What does an asset not have ?
def ConstructAssetId(id_prefix, device_id, uniquifier): assert IdPrefix.IsValid(id_prefix), id_prefix byte_str = util.EncodeVarLengthNumber(device_id) byte_str += _EncodeUniquifier(uniquifier) return (id_prefix + base64hex.B64HexEncode(byte_str, padding=False))
null
null
null
a timestamp part
codeqa
def Construct Asset Id id prefix device id uniquifier assert Id Prefix Is Valid id prefix id prefixbyte str util Encode Var Length Number device id byte str + Encode Uniquifier uniquifier return id prefix + base 64 hex B64 Hex Encode byte str padding False
null
null
null
null
Question: What does an asset not have ? Code: def ConstructAssetId(id_prefix, device_id, uniquifier): assert IdPrefix.IsValid(id_prefix), id_prefix byte_str = util.EncodeVarLengthNumber(device_id) byte_str += _EncodeUniquifier(uniquifier) return (id_prefix + base64hex.B64HexEncode(byte_str, padding=False))
null
null
null
Does an asset have a timestamp part ?
def ConstructAssetId(id_prefix, device_id, uniquifier): assert IdPrefix.IsValid(id_prefix), id_prefix byte_str = util.EncodeVarLengthNumber(device_id) byte_str += _EncodeUniquifier(uniquifier) return (id_prefix + base64hex.B64HexEncode(byte_str, padding=False))
null
null
null
No
codeqa
def Construct Asset Id id prefix device id uniquifier assert Id Prefix Is Valid id prefix id prefixbyte str util Encode Var Length Number device id byte str + Encode Uniquifier uniquifier return id prefix + base 64 hex B64 Hex Encode byte str padding False
null
null
null
null
Question: Does an asset have a timestamp part ? Code: def ConstructAssetId(id_prefix, device_id, uniquifier): assert IdPrefix.IsValid(id_prefix), id_prefix byte_str = util.EncodeVarLengthNumber(device_id) byte_str += _EncodeUniquifier(uniquifier) return (id_prefix + base64hex.B64HexEncode(byte_str, padding=False))
null
null
null
What does not have a timestamp part ?
def ConstructAssetId(id_prefix, device_id, uniquifier): assert IdPrefix.IsValid(id_prefix), id_prefix byte_str = util.EncodeVarLengthNumber(device_id) byte_str += _EncodeUniquifier(uniquifier) return (id_prefix + base64hex.B64HexEncode(byte_str, padding=False))
null
null
null
an asset
codeqa
def Construct Asset Id id prefix device id uniquifier assert Id Prefix Is Valid id prefix id prefixbyte str util Encode Var Length Number device id byte str + Encode Uniquifier uniquifier return id prefix + base 64 hex B64 Hex Encode byte str padding False
null
null
null
null
Question: What does not have a timestamp part ? Code: def ConstructAssetId(id_prefix, device_id, uniquifier): assert IdPrefix.IsValid(id_prefix), id_prefix byte_str = util.EncodeVarLengthNumber(device_id) byte_str += _EncodeUniquifier(uniquifier) return (id_prefix + base64hex.B64HexEncode(byte_str, padding=False))
null
null
null
What does the code extract from reads to sample_ids from split_libraries ?
def extract_read_to_sample_mapping(labels): sample_id_mapping = {} re = compile('(\\S+) (\\S+)') for label in labels: tmatch = search(re, label) sample_id = tmatch.group(1) flowgram_id = tmatch.group(2) sample_id_mapping[flowgram_id] = sample_id return sample_id_mapping
null
null
null
a mapping
codeqa
def extract read to sample mapping labels sample id mapping {}re compile ' \\S+ \\S+ ' for label in labels tmatch search re label sample id tmatch group 1 flowgram id tmatch group 2 sample id mapping[flowgram id] sample idreturn sample id mapping
null
null
null
null
Question: What does the code extract from reads to sample_ids from split_libraries ? Code: def extract_read_to_sample_mapping(labels): sample_id_mapping = {} re = compile('(\\S+) (\\S+)') for label in labels: tmatch = search(re, label) sample_id = tmatch.group(1) flowgram_id = tmatch.group(2) sample_id_mapping[flowgram_id] = sample_id return sample_id_mapping