labNo float64 1 10 ⌀ | taskNo float64 0 4 ⌀ | questioner stringclasses 2
values | question stringlengths 9 201 | code stringlengths 18 30.3k | startLine float64 0 192 ⌀ | endLine float64 0 196 ⌀ | questionType stringclasses 4
values | answer stringlengths 2 905 | src stringclasses 3
values | code_processed stringlengths 12 28.3k ⌀ | id stringlengths 2 5 ⌀ | raw_code stringlengths 20 30.3k ⌀ | raw_comment stringlengths 10 242 ⌀ | comment stringlengths 9 207 ⌀ | q_code stringlengths 66 30.3k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
null | null | null | What is executing in a shell ?
| def getstatusoutput(cmd):
import os
pipe = os.popen((('{ ' + cmd) + '; } 2>&1'), 'r')
text = pipe.read()
sts = pipe.close()
if (sts is None):
sts = 0
if (text[(-1):] == '\n'):
text = text[:(-1)]
return (sts, text)
| null | null | null | cmd
| codeqa | def getstatusoutput cmd import ospipe os popen '{' + cmd + ' }2 >& 1 ' 'r' text pipe read sts pipe close if sts is None sts 0if text[ -1 ] '\n' text text[ -1 ]return sts text
| null | null | null | null | Question:
What is executing in a shell ?
Code:
def getstatusoutput(cmd):
import os
pipe = os.popen((('{ ' + cmd) + '; } 2>&1'), 'r')
text = pipe.read()
sts = pipe.close()
if (sts is None):
sts = 0
if (text[(-1):] == '\n'):
text = text[:(-1)]
return (sts, text)
|
null | null | null | Where do cmd execute ?
| def getstatusoutput(cmd):
import os
pipe = os.popen((('{ ' + cmd) + '; } 2>&1'), 'r')
text = pipe.read()
sts = pipe.close()
if (sts is None):
sts = 0
if (text[(-1):] == '\n'):
text = text[:(-1)]
return (sts, text)
| null | null | null | in a shell
| codeqa | def getstatusoutput cmd import ospipe os popen '{' + cmd + ' }2 >& 1 ' 'r' text pipe read sts pipe close if sts is None sts 0if text[ -1 ] '\n' text text[ -1 ]return sts text
| null | null | null | null | Question:
Where do cmd execute ?
Code:
def getstatusoutput(cmd):
import os
pipe = os.popen((('{ ' + cmd) + '; } 2>&1'), 'r')
text = pipe.read()
sts = pipe.close()
if (sts is None):
sts = 0
if (text[(-1):] == '\n'):
text = text[:(-1)]
return (sts, text)
|
null | null | null | What does the code verify ?
| def _should_validate_sub_attributes(attribute, sub_attr):
validate = attribute.get('validate')
return (validate and isinstance(sub_attr, collections.Iterable) and any([(k.startswith('type:dict') and v) for (k, v) in six.iteritems(validate)]))
| null | null | null | that sub - attributes are iterable and should be validated
| codeqa | def should validate sub attributes attribute sub attr validate attribute get 'validate' return validate and isinstance sub attr collections Iterable and any [ k startswith 'type dict' and v for k v in six iteritems validate ]
| null | null | null | null | Question:
What does the code verify ?
Code:
def _should_validate_sub_attributes(attribute, sub_attr):
validate = attribute.get('validate')
return (validate and isinstance(sub_attr, collections.Iterable) and any([(k.startswith('type:dict') and v) for (k, v) in six.iteritems(validate)]))
|
null | null | null | How does a sequence of objects filter ?
| @contextfilter
def do_selectattr(*args, **kwargs):
return select_or_reject(args, kwargs, (lambda x: x), True)
| null | null | null | by applying a test to the specified attribute of each object
| codeqa | @contextfilterdef do selectattr *args **kwargs return select or reject args kwargs lambda x x True
| null | null | null | null | Question:
How does a sequence of objects filter ?
Code:
@contextfilter
def do_selectattr(*args, **kwargs):
return select_or_reject(args, kwargs, (lambda x: x), True)
|
null | null | null | What do we have only from somewhere in the tree the full path ?
| def find_full_path(path_to_file):
for (subdir, dirs, files) in os.walk('.'):
full = os.path.relpath(os.path.join(subdir, path_to_file))
if os.path.exists(full):
return full
| null | null | null | a relative path
| codeqa | def find full path path to file for subdir dirs files in os walk ' ' full os path relpath os path join subdir path to file if os path exists full return full
| null | null | null | null | Question:
What do we have only from somewhere in the tree the full path ?
Code:
def find_full_path(path_to_file):
for (subdir, dirs, files) in os.walk('.'):
full = os.path.relpath(os.path.join(subdir, path_to_file))
if os.path.exists(full):
return full
|
null | null | null | Where do we have a relative path only from somewhere in the tree ?
| def find_full_path(path_to_file):
for (subdir, dirs, files) in os.walk('.'):
full = os.path.relpath(os.path.join(subdir, path_to_file))
if os.path.exists(full):
return full
| null | null | null | the full path
| codeqa | def find full path path to file for subdir dirs files in os walk ' ' full os path relpath os path join subdir path to file if os path exists full return full
| null | null | null | null | Question:
Where do we have a relative path only from somewhere in the tree ?
Code:
def find_full_path(path_to_file):
for (subdir, dirs, files) in os.walk('.'):
full = os.path.relpath(os.path.join(subdir, path_to_file))
if os.path.exists(full):
return full
|
null | null | null | What do path contain ?
| def is_conflict_free(path):
rgx = re.compile(u'^(<<<<<<<|\\|\\|\\|\\|\\|\\|\\||>>>>>>>) ')
try:
with core.xopen(path, u'r') as f:
for line in f:
line = core.decode(line, errors=u'ignore')
if rgx.match(line):
if should_stage_conflicts(path):
return True
else:
return False
except IO... | null | null | null | no conflict markers
| codeqa | def is conflict free path rgx re compile u'^ <<<<<<< \\ \\ \\ \\ \\ \\ \\ >>>>>>> ' try with core xopen path u'r' as f for line in f line core decode line errors u'ignore' if rgx match line if should stage conflicts path return Trueelse return Falseexcept IO Error passreturn True
| null | null | null | null | Question:
What do path contain ?
Code:
def is_conflict_free(path):
rgx = re.compile(u'^(<<<<<<<|\\|\\|\\|\\|\\|\\|\\||>>>>>>>) ')
try:
with core.xopen(path, u'r') as f:
for line in f:
line = core.decode(line, errors=u'ignore')
if rgx.match(line):
if should_stage_conflicts(path):
return Tr... |
null | null | null | What contains no conflict markers ?
| def is_conflict_free(path):
rgx = re.compile(u'^(<<<<<<<|\\|\\|\\|\\|\\|\\|\\||>>>>>>>) ')
try:
with core.xopen(path, u'r') as f:
for line in f:
line = core.decode(line, errors=u'ignore')
if rgx.match(line):
if should_stage_conflicts(path):
return True
else:
return False
except IO... | null | null | null | path
| codeqa | def is conflict free path rgx re compile u'^ <<<<<<< \\ \\ \\ \\ \\ \\ \\ >>>>>>> ' try with core xopen path u'r' as f for line in f line core decode line errors u'ignore' if rgx match line if should stage conflicts path return Trueelse return Falseexcept IO Error passreturn True
| null | null | null | null | Question:
What contains no conflict markers ?
Code:
def is_conflict_free(path):
rgx = re.compile(u'^(<<<<<<<|\\|\\|\\|\\|\\|\\|\\||>>>>>>>) ')
try:
with core.xopen(path, u'r') as f:
for line in f:
line = core.decode(line, errors=u'ignore')
if rgx.match(line):
if should_stage_conflicts(path):
... |
null | null | null | What see the issue ?
| def test_matrices_with_C_F_orders():
P_C = np.array([[0.5, 0.5], [0, 1]], order='C')
P_F = np.array([[0.5, 0.5], [0, 1]], order='F')
stationary_dist = [0.0, 1.0]
computed_C_and_F = gth_solve(np.array([[1]]))
assert_array_equal(computed_C_and_F, [1])
computed_C = gth_solve(P_C)
computed_F = gth_solve(P_F)
assert... | null | null | null | test matrices with c- and f - contiguous orders
| codeqa | def test matrices with C F orders P C np array [[ 0 5 0 5] [0 1]] order 'C' P F np array [[ 0 5 0 5] [0 1]] order 'F' stationary dist [0 0 1 0]computed C and F gth solve np array [[ 1 ]] assert array equal computed C and F [1 ] computed C gth solve P C computed F gth solve P F assert array equal computed C stationary d... | null | null | null | null | Question:
What see the issue ?
Code:
def test_matrices_with_C_F_orders():
P_C = np.array([[0.5, 0.5], [0, 1]], order='C')
P_F = np.array([[0.5, 0.5], [0, 1]], order='F')
stationary_dist = [0.0, 1.0]
computed_C_and_F = gth_solve(np.array([[1]]))
assert_array_equal(computed_C_and_F, [1])
computed_C = gth_solve(... |
null | null | null | What do test matrices with c- and f - contiguous orders see ?
| def test_matrices_with_C_F_orders():
P_C = np.array([[0.5, 0.5], [0, 1]], order='C')
P_F = np.array([[0.5, 0.5], [0, 1]], order='F')
stationary_dist = [0.0, 1.0]
computed_C_and_F = gth_solve(np.array([[1]]))
assert_array_equal(computed_C_and_F, [1])
computed_C = gth_solve(P_C)
computed_F = gth_solve(P_F)
assert... | null | null | null | the issue
| codeqa | def test matrices with C F orders P C np array [[ 0 5 0 5] [0 1]] order 'C' P F np array [[ 0 5 0 5] [0 1]] order 'F' stationary dist [0 0 1 0]computed C and F gth solve np array [[ 1 ]] assert array equal computed C and F [1 ] computed C gth solve P C computed F gth solve P F assert array equal computed C stationary d... | null | null | null | null | Question:
What do test matrices with c- and f - contiguous orders see ?
Code:
def test_matrices_with_C_F_orders():
P_C = np.array([[0.5, 0.5], [0, 1]], order='C')
P_F = np.array([[0.5, 0.5], [0, 1]], order='F')
stationary_dist = [0.0, 1.0]
computed_C_and_F = gth_solve(np.array([[1]]))
assert_array_equal(comput... |
null | null | null | What do runner import ?
| @with_setup(prepare_stderr)
def test_try_to_import_terrain():
sandbox_path = ojoin('..', 'sandbox')
original_path = abspath('.')
os.chdir(sandbox_path)
try:
import lettuce
reload(lettuce)
raise AssertionError('The runner should raise ImportError !')
except LettuceRunnerError:
assert_stderr_lines_with_... | null | null | null | terrain
| codeqa | @with setup prepare stderr def test try to import terrain sandbox path ojoin ' ' 'sandbox' original path abspath ' ' os chdir sandbox path try import lettucereload lettuce raise Assertion Error ' Therunnershouldraise Import Error ' except Lettuce Runner Error assert stderr lines with traceback ' Lettucehastriedtoloadth... | null | null | null | null | Question:
What do runner import ?
Code:
@with_setup(prepare_stderr)
def test_try_to_import_terrain():
sandbox_path = ojoin('..', 'sandbox')
original_path = abspath('.')
os.chdir(sandbox_path)
try:
import lettuce
reload(lettuce)
raise AssertionError('The runner should raise ImportError !')
except Let... |
null | null | null | What imports terrain ?
| @with_setup(prepare_stderr)
def test_try_to_import_terrain():
sandbox_path = ojoin('..', 'sandbox')
original_path = abspath('.')
os.chdir(sandbox_path)
try:
import lettuce
reload(lettuce)
raise AssertionError('The runner should raise ImportError !')
except LettuceRunnerError:
assert_stderr_lines_with_... | null | null | null | runner
| codeqa | @with setup prepare stderr def test try to import terrain sandbox path ojoin ' ' 'sandbox' original path abspath ' ' os chdir sandbox path try import lettucereload lettuce raise Assertion Error ' Therunnershouldraise Import Error ' except Lettuce Runner Error assert stderr lines with traceback ' Lettucehastriedtoloadth... | null | null | null | null | Question:
What imports terrain ?
Code:
@with_setup(prepare_stderr)
def test_try_to_import_terrain():
sandbox_path = ojoin('..', 'sandbox')
original_path = abspath('.')
os.chdir(sandbox_path)
try:
import lettuce
reload(lettuce)
raise AssertionError('The runner should raise ImportError !')
except Lett... |
null | null | null | What creates a file or a directory from a stat response ?
| def CreateAFF4Object(stat_response, client_id, token, sync=False):
stat_response.aff4path = aff4_grr.VFSGRRClient.PathspecToURN(stat_response.pathspec, client_id)
if stat_response.pathspec.last.stream_name:
stat_response.st_mode &= (~ stat_type_mask)
stat_response.st_mode |= stat.S_IFREG
if stat.S_ISDIR(stat_res... | null | null | null | this
| codeqa | def Create AFF 4 Object stat response client id token sync False stat response aff 4 path aff 4 grr VFSGRR Client Pathspec To URN stat response pathspec client id if stat response pathspec last stream name stat response st mode & ~ stat type mask stat response st mode stat S IFRE Gif stat S ISDIR stat response st mode ... | null | null | null | null | Question:
What creates a file or a directory from a stat response ?
Code:
def CreateAFF4Object(stat_response, client_id, token, sync=False):
stat_response.aff4path = aff4_grr.VFSGRRClient.PathspecToURN(stat_response.pathspec, client_id)
if stat_response.pathspec.last.stream_name:
stat_response.st_mode &= (~ sta... |
null | null | null | What does this create from a stat response ?
| def CreateAFF4Object(stat_response, client_id, token, sync=False):
stat_response.aff4path = aff4_grr.VFSGRRClient.PathspecToURN(stat_response.pathspec, client_id)
if stat_response.pathspec.last.stream_name:
stat_response.st_mode &= (~ stat_type_mask)
stat_response.st_mode |= stat.S_IFREG
if stat.S_ISDIR(stat_res... | null | null | null | a file or a directory
| codeqa | def Create AFF 4 Object stat response client id token sync False stat response aff 4 path aff 4 grr VFSGRR Client Pathspec To URN stat response pathspec client id if stat response pathspec last stream name stat response st mode & ~ stat type mask stat response st mode stat S IFRE Gif stat S ISDIR stat response st mode ... | null | null | null | null | Question:
What does this create from a stat response ?
Code:
def CreateAFF4Object(stat_response, client_id, token, sync=False):
stat_response.aff4path = aff4_grr.VFSGRRClient.PathspecToURN(stat_response.pathspec, client_id)
if stat_response.pathspec.last.stream_name:
stat_response.st_mode &= (~ stat_type_mask)
... |
null | null | null | What does the code get from a time object in a particular scale ?
| def get_jd12(time, scale):
if (time.scale == scale):
newtime = time
else:
try:
newtime = getattr(time, scale)
except iers.IERSRangeError as e:
_warn_iers(e)
newtime = time
return (newtime.jd1, newtime.jd2)
| null | null | null | jd1 and jd2
| codeqa | def get jd 12 time scale if time scale scale newtime timeelse try newtime getattr time scale except iers IERS Range Error as e warn iers e newtime timereturn newtime jd 1 newtime jd 2
| null | null | null | null | Question:
What does the code get from a time object in a particular scale ?
Code:
def get_jd12(time, scale):
if (time.scale == scale):
newtime = time
else:
try:
newtime = getattr(time, scale)
except iers.IERSRangeError as e:
_warn_iers(e)
newtime = time
return (newtime.jd1, newtime.jd2)
|
null | null | null | Where does the code get jd1 and jd2 from a time object ?
| def get_jd12(time, scale):
if (time.scale == scale):
newtime = time
else:
try:
newtime = getattr(time, scale)
except iers.IERSRangeError as e:
_warn_iers(e)
newtime = time
return (newtime.jd1, newtime.jd2)
| null | null | null | in a particular scale
| codeqa | def get jd 12 time scale if time scale scale newtime timeelse try newtime getattr time scale except iers IERS Range Error as e warn iers e newtime timereturn newtime jd 1 newtime jd 2
| null | null | null | null | Question:
Where does the code get jd1 and jd2 from a time object ?
Code:
def get_jd12(time, scale):
if (time.scale == scale):
newtime = time
else:
try:
newtime = getattr(time, scale)
except iers.IERSRangeError as e:
_warn_iers(e)
newtime = time
return (newtime.jd1, newtime.jd2)
|
null | null | null | How do an executing test skip ?
| def skip(msg=''):
__tracebackhide__ = True
raise Skipped(msg=msg)
| null | null | null | with the given message
| codeqa | def skip msg '' tracebackhide Trueraise Skipped msg msg
| null | null | null | null | Question:
How do an executing test skip ?
Code:
def skip(msg=''):
__tracebackhide__ = True
raise Skipped(msg=msg)
|
null | null | null | When does code run ?
| def Application_Error(app, e):
pass
| null | null | null | when an unhandled error occurs
| codeqa | def Application Error app e pass
| null | null | null | null | Question:
When does code run ?
Code:
def Application_Error(app, e):
pass
|
null | null | null | For what purpose do the glance metadata return ?
| def volume_snapshot_glance_metadata_get(context, snapshot_id):
return IMPL.volume_snapshot_glance_metadata_get(context, snapshot_id)
| null | null | null | for the specified snapshot
| codeqa | def volume snapshot glance metadata get context snapshot id return IMPL volume snapshot glance metadata get context snapshot id
| null | null | null | null | Question:
For what purpose do the glance metadata return ?
Code:
def volume_snapshot_glance_metadata_get(context, snapshot_id):
return IMPL.volume_snapshot_glance_metadata_get(context, snapshot_id)
|
null | null | null | What does the code render ?
| @login_required
def financial_assistance(_request):
return render_to_response('financial-assistance/financial-assistance.html', {'header_text': FINANCIAL_ASSISTANCE_HEADER})
| null | null | null | the initial financial assistance page
| codeqa | @login requireddef financial assistance request return render to response 'financial-assistance/financial-assistance html' {'header text' FINANCIAL ASSISTANCE HEADER}
| null | null | null | null | Question:
What does the code render ?
Code:
@login_required
def financial_assistance(_request):
return render_to_response('financial-assistance/financial-assistance.html', {'header_text': FINANCIAL_ASSISTANCE_HEADER})
|
null | null | null | What does this function do ?
| def test_linear():
xs = [1, 5, True, None, 'foo']
for x in xs:
assert (x == activations.linear(x))
| null | null | null | no input validation
| codeqa | def test linear xs [1 5 True None 'foo']for x in xs assert x activations linear x
| null | null | null | null | Question:
What does this function do ?
Code:
def test_linear():
xs = [1, 5, True, None, 'foo']
for x in xs:
assert (x == activations.linear(x))
|
null | null | null | What does the code translate ?
| def Target(filename):
return (os.path.splitext(filename)[0] + '.o')
| null | null | null | a compilable filename to its
| codeqa | def Target filename return os path splitext filename [0 ] + ' o'
| null | null | null | null | Question:
What does the code translate ?
Code:
def Target(filename):
return (os.path.splitext(filename)[0] + '.o')
|
null | null | null | How does an application validate ?
| def is_app_name_valid(app_name):
if re.match(VALID_APP_NAME_CHARS_REGEX, app_name):
return True
else:
return False
| null | null | null | by checking if it contains certain characters
| codeqa | def is app name valid app name if re match VALID APP NAME CHARS REGEX app name return Trueelse return False
| null | null | null | null | Question:
How does an application validate ?
Code:
def is_app_name_valid(app_name):
if re.match(VALID_APP_NAME_CHARS_REGEX, app_name):
return True
else:
return False
|
null | null | null | How does the estimated number of syllables in the word return ?
| def _count_syllables(word):
n = 0
p = False
for ch in ((word.endswith('e') and word[:(-1)]) or word):
v = (ch in VOWELS)
n += int((v and (not p)))
p = v
return n
| null | null | null | by counting vowel - groups
| codeqa | def count syllables word n 0p Falsefor ch in word endswith 'e' and word[ -1 ] or word v ch in VOWELS n + int v and not p p vreturn n
| null | null | null | null | Question:
How does the estimated number of syllables in the word return ?
Code:
def _count_syllables(word):
n = 0
p = False
for ch in ((word.endswith('e') and word[:(-1)]) or word):
v = (ch in VOWELS)
n += int((v and (not p)))
p = v
return n
|
null | null | null | What should filters receive only ?
| def stringfilter(func):
def _dec(*args, **kwargs):
if args:
args = list(args)
args[0] = force_text(args[0])
if (isinstance(args[0], SafeData) and getattr(_dec._decorated_function, u'is_safe', False)):
return mark_safe(func(*args, **kwargs))
return func(*args, **kwargs)
_dec._decorated_function = geta... | null | null | null | unicode objects
| codeqa | def stringfilter func def dec *args **kwargs if args args list args args[ 0 ] force text args[ 0 ] if isinstance args[ 0 ] Safe Data and getattr dec decorated function u'is safe' False return mark safe func *args **kwargs return func *args **kwargs dec decorated function getattr func u' decorated function' func return ... | null | null | null | null | Question:
What should filters receive only ?
Code:
def stringfilter(func):
def _dec(*args, **kwargs):
if args:
args = list(args)
args[0] = force_text(args[0])
if (isinstance(args[0], SafeData) and getattr(_dec._decorated_function, u'is_safe', False)):
return mark_safe(func(*args, **kwargs))
return... |
null | null | null | What does the code return ?
| def get_status(dev, recipient=None):
(bmRequestType, wIndex) = _parse_recipient(recipient, util.CTRL_IN)
ret = dev.ctrl_transfer(bmRequestType=bmRequestType, bRequest=0, wIndex=wIndex, data_or_wLength=2)
return (ret[0] | (ret[1] << 8))
| null | null | null | the status for the specified recipient
| codeqa | def get status dev recipient None bm Request Type w Index parse recipient recipient util CTRL IN ret dev ctrl transfer bm Request Type bm Request Type b Request 0 w Index w Index data or w Length 2 return ret[ 0 ] ret[ 1 ] << 8
| null | null | null | null | Question:
What does the code return ?
Code:
def get_status(dev, recipient=None):
(bmRequestType, wIndex) = _parse_recipient(recipient, util.CTRL_IN)
ret = dev.ctrl_transfer(bmRequestType=bmRequestType, bRequest=0, wIndex=wIndex, data_or_wLength=2)
return (ret[0] | (ret[1] << 8))
|
null | null | null | What normalizes in the given domain ?
| def dup_normal(f, K):
return dup_strip([K.normal(c) for c in f])
| null | null | null | univariate polynomial
| codeqa | def dup normal f K return dup strip [K normal c for c in f]
| null | null | null | null | Question:
What normalizes in the given domain ?
Code:
def dup_normal(f, K):
return dup_strip([K.normal(c) for c in f])
|
null | null | null | Where do univariate polynomial normalize ?
| def dup_normal(f, K):
return dup_strip([K.normal(c) for c in f])
| null | null | null | in the given domain
| codeqa | def dup normal f K return dup strip [K normal c for c in f]
| null | null | null | null | Question:
Where do univariate polynomial normalize ?
Code:
def dup_normal(f, K):
return dup_strip([K.normal(c) for c in f])
|
null | null | null | What does the code get ?
| def _get_raw_path(src, dst):
if (len(path_map) == 0):
_calc_paths()
if (src is dst):
return []
if (path_map[src][dst][0] is None):
return None
intermediate = path_map[src][dst][1]
if (intermediate is None):
return []
return ((_get_raw_path(src, intermediate) + [intermediate]) + _get_raw_path(intermediate,... | null | null | null | a raw path
| codeqa | def get raw path src dst if len path map 0 calc paths if src is dst return []if path map[src][dst][ 0 ] is None return Noneintermediate path map[src][dst][ 1 ]if intermediate is None return []return get raw path src intermediate + [intermediate] + get raw path intermediate dst
| null | null | null | null | Question:
What does the code get ?
Code:
def _get_raw_path(src, dst):
if (len(path_map) == 0):
_calc_paths()
if (src is dst):
return []
if (path_map[src][dst][0] is None):
return None
intermediate = path_map[src][dst][1]
if (intermediate is None):
return []
return ((_get_raw_path(src, intermediate) + ... |
null | null | null | How do a wheel uninstall ?
| def test_uninstall_wheel(script, data):
package = data.packages.join('simple.dist-0.1-py2.py3-none-any.whl')
result = script.pip('install', package, '--no-index')
dist_info_folder = (script.site_packages / 'simple.dist-0.1.dist-info')
assert (dist_info_folder in result.files_created)
result2 = script.pip('uninstal... | null | null | null | test
| codeqa | def test uninstall wheel script data package data packages join 'simple dist- 0 1-py 2 py 3 -none-any whl' result script pip 'install' package '--no-index' dist info folder script site packages / 'simple dist- 0 1 dist-info' assert dist info folder in result files created result 2 script pip 'uninstall' 'simple dist' '... | null | null | null | null | Question:
How do a wheel uninstall ?
Code:
def test_uninstall_wheel(script, data):
package = data.packages.join('simple.dist-0.1-py2.py3-none-any.whl')
result = script.pip('install', package, '--no-index')
dist_info_folder = (script.site_packages / 'simple.dist-0.1.dist-info')
assert (dist_info_folder in result... |
null | null | null | What does the code write ?
| def write_file(name, text, opts):
if opts.dryrun:
return
fname = os.path.join(opts.destdir, ('%s.%s' % (name, opts.suffix)))
if ((not opts.force) and os.path.isfile(fname)):
print ('File %s already exists, skipping.' % fname)
else:
print ('Creating file %s.' % fname)
f = open(fname, 'w')
f.write(tex... | null | null | null | the output file for module / package < name >
| codeqa | def write file name text opts if opts dryrun returnfname os path join opts destdir '%s %s' % name opts suffix if not opts force and os path isfile fname print ' File%salreadyexists skipping ' % fname else print ' Creatingfile%s ' % fname f open fname 'w' f write text f close
| null | null | null | null | Question:
What does the code write ?
Code:
def write_file(name, text, opts):
if opts.dryrun:
return
fname = os.path.join(opts.destdir, ('%s.%s' % (name, opts.suffix)))
if ((not opts.force) and os.path.isfile(fname)):
print ('File %s already exists, skipping.' % fname)
else:
print ('Creating file %s.... |
null | null | null | What does the code ensure ?
| def resource_op_defaults_to(name, op_default, value, extra_args=None, cibname=None):
return _item_present(name=name, item='resource', item_id='{0}={1}'.format(op_default, value), item_type=None, show=['op', 'defaults'], create=['op', 'defaults'], extra_args=extra_args, cibname=cibname)
| null | null | null | a resource operation default in the cluster is set to a given value should be run on one cluster node
| codeqa | def resource op defaults to name op default value extra args None cibname None return item present name name item 'resource' item id '{ 0 } {1 }' format op default value item type None show ['op' 'defaults'] create ['op' 'defaults'] extra args extra args cibname cibname
| null | null | null | null | Question:
What does the code ensure ?
Code:
def resource_op_defaults_to(name, op_default, value, extra_args=None, cibname=None):
return _item_present(name=name, item='resource', item_id='{0}={1}'.format(op_default, value), item_type=None, show=['op', 'defaults'], create=['op', 'defaults'], extra_args=extra_args, c... |
null | null | null | What should be run on one cluster node ?
| def resource_op_defaults_to(name, op_default, value, extra_args=None, cibname=None):
return _item_present(name=name, item='resource', item_id='{0}={1}'.format(op_default, value), item_type=None, show=['op', 'defaults'], create=['op', 'defaults'], extra_args=extra_args, cibname=cibname)
| null | null | null | a resource operation default in the cluster is set to a given value
| codeqa | def resource op defaults to name op default value extra args None cibname None return item present name name item 'resource' item id '{ 0 } {1 }' format op default value item type None show ['op' 'defaults'] create ['op' 'defaults'] extra args extra args cibname cibname
| null | null | null | null | Question:
What should be run on one cluster node ?
Code:
def resource_op_defaults_to(name, op_default, value, extra_args=None, cibname=None):
return _item_present(name=name, item='resource', item_id='{0}={1}'.format(op_default, value), item_type=None, show=['op', 'defaults'], create=['op', 'defaults'], extra_args=... |
null | null | null | Where should a resource operation default in the cluster is set to a given value be run ?
| def resource_op_defaults_to(name, op_default, value, extra_args=None, cibname=None):
return _item_present(name=name, item='resource', item_id='{0}={1}'.format(op_default, value), item_type=None, show=['op', 'defaults'], create=['op', 'defaults'], extra_args=extra_args, cibname=cibname)
| null | null | null | on one cluster node
| codeqa | def resource op defaults to name op default value extra args None cibname None return item present name name item 'resource' item id '{ 0 } {1 }' format op default value item type None show ['op' 'defaults'] create ['op' 'defaults'] extra args extra args cibname cibname
| null | null | null | null | Question:
Where should a resource operation default in the cluster is set to a given value be run ?
Code:
def resource_op_defaults_to(name, op_default, value, extra_args=None, cibname=None):
return _item_present(name=name, item='resource', item_id='{0}={1}'.format(op_default, value), item_type=None, show=['op', 'd... |
null | null | null | When did event source add ?
| def ReportEvent(appName, eventID, eventCategory=0, eventType=win32evtlog.EVENTLOG_ERROR_TYPE, strings=None, data=None, sid=None):
hAppLog = win32evtlog.RegisterEventSource(None, appName)
win32evtlog.ReportEvent(hAppLog, eventType, eventCategory, eventID, sid, strings, data)
win32evtlog.DeregisterEventSource(hAppLog)... | null | null | null | previously
| codeqa | def Report Event app Name event ID event Category 0 event Type win 32 evtlog EVENTLOG ERROR TYPE strings None data None sid None h App Log win 32 evtlog Register Event Source None app Name win 32 evtlog Report Event h App Log event Type event Category event ID sid strings data win 32 evtlog Deregister Event Source h Ap... | null | null | null | null | Question:
When did event source add ?
Code:
def ReportEvent(appName, eventID, eventCategory=0, eventType=win32evtlog.EVENTLOG_ERROR_TYPE, strings=None, data=None, sid=None):
hAppLog = win32evtlog.RegisterEventSource(None, appName)
win32evtlog.ReportEvent(hAppLog, eventType, eventCategory, eventID, sid, strings, d... |
null | null | null | What does the code draw around the faces ?
| def highlight_faces(image, faces, output_filename):
im = Image.open(image)
draw = ImageDraw.Draw(im)
for face in faces:
box = [(v.get('x', 0.0), v.get('y', 0.0)) for v in face['fdBoundingPoly']['vertices']]
draw.line((box + [box[0]]), width=5, fill='#00ff00')
im.save(output_filename)
| null | null | null | a polygon
| codeqa | def highlight faces image faces output filename im Image open image draw Image Draw Draw im for face in faces box [ v get 'x' 0 0 v get 'y' 0 0 for v in face['fd Bounding Poly']['vertices']]draw line box + [box[ 0 ]] width 5 fill '# 00 ff 00 ' im save output filename
| null | null | null | null | Question:
What does the code draw around the faces ?
Code:
def highlight_faces(image, faces, output_filename):
im = Image.open(image)
draw = ImageDraw.Draw(im)
for face in faces:
box = [(v.get('x', 0.0), v.get('y', 0.0)) for v in face['fdBoundingPoly']['vertices']]
draw.line((box + [box[0]]), width=5, fill='... |
null | null | null | Where does the code draw a polygon ?
| def highlight_faces(image, faces, output_filename):
im = Image.open(image)
draw = ImageDraw.Draw(im)
for face in faces:
box = [(v.get('x', 0.0), v.get('y', 0.0)) for v in face['fdBoundingPoly']['vertices']]
draw.line((box + [box[0]]), width=5, fill='#00ff00')
im.save(output_filename)
| null | null | null | around the faces
| codeqa | def highlight faces image faces output filename im Image open image draw Image Draw Draw im for face in faces box [ v get 'x' 0 0 v get 'y' 0 0 for v in face['fd Bounding Poly']['vertices']]draw line box + [box[ 0 ]] width 5 fill '# 00 ff 00 ' im save output filename
| null | null | null | null | Question:
Where does the code draw a polygon ?
Code:
def highlight_faces(image, faces, output_filename):
im = Image.open(image)
draw = ImageDraw.Draw(im)
for face in faces:
box = [(v.get('x', 0.0), v.get('y', 0.0)) for v in face['fdBoundingPoly']['vertices']]
draw.line((box + [box[0]]), width=5, fill='#00ff0... |
null | null | null | What is specifying a host and port ?
| def decodeHostPort(line):
abcdef = re.sub('[^0-9, ]', '', line)
parsed = [int(p.strip()) for p in abcdef.split(',')]
for x in parsed:
if ((x < 0) or (x > 255)):
raise ValueError('Out of range', line, x)
(a, b, c, d, e, f) = parsed
host = ('%s.%s.%s.%s' % (a, b, c, d))
port = ((int(e) << 8) + int(f))
retu... | null | null | null | an ftp response
| codeqa | def decode Host Port line abcdef re sub '[^ 0 - 9 ]' '' line parsed [int p strip for p in abcdef split ' ' ]for x in parsed if x < 0 or x > 255 raise Value Error ' Outofrange' line x a b c d e f parsedhost '%s %s %s %s' % a b c d port int e << 8 + int f return host port
| null | null | null | null | Question:
What is specifying a host and port ?
Code:
def decodeHostPort(line):
abcdef = re.sub('[^0-9, ]', '', line)
parsed = [int(p.strip()) for p in abcdef.split(',')]
for x in parsed:
if ((x < 0) or (x > 255)):
raise ValueError('Out of range', line, x)
(a, b, c, d, e, f) = parsed
host = ('%s.%s.%s.%... |
null | null | null | What does the code find ?
| def _get_logger(self):
try:
logger = self.logger
except AttributeError:
return _logger
else:
if (logger is None):
logger = _logger
return logger
| null | null | null | the specific or default logger
| codeqa | def get logger self try logger self loggerexcept Attribute Error return loggerelse if logger is None logger loggerreturn logger
| null | null | null | null | Question:
What does the code find ?
Code:
def _get_logger(self):
try:
logger = self.logger
except AttributeError:
return _logger
else:
if (logger is None):
logger = _logger
return logger
|
null | null | null | When are identical strings not stored ?
| def config_14(key, salt, string_list):
if ('email' in string_list[18]):
dup = True
elif ('email' in string_list[19]):
dup = False
config_dict = {}
config_dict['Version'] = 'Predator Pain v14'
config_dict['Email Address'] = decrypt_string(key, salt, string_list[4])
config_dict['Email Password'] = decrypt_s... | null | null | null | multiple times
| codeqa | def config 14 key salt string list if 'email' in string list[ 18 ] dup Trueelif 'email' in string list[ 19 ] dup Falseconfig dict {}config dict[' Version'] ' Predator Painv 14 'config dict[' Email Address'] decrypt string key salt string list[ 4 ] config dict[' Email Password'] decrypt string key salt string list[ 5 ] ... | null | null | null | null | Question:
When are identical strings not stored ?
Code:
def config_14(key, salt, string_list):
if ('email' in string_list[18]):
dup = True
elif ('email' in string_list[19]):
dup = False
config_dict = {}
config_dict['Version'] = 'Predator Pain v14'
config_dict['Email Address'] = decrypt_string(key, salt,... |
null | null | null | What does the code get from attribute dictionary ?
| def getGeometryOutput(derivation, elementNode):
if (derivation == None):
derivation = ConcatenateDerivation(elementNode)
concatenatedList = euclidean.getConcatenatedList(derivation.target)[:]
if (len(concatenatedList) == 0):
print 'Warning, in concatenate there are no paths.'
print elementNode.attributes... | null | null | null | triangle mesh
| codeqa | def get Geometry Output derivation element Node if derivation None derivation Concatenate Derivation element Node concatenated List euclidean get Concatenated List derivation target [ ]if len concatenated List 0 print ' Warning inconcatenatetherearenopaths 'print element Node attributesreturn Noneif 'closed' not in ele... | null | null | null | null | Question:
What does the code get from attribute dictionary ?
Code:
def getGeometryOutput(derivation, elementNode):
if (derivation == None):
derivation = ConcatenateDerivation(elementNode)
concatenatedList = euclidean.getConcatenatedList(derivation.target)[:]
if (len(concatenatedList) == 0):
print 'Warning, ... |
null | null | null | What does a decorator run during function execution ?
| def server(responses=RESPONSES, files=FILES, passwords=PASSWORDS, home=HOME, pubkeys=False, port=PORT):
def run_server(func):
@wraps(func)
def inner(*args, **kwargs):
_server = serve_responses(responses, files, passwords, home, pubkeys, port)
_server.all_done = threading.Event()
worker = ThreadHandler('se... | null | null | null | an ssh server
| codeqa | def server responses RESPONSES files FILES passwords PASSWORDS home HOME pubkeys False port PORT def run server func @wraps func def inner *args **kwargs server serve responses responses files passwords home pubkeys port server all done threading Event worker Thread Handler 'server' server serve forever try return func... | null | null | null | null | Question:
What does a decorator run during function execution ?
Code:
def server(responses=RESPONSES, files=FILES, passwords=PASSWORDS, home=HOME, pubkeys=False, port=PORT):
def run_server(func):
@wraps(func)
def inner(*args, **kwargs):
_server = serve_responses(responses, files, passwords, home, pubkeys, p... |
null | null | null | When does a decorator run an ssh server ?
| def server(responses=RESPONSES, files=FILES, passwords=PASSWORDS, home=HOME, pubkeys=False, port=PORT):
def run_server(func):
@wraps(func)
def inner(*args, **kwargs):
_server = serve_responses(responses, files, passwords, home, pubkeys, port)
_server.all_done = threading.Event()
worker = ThreadHandler('se... | null | null | null | during function execution
| codeqa | def server responses RESPONSES files FILES passwords PASSWORDS home HOME pubkeys False port PORT def run server func @wraps func def inner *args **kwargs server serve responses responses files passwords home pubkeys port server all done threading Event worker Thread Handler 'server' server serve forever try return func... | null | null | null | null | Question:
When does a decorator run an ssh server ?
Code:
def server(responses=RESPONSES, files=FILES, passwords=PASSWORDS, home=HOME, pubkeys=False, port=PORT):
def run_server(func):
@wraps(func)
def inner(*args, **kwargs):
_server = serve_responses(responses, files, passwords, home, pubkeys, port)
_ser... |
null | null | null | What runs an ssh server during function execution ?
| def server(responses=RESPONSES, files=FILES, passwords=PASSWORDS, home=HOME, pubkeys=False, port=PORT):
def run_server(func):
@wraps(func)
def inner(*args, **kwargs):
_server = serve_responses(responses, files, passwords, home, pubkeys, port)
_server.all_done = threading.Event()
worker = ThreadHandler('se... | null | null | null | a decorator
| codeqa | def server responses RESPONSES files FILES passwords PASSWORDS home HOME pubkeys False port PORT def run server func @wraps func def inner *args **kwargs server serve responses responses files passwords home pubkeys port server all done threading Event worker Thread Handler 'server' server serve forever try return func... | null | null | null | null | Question:
What runs an ssh server during function execution ?
Code:
def server(responses=RESPONSES, files=FILES, passwords=PASSWORDS, home=HOME, pubkeys=False, port=PORT):
def run_server(func):
@wraps(func)
def inner(*args, **kwargs):
_server = serve_responses(responses, files, passwords, home, pubkeys, por... |
null | null | null | What executes locally ?
| def script_retcode(source, args=None, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, python_shell=None, env=None, template='jinja', umask=None, timeout=None, reset_system_locale=True, saltenv='base', output_loglevel='debug', log_callback=None, use_vt=False, password=None, **kwargs):
if ('__env__' in kwargs):
... | null | null | null | the script
| codeqa | def script retcode source args None cwd None stdin None runas None shell DEFAULT SHELL python shell None env None template 'jinja' umask None timeout None reset system locale True saltenv 'base' output loglevel 'debug' log callback None use vt False password None **kwargs if ' env ' in kwargs salt utils warn until ' Ox... | null | null | null | null | Question:
What executes locally ?
Code:
def script_retcode(source, args=None, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, python_shell=None, env=None, template='jinja', umask=None, timeout=None, reset_system_locale=True, saltenv='base', output_loglevel='debug', log_callback=None, use_vt=False, password=N... |
null | null | null | What does the code estimate ?
| def estimate_bandwidth(X, quantile=0.3, n_samples=None, random_state=0, n_jobs=1):
random_state = check_random_state(random_state)
if (n_samples is not None):
idx = random_state.permutation(X.shape[0])[:n_samples]
X = X[idx]
nbrs = NearestNeighbors(n_neighbors=int((X.shape[0] * quantile)), n_jobs=n_jobs)
nbrs.f... | null | null | null | the bandwidth to use with the mean - shift algorithm
| codeqa | def estimate bandwidth X quantile 0 3 n samples None random state 0 n jobs 1 random state check random state random state if n samples is not None idx random state permutation X shape[ 0 ] [ n samples]X X[idx]nbrs Nearest Neighbors n neighbors int X shape[ 0 ] * quantile n jobs n jobs nbrs fit X bandwidth 0 0for batch ... | null | null | null | null | Question:
What does the code estimate ?
Code:
def estimate_bandwidth(X, quantile=0.3, n_samples=None, random_state=0, n_jobs=1):
random_state = check_random_state(random_state)
if (n_samples is not None):
idx = random_state.permutation(X.shape[0])[:n_samples]
X = X[idx]
nbrs = NearestNeighbors(n_neighbors=in... |
null | null | null | What does the code read ?
| def read_bin_lush_matrix(filepath):
f = open(filepath, 'rb')
try:
magic = read_int(f)
except ValueError:
reraise_as("Couldn't read magic number")
ndim = read_int(f)
if (ndim == 0):
shape = ()
else:
shape = read_int(f, max(3, ndim))
total_elems = 1
for dim in shape:
total_elems *= dim
try:
dtype ... | null | null | null | a binary matrix saved by the lush library
| codeqa | def read bin lush matrix filepath f open filepath 'rb' try magic read int f except Value Error reraise as " Couldn'treadmagicnumber" ndim read int f if ndim 0 shape else shape read int f max 3 ndim total elems 1for dim in shape total elems * dimtry dtype lush magic[magic]except Key Error reraise as Value Error ' Unreco... | null | null | null | null | Question:
What does the code read ?
Code:
def read_bin_lush_matrix(filepath):
f = open(filepath, 'rb')
try:
magic = read_int(f)
except ValueError:
reraise_as("Couldn't read magic number")
ndim = read_int(f)
if (ndim == 0):
shape = ()
else:
shape = read_int(f, max(3, ndim))
total_elems = 1
for dim... |
null | null | null | How did the code set node location information ?
| def set_location(node, lineno, col_offset):
def _fix(node, lineno, col_offset):
if ('lineno' in node._attributes):
node.lineno = lineno
if ('col_offset' in node._attributes):
node.col_offset = col_offset
for child in ast.iter_child_nodes(node):
_fix(child, lineno, col_offset)
_fix(node, lineno, col_off... | null | null | null | recursively
| codeqa | def set location node lineno col offset def fix node lineno col offset if 'lineno' in node attributes node lineno linenoif 'col offset' in node attributes node col offset col offsetfor child in ast iter child nodes node fix child lineno col offset fix node lineno col offset return node
| null | null | null | null | Question:
How did the code set node location information ?
Code:
def set_location(node, lineno, col_offset):
def _fix(node, lineno, col_offset):
if ('lineno' in node._attributes):
node.lineno = lineno
if ('col_offset' in node._attributes):
node.col_offset = col_offset
for child in ast.iter_child_nodes(... |
null | null | null | What did the code set recursively ?
| def set_location(node, lineno, col_offset):
def _fix(node, lineno, col_offset):
if ('lineno' in node._attributes):
node.lineno = lineno
if ('col_offset' in node._attributes):
node.col_offset = col_offset
for child in ast.iter_child_nodes(node):
_fix(child, lineno, col_offset)
_fix(node, lineno, col_off... | null | null | null | node location information
| codeqa | def set location node lineno col offset def fix node lineno col offset if 'lineno' in node attributes node lineno linenoif 'col offset' in node attributes node col offset col offsetfor child in ast iter child nodes node fix child lineno col offset fix node lineno col offset return node
| null | null | null | null | Question:
What did the code set recursively ?
Code:
def set_location(node, lineno, col_offset):
def _fix(node, lineno, col_offset):
if ('lineno' in node._attributes):
node.lineno = lineno
if ('col_offset' in node._attributes):
node.col_offset = col_offset
for child in ast.iter_child_nodes(node):
_fi... |
null | null | null | How does the code run a command ?
| def run_command(command, module, check_rc=True):
(rc, out, err) = module.run_command(command, check_rc=check_rc, cwd=module.params['chdir'])
return (rc, sanitize_output(out), sanitize_output(err))
| null | null | null | using the module
| codeqa | def run command command module check rc True rc out err module run command command check rc check rc cwd module params['chdir'] return rc sanitize output out sanitize output err
| null | null | null | null | Question:
How does the code run a command ?
Code:
def run_command(command, module, check_rc=True):
(rc, out, err) = module.run_command(command, check_rc=check_rc, cwd=module.params['chdir'])
return (rc, sanitize_output(out), sanitize_output(err))
|
null | null | null | What does the code run using the module ?
| def run_command(command, module, check_rc=True):
(rc, out, err) = module.run_command(command, check_rc=check_rc, cwd=module.params['chdir'])
return (rc, sanitize_output(out), sanitize_output(err))
| null | null | null | a command
| codeqa | def run command command module check rc True rc out err module run command command check rc check rc cwd module params['chdir'] return rc sanitize output out sanitize output err
| null | null | null | null | Question:
What does the code run using the module ?
Code:
def run_command(command, module, check_rc=True):
(rc, out, err) = module.run_command(command, check_rc=check_rc, cwd=module.params['chdir'])
return (rc, sanitize_output(out), sanitize_output(err))
|
null | null | null | What does the system need ?
| def needs_reboot():
pythoncom.CoInitialize()
obj_sys = win32com.client.Dispatch('Microsoft.Update.SystemInfo')
return salt.utils.is_true(obj_sys.RebootRequired)
| null | null | null | to be rebooted
| codeqa | def needs reboot pythoncom Co Initialize obj sys win 32 com client Dispatch ' Microsoft Update System Info' return salt utils is true obj sys Reboot Required
| null | null | null | null | Question:
What does the system need ?
Code:
def needs_reboot():
pythoncom.CoInitialize()
obj_sys = win32com.client.Dispatch('Microsoft.Update.SystemInfo')
return salt.utils.is_true(obj_sys.RebootRequired)
|
null | null | null | What needs to be rebooted ?
| def needs_reboot():
pythoncom.CoInitialize()
obj_sys = win32com.client.Dispatch('Microsoft.Update.SystemInfo')
return salt.utils.is_true(obj_sys.RebootRequired)
| null | null | null | the system
| codeqa | def needs reboot pythoncom Co Initialize obj sys win 32 com client Dispatch ' Microsoft Update System Info' return salt utils is true obj sys Reboot Required
| null | null | null | null | Question:
What needs to be rebooted ?
Code:
def needs_reboot():
pythoncom.CoInitialize()
obj_sys = win32com.client.Dispatch('Microsoft.Update.SystemInfo')
return salt.utils.is_true(obj_sys.RebootRequired)
|
null | null | null | What will multiline - related code cause ?
| def normalize_multiline(line):
if (line.startswith(u'def ') and line.rstrip().endswith(u':')):
return (line + u' pass')
elif line.startswith(u'return '):
return (u'def _(): ' + line)
elif line.startswith(u'@'):
return (line + u'def _(): pass')
elif line.startswith(u'class '):
return (line + u' pass... | null | null | null | syntax error
| codeqa | def normalize multiline line if line startswith u'def' and line rstrip endswith u' ' return line + u'pass' elif line startswith u'return' return u'def ' + line elif line startswith u'@' return line + u'def pass' elif line startswith u'class' return line + u'pass' elif line startswith u'if' u'elif' u'for' u'while' retur... | null | null | null | null | Question:
What will multiline - related code cause ?
Code:
def normalize_multiline(line):
if (line.startswith(u'def ') and line.rstrip().endswith(u':')):
return (line + u' pass')
elif line.startswith(u'return '):
return (u'def _(): ' + line)
elif line.startswith(u'@'):
return (line + u'def _(): pass... |
null | null | null | What will cause syntax error ?
| def normalize_multiline(line):
if (line.startswith(u'def ') and line.rstrip().endswith(u':')):
return (line + u' pass')
elif line.startswith(u'return '):
return (u'def _(): ' + line)
elif line.startswith(u'@'):
return (line + u'def _(): pass')
elif line.startswith(u'class '):
return (line + u' pass... | null | null | null | multiline - related code
| codeqa | def normalize multiline line if line startswith u'def' and line rstrip endswith u' ' return line + u'pass' elif line startswith u'return' return u'def ' + line elif line startswith u'@' return line + u'def pass' elif line startswith u'class' return line + u'pass' elif line startswith u'if' u'elif' u'for' u'while' retur... | null | null | null | null | Question:
What will cause syntax error ?
Code:
def normalize_multiline(line):
if (line.startswith(u'def ') and line.rstrip().endswith(u':')):
return (line + u' pass')
elif line.startswith(u'return '):
return (u'def _(): ' + line)
elif line.startswith(u'@'):
return (line + u'def _(): pass')
elif lin... |
null | null | null | What does the code compare ?
| def darker(image1, image2):
image1.load()
image2.load()
return image1._new(image1.im.chop_darker(image2.im))
| null | null | null | the two images
| codeqa | def darker image 1 image 2 image 1 load image 2 load return image 1 new image 1 im chop darker image 2 im
| null | null | null | null | Question:
What does the code compare ?
Code:
def darker(image1, image2):
image1.load()
image2.load()
return image1._new(image1.im.chop_darker(image2.im))
|
null | null | null | What does the code retrieve from the request cache ?
| def get_event_transaction_type():
return get_cache('event_transaction').get('type', None)
| null | null | null | the current event transaction type
| codeqa | def get event transaction type return get cache 'event transaction' get 'type' None
| null | null | null | null | Question:
What does the code retrieve from the request cache ?
Code:
def get_event_transaction_type():
return get_cache('event_transaction').get('type', None)
|
null | null | null | What does the code insert into a loop ?
| def addWithLeastLength(loops, point, shortestAdditionalLength):
shortestLoop = None
shortestPointIndex = None
for loop in loops:
if (len(loop) > 2):
for pointIndex in xrange(len(loop)):
additionalLength = getAdditionalLoopLength(loop, point, pointIndex)
if (additionalLength < shortestAdditionalLength):
... | null | null | null | a point
| codeqa | def add With Least Length loops point shortest Additional Length shortest Loop Noneshortest Point Index Nonefor loop in loops if len loop > 2 for point Index in xrange len loop additional Length get Additional Loop Length loop point point Index if additional Length < shortest Additional Length shortest Additional Lengt... | null | null | null | null | Question:
What does the code insert into a loop ?
Code:
def addWithLeastLength(loops, point, shortestAdditionalLength):
shortestLoop = None
shortestPointIndex = None
for loop in loops:
if (len(loop) > 2):
for pointIndex in xrange(len(loop)):
additionalLength = getAdditionalLoopLength(loop, point, pointI... |
null | null | null | What raises a user ?
| @common_exceptions_400
def view_user_doesnotexist(request):
raise User.DoesNotExist()
| null | null | null | a dummy view
| codeqa | @common exceptions 400 def view user doesnotexist request raise User Does Not Exist
| null | null | null | null | Question:
What raises a user ?
Code:
@common_exceptions_400
def view_user_doesnotexist(request):
raise User.DoesNotExist()
|
null | null | null | What does a dummy view raise ?
| @common_exceptions_400
def view_user_doesnotexist(request):
raise User.DoesNotExist()
| null | null | null | a user
| codeqa | @common exceptions 400 def view user doesnotexist request raise User Does Not Exist
| null | null | null | null | Question:
What does a dummy view raise ?
Code:
@common_exceptions_400
def view_user_doesnotexist(request):
raise User.DoesNotExist()
|
null | null | null | By how much have filenames been modified ?
| def diff_index_filenames(ref):
out = git.diff_index(ref, name_only=True, z=True)[STDOUT]
return _parse_diff_filenames(out)
| null | null | null | relative to the index
| codeqa | def diff index filenames ref out git diff index ref name only True z True [STDOUT]return parse diff filenames out
| null | null | null | null | Question:
By how much have filenames been modified ?
Code:
def diff_index_filenames(ref):
out = git.diff_index(ref, name_only=True, z=True)[STDOUT]
return _parse_diff_filenames(out)
|
null | null | null | What does the code get ?
| def getTopPath(path):
top = (-9.876543219876543e+17)
for point in path:
top = max(top, point.z)
return top
| null | null | null | the top of the path
| codeqa | def get Top Path path top -9 876543219876543 e+ 17 for point in path top max top point z return top
| null | null | null | null | Question:
What does the code get ?
Code:
def getTopPath(path):
top = (-9.876543219876543e+17)
for point in path:
top = max(top, point.z)
return top
|
null | null | null | What did the code read ?
| def read_regexp_block(stream, start_re, end_re=None):
while True:
line = stream.readline()
if (not line):
return []
if re.match(start_re, line):
break
lines = [line]
while True:
oldpos = stream.tell()
line = stream.readline()
if (not line):
return [''.join(lines)]
if ((end_re is not None) and ... | null | null | null | a sequence of tokens from a stream
| codeqa | def read regexp block stream start re end re None while True line stream readline if not line return []if re match start re line breaklines [line]while True oldpos stream tell line stream readline if not line return ['' join lines ]if end re is not None and re match end re line return ['' join lines ]if end re is None ... | null | null | null | null | Question:
What did the code read ?
Code:
def read_regexp_block(stream, start_re, end_re=None):
while True:
line = stream.readline()
if (not line):
return []
if re.match(start_re, line):
break
lines = [line]
while True:
oldpos = stream.tell()
line = stream.readline()
if (not line):
return [''... |
null | null | null | How does that creation fail ?
| def test_account_create_should_fail():
credentials = [((c['user'], c['password']), e) for (c, e) in broken_credentials]
for ((email, password), error) in credentials:
error_obj = getattr(errors, error)
with session_scope() as db_session:
with pytest.raises(error_obj):
create_account(db_session, email, pass... | null | null | null | with appropriate errors
| codeqa | def test account create should fail credentials [ c['user'] c['password'] e for c e in broken credentials]for email password error in credentials error obj getattr errors error with session scope as db session with pytest raises error obj create account db session email password
| null | null | null | null | Question:
How does that creation fail ?
Code:
def test_account_create_should_fail():
credentials = [((c['user'], c['password']), e) for (c, e) in broken_credentials]
for ((email, password), error) in credentials:
error_obj = getattr(errors, error)
with session_scope() as db_session:
with pytest.raises(erro... |
null | null | null | What does the code provide ?
| def WinChmod(filename, acl_list, user=None):
if (user is None):
user = win32api.GetUserName()
if (not os.path.exists(filename)):
raise RuntimeError(('filename %s does not exist' % filename))
acl_bitmask = 0
for acl in acl_list:
acl_bitmask |= getattr(ntsecuritycon, acl)
dacl = win32security.ACL()
(win_u... | null | null | null | chmod - like functionality for windows
| codeqa | def Win Chmod filename acl list user None if user is None user win 32 api Get User Name if not os path exists filename raise Runtime Error 'filename%sdoesnotexist' % filename acl bitmask 0for acl in acl list acl bitmask getattr ntsecuritycon acl dacl win 32 security ACL win user win 32 security Lookup Account Name '' u... | null | null | null | null | Question:
What does the code provide ?
Code:
def WinChmod(filename, acl_list, user=None):
if (user is None):
user = win32api.GetUserName()
if (not os.path.exists(filename)):
raise RuntimeError(('filename %s does not exist' % filename))
acl_bitmask = 0
for acl in acl_list:
acl_bitmask |= getattr(ntsecu... |
null | null | null | What does the code decorate ?
| def one(method):
def loop(method, self, *args, **kwargs):
result = [method(rec, *args, **kwargs) for rec in self]
return aggregate(method, result, self)
wrapper = decorator(loop, method)
wrapper._api = 'one'
return wrapper
| null | null | null | a record - style method where self is expected to be a singleton instance
| codeqa | def one method def loop method self *args **kwargs result [method rec *args **kwargs for rec in self]return aggregate method result self wrapper decorator loop method wrapper api 'one'return wrapper
| null | null | null | null | Question:
What does the code decorate ?
Code:
def one(method):
def loop(method, self, *args, **kwargs):
result = [method(rec, *args, **kwargs) for rec in self]
return aggregate(method, result, self)
wrapper = decorator(loop, method)
wrapper._api = 'one'
return wrapper
|
null | null | null | What does the code get ?
| @pick_context_manager_reader
def instance_group_get_all(context):
return _instance_group_get_query(context, models.InstanceGroup).all()
| null | null | null | all groups
| codeqa | @pick context manager readerdef instance group get all context return instance group get query context models Instance Group all
| null | null | null | null | Question:
What does the code get ?
Code:
@pick_context_manager_reader
def instance_group_get_all(context):
return _instance_group_get_query(context, models.InstanceGroup).all()
|
null | null | null | When do requests serve ?
| def _eventlet_serve(sock, handle, concurrency):
pool = eventlet.greenpool.GreenPool(concurrency)
server_gt = eventlet.greenthread.getcurrent()
while True:
try:
(conn, addr) = sock.accept()
gt = pool.spawn(handle, conn, addr)
gt.link(_eventlet_stop, server_gt, conn)
(conn, addr, gt) = (None, None, None)... | null | null | null | forever
| codeqa | def eventlet serve sock handle concurrency pool eventlet greenpool Green Pool concurrency server gt eventlet greenthread getcurrent while True try conn addr sock accept gt pool spawn handle conn addr gt link eventlet stop server gt conn conn addr gt None None None except eventlet Stop Serve sock close pool waitall retu... | null | null | null | null | Question:
When do requests serve ?
Code:
def _eventlet_serve(sock, handle, concurrency):
pool = eventlet.greenpool.GreenPool(concurrency)
server_gt = eventlet.greenthread.getcurrent()
while True:
try:
(conn, addr) = sock.accept()
gt = pool.spawn(handle, conn, addr)
gt.link(_eventlet_stop, server_gt, c... |
null | null | null | How did decorator apply ?
| def conditional(condition, decorator):
if condition:
return decorator
else:
return (lambda fn: fn)
| null | null | null | conditionally
| codeqa | def conditional condition decorator if condition return decoratorelse return lambda fn fn
| null | null | null | null | Question:
How did decorator apply ?
Code:
def conditional(condition, decorator):
if condition:
return decorator
else:
return (lambda fn: fn)
|
null | null | null | What returns a unique temporary file name ?
| def mktemp(suffix='', prefix=template, dir=None):
if (dir is None):
dir = gettempdir()
names = _get_candidate_names()
for seq in range(TMP_MAX):
name = next(names)
file = _os.path.join(dir, ((prefix + name) + suffix))
if (not _exists(file)):
return file
raise FileExistsError(_errno.EEXIST, 'No usable t... | null | null | null | user - callable function
| codeqa | def mktemp suffix '' prefix template dir None if dir is None dir gettempdir names get candidate names for seq in range TMP MAX name next names file os path join dir prefix + name + suffix if not exists file return fileraise File Exists Error errno EEXIST ' Nousabletemporaryfilenamefound'
| null | null | null | null | Question:
What returns a unique temporary file name ?
Code:
def mktemp(suffix='', prefix=template, dir=None):
if (dir is None):
dir = gettempdir()
names = _get_candidate_names()
for seq in range(TMP_MAX):
name = next(names)
file = _os.path.join(dir, ((prefix + name) + suffix))
if (not _exists(file)):
... |
null | null | null | What do user - callable function return ?
| def mktemp(suffix='', prefix=template, dir=None):
if (dir is None):
dir = gettempdir()
names = _get_candidate_names()
for seq in range(TMP_MAX):
name = next(names)
file = _os.path.join(dir, ((prefix + name) + suffix))
if (not _exists(file)):
return file
raise FileExistsError(_errno.EEXIST, 'No usable t... | null | null | null | a unique temporary file name
| codeqa | def mktemp suffix '' prefix template dir None if dir is None dir gettempdir names get candidate names for seq in range TMP MAX name next names file os path join dir prefix + name + suffix if not exists file return fileraise File Exists Error errno EEXIST ' Nousabletemporaryfilenamefound'
| null | null | null | null | Question:
What do user - callable function return ?
Code:
def mktemp(suffix='', prefix=template, dir=None):
if (dir is None):
dir = gettempdir()
names = _get_candidate_names()
for seq in range(TMP_MAX):
name = next(names)
file = _os.path.join(dir, ((prefix + name) + suffix))
if (not _exists(file)):
re... |
null | null | null | What does this read ?
| def read_batchfile(pythonpath, file_ending='.py'):
abspaths = utils.pypath_to_realpath(pythonpath, file_ending, settings.BASE_BATCHPROCESS_PATHS)
if (not abspaths):
raise IOError
text = None
decoderr = []
for abspath in abspaths:
for file_encoding in _ENCODINGS:
try:
with codecs.open(abspath, 'r', encod... | null | null | null | the contents of a batch - file
| codeqa | def read batchfile pythonpath file ending ' py' abspaths utils pypath to realpath pythonpath file ending settings BASE BATCHPROCESS PATHS if not abspaths raise IO Errortext Nonedecoderr []for abspath in abspaths for file encoding in ENCODINGS try with codecs open abspath 'r' encoding file encoding as fobj text fobj rea... | null | null | null | null | Question:
What does this read ?
Code:
def read_batchfile(pythonpath, file_ending='.py'):
abspaths = utils.pypath_to_realpath(pythonpath, file_ending, settings.BASE_BATCHPROCESS_PATHS)
if (not abspaths):
raise IOError
text = None
decoderr = []
for abspath in abspaths:
for file_encoding in _ENCODINGS:
try... |
null | null | null | What reads the contents of a batch - file ?
| def read_batchfile(pythonpath, file_ending='.py'):
abspaths = utils.pypath_to_realpath(pythonpath, file_ending, settings.BASE_BATCHPROCESS_PATHS)
if (not abspaths):
raise IOError
text = None
decoderr = []
for abspath in abspaths:
for file_encoding in _ENCODINGS:
try:
with codecs.open(abspath, 'r', encod... | null | null | null | this
| codeqa | def read batchfile pythonpath file ending ' py' abspaths utils pypath to realpath pythonpath file ending settings BASE BATCHPROCESS PATHS if not abspaths raise IO Errortext Nonedecoderr []for abspath in abspaths for file encoding in ENCODINGS try with codecs open abspath 'r' encoding file encoding as fobj text fobj rea... | null | null | null | null | Question:
What reads the contents of a batch - file ?
Code:
def read_batchfile(pythonpath, file_ending='.py'):
abspaths = utils.pypath_to_realpath(pythonpath, file_ending, settings.BASE_BATCHPROCESS_PATHS)
if (not abspaths):
raise IOError
text = None
decoderr = []
for abspath in abspaths:
for file_encoding... |
null | null | null | What does the code find ?
| def search_object_by_tag(key=None, category=None):
return ObjectDB.objects.get_by_tag(key=key, category=category)
| null | null | null | object based on tag or category
| codeqa | def search object by tag key None category None return Object DB objects get by tag key key category category
| null | null | null | null | Question:
What does the code find ?
Code:
def search_object_by_tag(key=None, category=None):
return ObjectDB.objects.get_by_tag(key=key, category=category)
|
null | null | null | What does the code kill before point ?
| @register(u'backward-kill-word')
def backward_kill_word(event):
unix_word_rubout(event, WORD=False)
| null | null | null | the word
| codeqa | @register u'backward-kill-word' def backward kill word event unix word rubout event WORD False
| null | null | null | null | Question:
What does the code kill before point ?
Code:
@register(u'backward-kill-word')
def backward_kill_word(event):
unix_word_rubout(event, WORD=False)
|
null | null | null | When does the code kill the word ?
| @register(u'backward-kill-word')
def backward_kill_word(event):
unix_word_rubout(event, WORD=False)
| null | null | null | before point
| codeqa | @register u'backward-kill-word' def backward kill word event unix word rubout event WORD False
| null | null | null | null | Question:
When does the code kill the word ?
Code:
@register(u'backward-kill-word')
def backward_kill_word(event):
unix_word_rubout(event, WORD=False)
|
null | null | null | What creates in a single block ?
| def from_func(func, shape, dtype=None, name=None, args=(), kwargs={}):
name = (name or ('from_func-' + tokenize(func, shape, dtype, args, kwargs)))
if (args or kwargs):
func = partial(func, *args, **kwargs)
dsk = {((name,) + ((0,) * len(shape))): (func,)}
chunks = tuple(((i,) for i in shape))
return Array(dsk, n... | null | null | null | dask array
| codeqa | def from func func shape dtype None name None args kwargs {} name name or 'from func-' + tokenize func shape dtype args kwargs if args or kwargs func partial func *args **kwargs dsk { name + 0 * len shape func }chunks tuple i for i in shape return Array dsk name chunks dtype
| null | null | null | null | Question:
What creates in a single block ?
Code:
def from_func(func, shape, dtype=None, name=None, args=(), kwargs={}):
name = (name or ('from_func-' + tokenize(func, shape, dtype, args, kwargs)))
if (args or kwargs):
func = partial(func, *args, **kwargs)
dsk = {((name,) + ((0,) * len(shape))): (func,)}
chunk... |
null | null | null | How do append_positions work ?
| @image_comparison(baseline_images=[u'EventCollection_plot__append_positions'])
def test__EventCollection__append_positions():
(splt, coll, props) = generate_EventCollection_plot()
new_positions = np.hstack([props[u'positions'], props[u'extra_positions'][2]])
coll.append_positions(props[u'extra_positions'][2])
np.te... | null | null | null | properly
| codeqa | @image comparison baseline images [u' Event Collection plot append positions'] def test Event Collection append positions splt coll props generate Event Collection plot new positions np hstack [props[u'positions'] props[u'extra positions'][ 2 ]] coll append positions props[u'extra positions'][ 2 ] np testing assert arr... | null | null | null | null | Question:
How do append_positions work ?
Code:
@image_comparison(baseline_images=[u'EventCollection_plot__append_positions'])
def test__EventCollection__append_positions():
(splt, coll, props) = generate_EventCollection_plot()
new_positions = np.hstack([props[u'positions'], props[u'extra_positions'][2]])
coll.ap... |
null | null | null | What does the code catch ?
| def catchLogs(testCase, logPublisher=globalLogPublisher):
logs = []
logPublisher.addObserver(logs.append)
testCase.addCleanup((lambda : logPublisher.removeObserver(logs.append)))
return (lambda : [formatEvent(event) for event in logs])
| null | null | null | the global log stream
| codeqa | def catch Logs test Case log Publisher global Log Publisher logs []log Publisher add Observer logs append test Case add Cleanup lambda log Publisher remove Observer logs append return lambda [format Event event for event in logs]
| null | null | null | null | Question:
What does the code catch ?
Code:
def catchLogs(testCase, logPublisher=globalLogPublisher):
logs = []
logPublisher.addObserver(logs.append)
testCase.addCleanup((lambda : logPublisher.removeObserver(logs.append)))
return (lambda : [formatEvent(event) for event in logs])
|
null | null | null | What are being stripped the part ?
| def _remove_statements(evaluator, stmt, name):
types = set()
check_instance = None
if (isinstance(stmt, er.InstanceElement) and stmt.is_class_var):
check_instance = stmt.instance
stmt = stmt.var
pep0484types = pep0484.find_type_from_comment_hint_assign(evaluator, stmt, name)
if pep0484types:
return pep0484ty... | null | null | null | statements
| codeqa | def remove statements evaluator stmt name types set check instance Noneif isinstance stmt er Instance Element and stmt is class var check instance stmt instancestmt stmt varpep 0484 types pep 0484 find type from comment hint assign evaluator stmt name if pep 0484 types return pep 0484 typestypes evaluator eval statemen... | null | null | null | null | Question:
What are being stripped the part ?
Code:
def _remove_statements(evaluator, stmt, name):
types = set()
check_instance = None
if (isinstance(stmt, er.InstanceElement) and stmt.is_class_var):
check_instance = stmt.instance
stmt = stmt.var
pep0484types = pep0484.find_type_from_comment_hint_assign(eval... |
null | null | null | Where are statements being stripped ?
| def _remove_statements(evaluator, stmt, name):
types = set()
check_instance = None
if (isinstance(stmt, er.InstanceElement) and stmt.is_class_var):
check_instance = stmt.instance
stmt = stmt.var
pep0484types = pep0484.find_type_from_comment_hint_assign(evaluator, stmt, name)
if pep0484types:
return pep0484ty... | null | null | null | the part
| codeqa | def remove statements evaluator stmt name types set check instance Noneif isinstance stmt er Instance Element and stmt is class var check instance stmt instancestmt stmt varpep 0484 types pep 0484 find type from comment hint assign evaluator stmt name if pep 0484 types return pep 0484 typestypes evaluator eval statemen... | null | null | null | null | Question:
Where are statements being stripped ?
Code:
def _remove_statements(evaluator, stmt, name):
types = set()
check_instance = None
if (isinstance(stmt, er.InstanceElement) and stmt.is_class_var):
check_instance = stmt.instance
stmt = stmt.var
pep0484types = pep0484.find_type_from_comment_hint_assign(e... |
null | null | null | What does the code delete ?
| @task
def unindex_documents(ids, index_pk):
cls = WikiDocumentType
es = cls.get_connection('indexing')
index = Index.objects.get(pk=index_pk)
cls.bulk_delete(ids, es=es, index=index.prefixed_name)
| null | null | null | a list of documents from the provided index
| codeqa | @taskdef unindex documents ids index pk cls Wiki Document Typees cls get connection 'indexing' index Index objects get pk index pk cls bulk delete ids es es index index prefixed name
| null | null | null | null | Question:
What does the code delete ?
Code:
@task
def unindex_documents(ids, index_pk):
cls = WikiDocumentType
es = cls.get_connection('indexing')
index = Index.objects.get(pk=index_pk)
cls.bulk_delete(ids, es=es, index=index.prefixed_name)
|
null | null | null | What do a string contain ?
| def parseoptions(module, options):
options_dict = keydict()
if options:
regex = re.compile('((?:[^,"\']|"[^"]*"|\'[^\']*\')+)')
parts = regex.split(options)[1:(-1)]
for part in parts:
if ('=' in part):
(key, value) = part.split('=', 1)
options_dict[key] = value
elif (part != ','):
options_dict... | null | null | null | ssh - key options
| codeqa | def parseoptions module options options dict keydict if options regex re compile ' ? [^ "\'] "[^"]*" \'[^\']*\' + ' parts regex split options [1 -1 ]for part in parts if ' ' in part key value part split ' ' 1 options dict[key] valueelif part ' ' options dict[part] Nonereturn options dict
| null | null | null | null | Question:
What do a string contain ?
Code:
def parseoptions(module, options):
options_dict = keydict()
if options:
regex = re.compile('((?:[^,"\']|"[^"]*"|\'[^\']*\')+)')
parts = regex.split(options)[1:(-1)]
for part in parts:
if ('=' in part):
(key, value) = part.split('=', 1)
options_dict[key] ... |
null | null | null | What is containing ssh - key options ?
| def parseoptions(module, options):
options_dict = keydict()
if options:
regex = re.compile('((?:[^,"\']|"[^"]*"|\'[^\']*\')+)')
parts = regex.split(options)[1:(-1)]
for part in parts:
if ('=' in part):
(key, value) = part.split('=', 1)
options_dict[key] = value
elif (part != ','):
options_dict... | null | null | null | a string
| codeqa | def parseoptions module options options dict keydict if options regex re compile ' ? [^ "\'] "[^"]*" \'[^\']*\' + ' parts regex split options [1 -1 ]for part in parts if ' ' in part key value part split ' ' 1 options dict[key] valueelif part ' ' options dict[part] Nonereturn options dict
| null | null | null | null | Question:
What is containing ssh - key options ?
Code:
def parseoptions(module, options):
options_dict = keydict()
if options:
regex = re.compile('((?:[^,"\']|"[^"]*"|\'[^\']*\')+)')
parts = regex.split(options)[1:(-1)]
for part in parts:
if ('=' in part):
(key, value) = part.split('=', 1)
option... |
null | null | null | What does the code return ?
| def parseoptions(module, options):
options_dict = keydict()
if options:
regex = re.compile('((?:[^,"\']|"[^"]*"|\'[^\']*\')+)')
parts = regex.split(options)[1:(-1)]
for part in parts:
if ('=' in part):
(key, value) = part.split('=', 1)
options_dict[key] = value
elif (part != ','):
options_dict... | null | null | null | a dictionary of those options
| codeqa | def parseoptions module options options dict keydict if options regex re compile ' ? [^ "\'] "[^"]*" \'[^\']*\' + ' parts regex split options [1 -1 ]for part in parts if ' ' in part key value part split ' ' 1 options dict[key] valueelif part ' ' options dict[part] Nonereturn options dict
| null | null | null | null | Question:
What does the code return ?
Code:
def parseoptions(module, options):
options_dict = keydict()
if options:
regex = re.compile('((?:[^,"\']|"[^"]*"|\'[^\']*\')+)')
parts = regex.split(options)[1:(-1)]
for part in parts:
if ('=' in part):
(key, value) = part.split('=', 1)
options_dict[key]... |
null | null | null | What does the code read ?
| def parseoptions(module, options):
options_dict = keydict()
if options:
regex = re.compile('((?:[^,"\']|"[^"]*"|\'[^\']*\')+)')
parts = regex.split(options)[1:(-1)]
for part in parts:
if ('=' in part):
(key, value) = part.split('=', 1)
options_dict[key] = value
elif (part != ','):
options_dict... | null | null | null | a string containing ssh - key options
| codeqa | def parseoptions module options options dict keydict if options regex re compile ' ? [^ "\'] "[^"]*" \'[^\']*\' + ' parts regex split options [1 -1 ]for part in parts if ' ' in part key value part split ' ' 1 options dict[key] valueelif part ' ' options dict[part] Nonereturn options dict
| null | null | null | null | Question:
What does the code read ?
Code:
def parseoptions(module, options):
options_dict = keydict()
if options:
regex = re.compile('((?:[^,"\']|"[^"]*"|\'[^\']*\')+)')
parts = regex.split(options)[1:(-1)]
for part in parts:
if ('=' in part):
(key, value) = part.split('=', 1)
options_dict[key] =... |
null | null | null | How does an entity process ?
| def process_entity(entity, datastore, zookeeper):
logging.debug('Process entity {}'.format(str(entity)))
key = entity.keys()[0]
app_id = key.split(dbconstants.KEY_DELIMITER)[0]
valid_entity = validate_row(app_id, entity, zookeeper, datastore)
if ((valid_entity is None) or (valid_entity[key][APP_ENTITY_SCHEMA[0]]... | null | null | null | by updating it if necessary and removing tombstones
| codeqa | def process entity entity datastore zookeeper logging debug ' Processentity{}' format str entity key entity keys [0 ]app id key split dbconstants KEY DELIMITER [0 ]valid entity validate row app id entity zookeeper datastore if valid entity is None or valid entity[key][APP ENTITY SCHEMA[ 0 ]] TOMBSTONE delete entity fro... | null | null | null | null | Question:
How does an entity process ?
Code:
def process_entity(entity, datastore, zookeeper):
logging.debug('Process entity {}'.format(str(entity)))
key = entity.keys()[0]
app_id = key.split(dbconstants.KEY_DELIMITER)[0]
valid_entity = validate_row(app_id, entity, zookeeper, datastore)
if ((valid_entity is ... |
null | null | null | What does the code get ?
| def getResolver():
global theResolver
if (theResolver is None):
try:
theResolver = createResolver()
except ValueError:
theResolver = createResolver(servers=[('127.0.0.1', 53)])
return theResolver
| null | null | null | a resolver instance
| codeqa | def get Resolver global the Resolverif the Resolver is None try the Resolver create Resolver except Value Error the Resolver create Resolver servers [ '127 0 0 1' 53 ] return the Resolver
| null | null | null | null | Question:
What does the code get ?
Code:
def getResolver():
global theResolver
if (theResolver is None):
try:
theResolver = createResolver()
except ValueError:
theResolver = createResolver(servers=[('127.0.0.1', 53)])
return theResolver
|
null | null | null | What does the code dump to the given file object that runs this python script ?
| def create_mock_ssh_script(path):
with open(path, 'w') as f:
f.write('#!/bin/sh\n')
f.write(('%s %s "$@"\n' % (pipes.quote(sys.executable), pipes.quote(os.path.abspath(__file__)))))
os.chmod(path, (stat.S_IREAD | stat.S_IEXEC))
| null | null | null | a wrapper script
| codeqa | def create mock ssh script path with open path 'w' as f f write '# /bin/sh\n' f write '%s%s"$@"\n' % pipes quote sys executable pipes quote os path abspath file os chmod path stat S IREAD stat S IEXEC
| null | null | null | null | Question:
What does the code dump to the given file object that runs this python script ?
Code:
def create_mock_ssh_script(path):
with open(path, 'w') as f:
f.write('#!/bin/sh\n')
f.write(('%s %s "$@"\n' % (pipes.quote(sys.executable), pipes.quote(os.path.abspath(__file__)))))
os.chmod(path, (stat.S_IREAD |... |
null | null | null | What does the given file object run ?
| def create_mock_ssh_script(path):
with open(path, 'w') as f:
f.write('#!/bin/sh\n')
f.write(('%s %s "$@"\n' % (pipes.quote(sys.executable), pipes.quote(os.path.abspath(__file__)))))
os.chmod(path, (stat.S_IREAD | stat.S_IEXEC))
| null | null | null | this python script
| codeqa | def create mock ssh script path with open path 'w' as f f write '# /bin/sh\n' f write '%s%s"$@"\n' % pipes quote sys executable pipes quote os path abspath file os chmod path stat S IREAD stat S IEXEC
| null | null | null | null | Question:
What does the given file object run ?
Code:
def create_mock_ssh_script(path):
with open(path, 'w') as f:
f.write('#!/bin/sh\n')
f.write(('%s %s "$@"\n' % (pipes.quote(sys.executable), pipes.quote(os.path.abspath(__file__)))))
os.chmod(path, (stat.S_IREAD | stat.S_IEXEC))
|
null | null | null | What runs this python script ?
| def create_mock_ssh_script(path):
with open(path, 'w') as f:
f.write('#!/bin/sh\n')
f.write(('%s %s "$@"\n' % (pipes.quote(sys.executable), pipes.quote(os.path.abspath(__file__)))))
os.chmod(path, (stat.S_IREAD | stat.S_IEXEC))
| null | null | null | the given file object
| codeqa | def create mock ssh script path with open path 'w' as f f write '# /bin/sh\n' f write '%s%s"$@"\n' % pipes quote sys executable pipes quote os path abspath file os chmod path stat S IREAD stat S IEXEC
| null | null | null | null | Question:
What runs this python script ?
Code:
def create_mock_ssh_script(path):
with open(path, 'w') as f:
f.write('#!/bin/sh\n')
f.write(('%s %s "$@"\n' % (pipes.quote(sys.executable), pipes.quote(os.path.abspath(__file__)))))
os.chmod(path, (stat.S_IREAD | stat.S_IEXEC))
|
null | null | null | What does a string identify ?
| def _MakeSignature(app_id=None, url=None, kind=None, db_filename=None, perform_map=None, download=None, has_header=None, result_db_filename=None, dump=None, restore=None):
if download:
result_db_line = ('result_db: %s' % result_db_filename)
else:
result_db_line = ''
return (u'\n app_id: %s\n url: %s\n k... | null | null | null | the important options for the database
| codeqa | def Make Signature app id None url None kind None db filename None perform map None download None has header None result db filename None dump None restore None if download result db line 'result db %s' % result db filename else result db line ''return u'\napp id %s\nurl %s\nkind %s\ndownload %s\nmap %s\ndump %s\nresto... | null | null | null | null | Question:
What does a string identify ?
Code:
def _MakeSignature(app_id=None, url=None, kind=None, db_filename=None, perform_map=None, download=None, has_header=None, result_db_filename=None, dump=None, restore=None):
if download:
result_db_line = ('result_db: %s' % result_db_filename)
else:
result_db_line =... |
null | null | null | What identifies the important options for the database ?
| def _MakeSignature(app_id=None, url=None, kind=None, db_filename=None, perform_map=None, download=None, has_header=None, result_db_filename=None, dump=None, restore=None):
if download:
result_db_line = ('result_db: %s' % result_db_filename)
else:
result_db_line = ''
return (u'\n app_id: %s\n url: %s\n k... | null | null | null | a string
| codeqa | def Make Signature app id None url None kind None db filename None perform map None download None has header None result db filename None dump None restore None if download result db line 'result db %s' % result db filename else result db line ''return u'\napp id %s\nurl %s\nkind %s\ndownload %s\nmap %s\ndump %s\nresto... | null | null | null | null | Question:
What identifies the important options for the database ?
Code:
def _MakeSignature(app_id=None, url=None, kind=None, db_filename=None, perform_map=None, download=None, has_header=None, result_db_filename=None, dump=None, restore=None):
if download:
result_db_line = ('result_db: %s' % result_db_filename... |
null | null | null | What does the code create ?
| def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None, attrnsprefix=None):
namespacemap = None
if isinstance(nsprefix, list):
namespacemap = {}
for prefix in nsprefix:
namespacemap[prefix] = nsprefixes[prefix]
nsprefix = nsprefix[0]
if nsprefix:
namespace = (('{' + nsprefixes[nsprefix]) + '... | null | null | null | an element
| codeqa | def makeelement tagname tagtext None nsprefix 'w' attributes None attrnsprefix None namespacemap Noneif isinstance nsprefix list namespacemap {}for prefix in nsprefix namespacemap[prefix] nsprefixes[prefix]nsprefix nsprefix[ 0 ]if nsprefix namespace '{' + nsprefixes[nsprefix] + '}' else namespace ''newelement etree Ele... | null | null | null | null | Question:
What does the code create ?
Code:
def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None, attrnsprefix=None):
namespacemap = None
if isinstance(nsprefix, list):
namespacemap = {}
for prefix in nsprefix:
namespacemap[prefix] = nsprefixes[prefix]
nsprefix = nsprefix[0]
if nsprefix:... |
null | null | null | How do an image file convert ?
| def convert_image(inpath, outpath, size):
cmd = ['sips', '-z', '{0}'.format(size), '{0}'.format(size), inpath, '--out', outpath]
with open(os.devnull, u'w') as pipe:
retcode = subprocess.call(cmd, stdout=pipe, stderr=subprocess.STDOUT)
if (retcode != 0):
raise RuntimeError(u'sips exited with {0}'.format(retco... | null | null | null | using sips
| codeqa | def convert image inpath outpath size cmd ['sips' '-z' '{ 0 }' format size '{ 0 }' format size inpath '--out' outpath]with open os devnull u'w' as pipe retcode subprocess call cmd stdout pipe stderr subprocess STDOUT if retcode 0 raise Runtime Error u'sipsexitedwith{ 0 }' format retcode
| null | null | null | null | Question:
How do an image file convert ?
Code:
def convert_image(inpath, outpath, size):
cmd = ['sips', '-z', '{0}'.format(size), '{0}'.format(size), inpath, '--out', outpath]
with open(os.devnull, u'w') as pipe:
retcode = subprocess.call(cmd, stdout=pipe, stderr=subprocess.STDOUT)
if (retcode != 0):
raise R... |
null | null | null | What does the code get ?
| def _get_id_token_user(token, audiences, allowed_client_ids, time_now, cache):
try:
parsed_token = _verify_signed_jwt_with_certs(token, time_now, cache)
except _AppIdentityError as e:
logging.warning('id_token verification failed: %s', e)
return None
except:
logging.warning('id_token verification failed... | null | null | null | a user for the given i d token
| codeqa | def get id token user token audiences allowed client ids time now cache try parsed token verify signed jwt with certs token time now cache except App Identity Error as e logging warning 'id tokenverificationfailed %s' e return Noneexcept logging warning 'id tokenverificationfailed ' return Noneif verify parsed token pa... | null | null | null | null | Question:
What does the code get ?
Code:
def _get_id_token_user(token, audiences, allowed_client_ids, time_now, cache):
try:
parsed_token = _verify_signed_jwt_with_certs(token, time_now, cache)
except _AppIdentityError as e:
logging.warning('id_token verification failed: %s', e)
return None
except:
lo... |
null | null | null | How do a file print ?
| def Print(file):
finder = _getfinder()
fss = Carbon.File.FSSpec(file)
return finder._print(fss)
| null | null | null | thru the finder
| codeqa | def Print file finder getfinder fss Carbon File FS Spec file return finder print fss
| null | null | null | null | Question:
How do a file print ?
Code:
def Print(file):
finder = _getfinder()
fss = Carbon.File.FSSpec(file)
return finder._print(fss)
|
null | null | null | What does the code retrieve from the global python module namespace by its fully qualified name ?
| def namedAny(name):
if (not name):
raise InvalidName('Empty module name')
names = name.split('.')
if ('' in names):
raise InvalidName(("name must be a string giving a '.'-separated list of Python identifiers, not %r" % (name,)))
topLevelPackage = None
moduleNames = names[:]
while (not topLevelP... | null | null | null | a python object
| codeqa | def named Any name if not name raise Invalid Name ' Emptymodulename' names name split ' ' if '' in names raise Invalid Name "namemustbeastringgivinga' '-separatedlistof Pythonidentifiers not%r" % name top Level Package Nonemodule Names names[ ]while not top Level Package if module Names trialname ' ' join module Names ... | null | null | null | null | Question:
What does the code retrieve from the global python module namespace by its fully qualified name ?
Code:
def namedAny(name):
if (not name):
raise InvalidName('Empty module name')
names = name.split('.')
if ('' in names):
raise InvalidName(("name must be a string giving a '.'-separated list... |
null | null | null | How does the code retrieve a python object from the global python module namespace ?
| def namedAny(name):
if (not name):
raise InvalidName('Empty module name')
names = name.split('.')
if ('' in names):
raise InvalidName(("name must be a string giving a '.'-separated list of Python identifiers, not %r" % (name,)))
topLevelPackage = None
moduleNames = names[:]
while (not topLevelP... | null | null | null | by its fully qualified name
| codeqa | def named Any name if not name raise Invalid Name ' Emptymodulename' names name split ' ' if '' in names raise Invalid Name "namemustbeastringgivinga' '-separatedlistof Pythonidentifiers not%r" % name top Level Package Nonemodule Names names[ ]while not top Level Package if module Names trialname ' ' join module Names ... | null | null | null | null | Question:
How does the code retrieve a python object from the global python module namespace ?
Code:
def namedAny(name):
if (not name):
raise InvalidName('Empty module name')
names = name.split('.')
if ('' in names):
raise InvalidName(("name must be a string giving a '.'-separated list of Python ... |
null | null | null | When do the message and the tensor print ?
| def print_tensor(x, message=''):
p_op = Print(message)
return p_op(x)
| null | null | null | when evaluated
| codeqa | def print tensor x message '' p op Print message return p op x
| null | null | null | null | Question:
When do the message and the tensor print ?
Code:
def print_tensor(x, message=''):
p_op = Print(message)
return p_op(x)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.