labNo float64 1 10 ⌀ | taskNo float64 0 4 ⌀ | questioner stringclasses 2 values | question stringlengths 9 201 | code stringlengths 18 30.3k | startLine float64 0 192 ⌀ | endLine float64 0 196 ⌀ | questionType stringclasses 4 values | answer stringlengths 2 905 | src stringclasses 3 values | code_processed stringlengths 12 28.3k ⌀ | id stringlengths 2 5 ⌀ | raw_code stringlengths 20 30.3k ⌀ | raw_comment stringlengths 10 242 ⌀ | comment stringlengths 9 207 ⌀ | q_code stringlengths 66 30.3k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
null | null | null | How do binary string convert ?
| def str2hex(value, prefix='', glue=u'', format='%02X'):
if isinstance(glue, str):
glue = unicode(glue)
if (0 < len(prefix)):
text = [prefix]
else:
text = []
for character in value:
text.append((format % ord(character)))
return glue.join(text)
| null | null | null | in hexadecimal
| codeqa | def str 2 hex value prefix '' glue u'' format '% 02 X' if isinstance glue str glue unicode glue if 0 < len prefix text [prefix]else text []for character in value text append format % ord character return glue join text
| null | null | null | null | Question:
How do binary string convert ?
Code:
def str2hex(value, prefix='', glue=u'', format='%02X'):
if isinstance(glue, str):
glue = unicode(glue)
if (0 < len(prefix)):
text = [prefix]
else:
text = []
for character in value:
text.append((format % ord(character)))
return glue.join(text)
|
null | null | null | What did the code use ?
| def members_set_option(arg):
if (arg is None):
return ALL
return set((x.strip() for x in arg.split(',')))
| null | null | null | to convert the : members : option to auto directives
| codeqa | def members set option arg if arg is None return AL Lreturn set x strip for x in arg split ' '
| null | null | null | null | Question:
What did the code use ?
Code:
def members_set_option(arg):
if (arg is None):
return ALL
return set((x.strip() for x in arg.split(',')))
|
null | null | null | What should take other context managers ?
| def test_settings_with_other_context_managers():
env.testval1 = 'outer 1'
prev_lcwd = env.lcwd
with settings(lcd('here'), testval1='inner 1'):
eq_(env.testval1, 'inner 1')
ok_(env.lcwd.endswith('here'))
ok_(env.testval1, 'outer 1')
eq_(env.lcwd, prev_lcwd)
| null | null | null | settings
| codeqa | def test settings with other context managers env testval 1 'outer 1 'prev lcwd env lcwdwith settings lcd 'here' testval 1 'inner 1 ' eq env testval 1 'inner 1 ' ok env lcwd endswith 'here' ok env testval 1 'outer 1 ' eq env lcwd prev lcwd
| null | null | null | null | Question:
What should take other context managers ?
Code:
def test_settings_with_other_context_managers():
env.testval1 = 'outer 1'
prev_lcwd = env.lcwd
with settings(lcd('here'), testval1='inner 1'):
eq_(env.testval1, 'inner 1')
ok_(env.lcwd.endswith('here'))
ok_(env.testval1, 'outer 1')
eq_(env.lcwd, prev_lcwd)
|
null | null | null | What should settings take ?
| def test_settings_with_other_context_managers():
env.testval1 = 'outer 1'
prev_lcwd = env.lcwd
with settings(lcd('here'), testval1='inner 1'):
eq_(env.testval1, 'inner 1')
ok_(env.lcwd.endswith('here'))
ok_(env.testval1, 'outer 1')
eq_(env.lcwd, prev_lcwd)
| null | null | null | other context managers
| codeqa | def test settings with other context managers env testval 1 'outer 1 'prev lcwd env lcwdwith settings lcd 'here' testval 1 'inner 1 ' eq env testval 1 'inner 1 ' ok env lcwd endswith 'here' ok env testval 1 'outer 1 ' eq env lcwd prev lcwd
| null | null | null | null | Question:
What should settings take ?
Code:
def test_settings_with_other_context_managers():
env.testval1 = 'outer 1'
prev_lcwd = env.lcwd
with settings(lcd('here'), testval1='inner 1'):
eq_(env.testval1, 'inner 1')
ok_(env.lcwd.endswith('here'))
ok_(env.testval1, 'outer 1')
eq_(env.lcwd, prev_lcwd)
|
null | null | null | What is containing the owners unique i d ?
| def refresh_lock(lock_file):
unique_id = ('%s_%s_%s' % (os.getpid(), ''.join([str(random.randint(0, 9)) for i in range(10)]), hostname))
try:
with open(lock_file, 'w') as lock_write:
lock_write.write((unique_id + '\n'))
except Exception:
while (get_lock.n_lock > 0):
release_lock()
_logger.warn('Refreshing lock failed, we release the lock before raising again the exception')
raise
return unique_id
| null | null | null | the file
| codeqa | def refresh lock lock file unique id '%s %s %s' % os getpid '' join [str random randint 0 9 for i in range 10 ] hostname try with open lock file 'w' as lock write lock write write unique id + '\n' except Exception while get lock n lock > 0 release lock logger warn ' Refreshinglockfailed wereleasethelockbeforeraisingagaintheexception' raisereturn unique id
| null | null | null | null | Question:
What is containing the owners unique i d ?
Code:
def refresh_lock(lock_file):
unique_id = ('%s_%s_%s' % (os.getpid(), ''.join([str(random.randint(0, 9)) for i in range(10)]), hostname))
try:
with open(lock_file, 'w') as lock_write:
lock_write.write((unique_id + '\n'))
except Exception:
while (get_lock.n_lock > 0):
release_lock()
_logger.warn('Refreshing lock failed, we release the lock before raising again the exception')
raise
return unique_id
|
null | null | null | For what purpose does the score return ?
| def get_score(submissions_scores, csm_scores, persisted_block, block):
weight = _get_weight_from_block(persisted_block, block)
(raw_earned, raw_possible, weighted_earned, weighted_possible, attempted) = (_get_score_from_submissions(submissions_scores, block) or _get_score_from_csm(csm_scores, block, weight) or _get_score_from_persisted_or_latest_block(persisted_block, block, weight))
if ((weighted_possible is None) or (weighted_earned is None)):
return None
else:
has_valid_denominator = (weighted_possible > 0.0)
graded = (_get_graded_from_block(persisted_block, block) if has_valid_denominator else False)
return ProblemScore(raw_earned, raw_possible, weighted_earned, weighted_possible, weight, graded, attempted=attempted)
| null | null | null | for a problem
| codeqa | def get score submissions scores csm scores persisted block block weight get weight from block persisted block block raw earned raw possible weighted earned weighted possible attempted get score from submissions submissions scores block or get score from csm csm scores block weight or get score from persisted or latest block persisted block block weight if weighted possible is None or weighted earned is None return Noneelse has valid denominator weighted possible > 0 0 graded get graded from block persisted block block if has valid denominator else False return Problem Score raw earned raw possible weighted earned weighted possible weight graded attempted attempted
| null | null | null | null | Question:
For what purpose does the score return ?
Code:
def get_score(submissions_scores, csm_scores, persisted_block, block):
weight = _get_weight_from_block(persisted_block, block)
(raw_earned, raw_possible, weighted_earned, weighted_possible, attempted) = (_get_score_from_submissions(submissions_scores, block) or _get_score_from_csm(csm_scores, block, weight) or _get_score_from_persisted_or_latest_block(persisted_block, block, weight))
if ((weighted_possible is None) or (weighted_earned is None)):
return None
else:
has_valid_denominator = (weighted_possible > 0.0)
graded = (_get_graded_from_block(persisted_block, block) if has_valid_denominator else False)
return ProblemScore(raw_earned, raw_possible, weighted_earned, weighted_possible, weight, graded, attempted=attempted)
|
null | null | null | How should it extract two steps ?
| def test_can_parse_regular_step_followed_by_tabular_step():
steps = Step.many_from_lines((I_LIKE_VEGETABLES.splitlines() + I_HAVE_TASTY_BEVERAGES.splitlines()))
assert_equals(len(steps), 2)
assert isinstance(steps[0], Step)
assert isinstance(steps[1], Step)
assert_equals(steps[0].sentence, I_LIKE_VEGETABLES)
assert_equals(steps[1].sentence, string.split(I_HAVE_TASTY_BEVERAGES, '\n')[0])
| null | null | null | correctly
| codeqa | def test can parse regular step followed by tabular step steps Step many from lines I LIKE VEGETABLES splitlines + I HAVE TASTY BEVERAGES splitlines assert equals len steps 2 assert isinstance steps[ 0 ] Step assert isinstance steps[ 1 ] Step assert equals steps[ 0 ] sentence I LIKE VEGETABLES assert equals steps[ 1 ] sentence string split I HAVE TASTY BEVERAGES '\n' [0 ]
| null | null | null | null | Question:
How should it extract two steps ?
Code:
def test_can_parse_regular_step_followed_by_tabular_step():
steps = Step.many_from_lines((I_LIKE_VEGETABLES.splitlines() + I_HAVE_TASTY_BEVERAGES.splitlines()))
assert_equals(len(steps), 2)
assert isinstance(steps[0], Step)
assert isinstance(steps[1], Step)
assert_equals(steps[0].sentence, I_LIKE_VEGETABLES)
assert_equals(steps[1].sentence, string.split(I_HAVE_TASTY_BEVERAGES, '\n')[0])
|
null | null | null | What should it extract correctly ?
| def test_can_parse_regular_step_followed_by_tabular_step():
steps = Step.many_from_lines((I_LIKE_VEGETABLES.splitlines() + I_HAVE_TASTY_BEVERAGES.splitlines()))
assert_equals(len(steps), 2)
assert isinstance(steps[0], Step)
assert isinstance(steps[1], Step)
assert_equals(steps[0].sentence, I_LIKE_VEGETABLES)
assert_equals(steps[1].sentence, string.split(I_HAVE_TASTY_BEVERAGES, '\n')[0])
| null | null | null | two steps
| codeqa | def test can parse regular step followed by tabular step steps Step many from lines I LIKE VEGETABLES splitlines + I HAVE TASTY BEVERAGES splitlines assert equals len steps 2 assert isinstance steps[ 0 ] Step assert isinstance steps[ 1 ] Step assert equals steps[ 0 ] sentence I LIKE VEGETABLES assert equals steps[ 1 ] sentence string split I HAVE TASTY BEVERAGES '\n' [0 ]
| null | null | null | null | Question:
What should it extract correctly ?
Code:
def test_can_parse_regular_step_followed_by_tabular_step():
steps = Step.many_from_lines((I_LIKE_VEGETABLES.splitlines() + I_HAVE_TASTY_BEVERAGES.splitlines()))
assert_equals(len(steps), 2)
assert isinstance(steps[0], Step)
assert isinstance(steps[1], Step)
assert_equals(steps[0].sentence, I_LIKE_VEGETABLES)
assert_equals(steps[1].sentence, string.split(I_HAVE_TASTY_BEVERAGES, '\n')[0])
|
null | null | null | How is the value from x - copy - from header formatted ?
| def _check_copy_from_header(req):
return _check_path_header(req, 'X-Copy-From', 2, 'X-Copy-From header must be of the form <container name>/<object name>')
| null | null | null | well
| codeqa | def check copy from header req return check path header req 'X- Copy- From' 2 'X- Copy- Fromheadermustbeoftheform<containername>/<objectname>'
| null | null | null | null | Question:
How is the value from x - copy - from header formatted ?
Code:
def _check_copy_from_header(req):
return _check_path_header(req, 'X-Copy-From', 2, 'X-Copy-From header must be of the form <container name>/<object name>')
|
null | null | null | How does the code create a decimal instance ?
| def _dec_from_triple(sign, coefficient, exponent, special=False):
self = object.__new__(Decimal)
self._sign = sign
self._int = coefficient
self._exp = exponent
self._is_special = special
return self
| null | null | null | directly
| codeqa | def dec from triple sign coefficient exponent special False self object new Decimal self sign signself int coefficientself exp exponentself is special specialreturn self
| null | null | null | null | Question:
How does the code create a decimal instance ?
Code:
def _dec_from_triple(sign, coefficient, exponent, special=False):
self = object.__new__(Decimal)
self._sign = sign
self._int = coefficient
self._exp = exponent
self._is_special = special
return self
|
null | null | null | What does the code create directly ?
| def _dec_from_triple(sign, coefficient, exponent, special=False):
self = object.__new__(Decimal)
self._sign = sign
self._int = coefficient
self._exp = exponent
self._is_special = special
return self
| null | null | null | a decimal instance
| codeqa | def dec from triple sign coefficient exponent special False self object new Decimal self sign signself int coefficientself exp exponentself is special specialreturn self
| null | null | null | null | Question:
What does the code create directly ?
Code:
def _dec_from_triple(sign, coefficient, exponent, special=False):
self = object.__new__(Decimal)
self._sign = sign
self._int = coefficient
self._exp = exponent
self._is_special = special
return self
|
null | null | null | What does the code compute ?
| def CoefDetermination(ys, res):
return (1 - (Var(res) / Var(ys)))
| null | null | null | the coefficient of determination for given residuals
| codeqa | def Coef Determination ys res return 1 - Var res / Var ys
| null | null | null | null | Question:
What does the code compute ?
Code:
def CoefDetermination(ys, res):
return (1 - (Var(res) / Var(ys)))
|
null | null | null | What do quota enable ?
| def enable_quota_volume(name):
cmd = 'volume quota {0} enable'.format(name)
if (not _gluster(cmd)):
return False
return True
| null | null | null | quota
| codeqa | def enable quota volume name cmd 'volumequota{ 0 }enable' format name if not gluster cmd return Falsereturn True
| null | null | null | null | Question:
What do quota enable ?
Code:
def enable_quota_volume(name):
cmd = 'volume quota {0} enable'.format(name)
if (not _gluster(cmd)):
return False
return True
|
null | null | null | What enable quota ?
| def enable_quota_volume(name):
cmd = 'volume quota {0} enable'.format(name)
if (not _gluster(cmd)):
return False
return True
| null | null | null | quota
| codeqa | def enable quota volume name cmd 'volumequota{ 0 }enable' format name if not gluster cmd return Falsereturn True
| null | null | null | null | Question:
What enable quota ?
Code:
def enable_quota_volume(name):
cmd = 'volume quota {0} enable'.format(name)
if (not _gluster(cmd)):
return False
return True
|
null | null | null | What does the code remove ?
| def remove_jacket(container):
name = find_existing_jacket(container)
if (name is not None):
remove_jacket_images(container, name)
container.remove_item(name)
return True
return False
| null | null | null | an existing jacket
| codeqa | def remove jacket container name find existing jacket container if name is not None remove jacket images container name container remove item name return Truereturn False
| null | null | null | null | Question:
What does the code remove ?
Code:
def remove_jacket(container):
name = find_existing_jacket(container)
if (name is not None):
remove_jacket_images(container, name)
container.remove_item(name)
return True
return False
|
null | null | null | What does the code get from name ?
| def getfqdn(name=''):
name = name.strip()
if ((not name) or (name == '0.0.0.0')):
name = gethostname()
try:
(hostname, aliases, ipaddrs) = gethostbyaddr(name)
except error:
pass
else:
aliases.insert(0, hostname)
for name in aliases:
if ('.' in name):
break
else:
name = hostname
return name
| null | null | null | fully qualified domain name
| codeqa | def getfqdn name '' name name strip if not name or name '0 0 0 0' name gethostname try hostname aliases ipaddrs gethostbyaddr name except error passelse aliases insert 0 hostname for name in aliases if ' ' in name breakelse name hostnamereturn name
| null | null | null | null | Question:
What does the code get from name ?
Code:
def getfqdn(name=''):
name = name.strip()
if ((not name) or (name == '0.0.0.0')):
name = gethostname()
try:
(hostname, aliases, ipaddrs) = gethostbyaddr(name)
except error:
pass
else:
aliases.insert(0, hostname)
for name in aliases:
if ('.' in name):
break
else:
name = hostname
return name
|
null | null | null | What does the code ensure ?
| def _is_vdi_a_snapshot(vdi_rec):
is_a_snapshot = vdi_rec['is_a_snapshot']
image_id = vdi_rec['other_config'].get('image-id')
return (is_a_snapshot and (not image_id))
| null | null | null | vdi is a snapshot
| codeqa | def is vdi a snapshot vdi rec is a snapshot vdi rec['is a snapshot']image id vdi rec['other config'] get 'image-id' return is a snapshot and not image id
| null | null | null | null | Question:
What does the code ensure ?
Code:
def _is_vdi_a_snapshot(vdi_rec):
is_a_snapshot = vdi_rec['is_a_snapshot']
image_id = vdi_rec['other_config'].get('image-id')
return (is_a_snapshot and (not image_id))
|
null | null | null | What does the code initialize ?
| def init_parser():
parser = argparse.ArgumentParser(description='Checks if any upgrade is required and runs the script for the process.')
parser.add_argument('--keyname', help='The deployment keyname')
parser.add_argument('--log-postfix', help='An identifier for the status log')
parser.add_argument('--db-master', required=True, help='The IP address of the DB master')
parser.add_argument('--zookeeper', nargs='+', help='A list of ZooKeeper IP addresses')
parser.add_argument('--database', nargs='+', help='A list of DB IP addresses')
parser.add_argument('--replication', type=int, help='The keyspace replication factor')
return parser
| null | null | null | the command line argument parser
| codeqa | def init parser parser argparse Argument Parser description ' Checksifanyupgradeisrequiredandrunsthescriptfortheprocess ' parser add argument '--keyname' help ' Thedeploymentkeyname' parser add argument '--log-postfix' help ' Anidentifierforthestatuslog' parser add argument '--db-master' required True help ' The I Paddressofthe D Bmaster' parser add argument '--zookeeper' nargs '+' help ' Alistof Zoo Keeper I Paddresses' parser add argument '--database' nargs '+' help ' Alistof DBI Paddresses' parser add argument '--replication' type int help ' Thekeyspacereplicationfactor' return parser
| null | null | null | null | Question:
What does the code initialize ?
Code:
def init_parser():
parser = argparse.ArgumentParser(description='Checks if any upgrade is required and runs the script for the process.')
parser.add_argument('--keyname', help='The deployment keyname')
parser.add_argument('--log-postfix', help='An identifier for the status log')
parser.add_argument('--db-master', required=True, help='The IP address of the DB master')
parser.add_argument('--zookeeper', nargs='+', help='A list of ZooKeeper IP addresses')
parser.add_argument('--database', nargs='+', help='A list of DB IP addresses')
parser.add_argument('--replication', type=int, help='The keyspace replication factor')
return parser
|
null | null | null | How be the object referenced ?
| def safeRef(target, onDelete=None):
if hasattr(target, 'im_self'):
if (target.im_self is not None):
assert hasattr(target, 'im_func'), ("safeRef target %r has im_self, but no im_func, don't know how to create reference" % (target,))
reference = get_bound_method_weakref(target=target, onDelete=onDelete)
return reference
if callable(onDelete):
return weakref.ref(target, onDelete)
else:
return weakref.ref(target)
| null | null | null | weakly
| codeqa | def safe Ref target on Delete None if hasattr target 'im self' if target im self is not None assert hasattr target 'im func' "safe Reftarget%rhasim self butnoim func don'tknowhowtocreatereference" % target reference get bound method weakref target target on Delete on Delete return referenceif callable on Delete return weakref ref target on Delete else return weakref ref target
| null | null | null | null | Question:
How be the object referenced ?
Code:
def safeRef(target, onDelete=None):
if hasattr(target, 'im_self'):
if (target.im_self is not None):
assert hasattr(target, 'im_func'), ("safeRef target %r has im_self, but no im_func, don't know how to create reference" % (target,))
reference = get_bound_method_weakref(target=target, onDelete=onDelete)
return reference
if callable(onDelete):
return weakref.ref(target, onDelete)
else:
return weakref.ref(target)
|
null | null | null | How is the longest subsequence increasing ?
| def longest_increasing_subseq(seq):
if (not seq):
return []
head = [0]
predecessor = [(-1)]
for i in range(1, len(seq)):
j = bisect_left([seq[head[idx]] for idx in range(len(head))], seq[i])
if (j == len(head)):
head.append(i)
if (seq[i] < seq[head[j]]):
head[j] = i
predecessor.append((head[(j - 1)] if (j > 0) else (-1)))
result = []
trace_idx = head[(-1)]
while (trace_idx >= 0):
result.append(seq[trace_idx])
trace_idx = predecessor[trace_idx]
return result[::(-1)]
| null | null | null | strictly
| codeqa | def longest increasing subseq seq if not seq return []head [0 ]predecessor [ -1 ]for i in range 1 len seq j bisect left [seq[head[idx]] for idx in range len head ] seq[i] if j len head head append i if seq[i] < seq[head[j]] head[j] ipredecessor append head[ j - 1 ] if j > 0 else -1 result []trace idx head[ -1 ]while trace idx > 0 result append seq[trace idx] trace idx predecessor[trace idx]return result[ -1 ]
| null | null | null | null | Question:
How is the longest subsequence increasing ?
Code:
def longest_increasing_subseq(seq):
if (not seq):
return []
head = [0]
predecessor = [(-1)]
for i in range(1, len(seq)):
j = bisect_left([seq[head[idx]] for idx in range(len(head))], seq[i])
if (j == len(head)):
head.append(i)
if (seq[i] < seq[head[j]]):
head[j] = i
predecessor.append((head[(j - 1)] if (j > 0) else (-1)))
result = []
trace_idx = head[(-1)]
while (trace_idx >= 0):
result.append(seq[trace_idx])
trace_idx = predecessor[trace_idx]
return result[::(-1)]
|
null | null | null | What runs the user ?
| def reinstall_ruby(ruby, runas=None):
return _rvm(['reinstall', ruby], runas=runas)
| null | null | null | rvm
| codeqa | def reinstall ruby ruby runas None return rvm ['reinstall' ruby] runas runas
| null | null | null | null | Question:
What runs the user ?
Code:
def reinstall_ruby(ruby, runas=None):
return _rvm(['reinstall', ruby], runas=runas)
|
null | null | null | What does the code calculate ?
| def _logn(n, x, out=None):
if (out is None):
return (np.log(x) / np.log(n))
else:
np.log(x, out=out)
np.true_divide(out, np.log(n), out=out)
return out
| null | null | null | the log base n of x
| codeqa | def logn n x out None if out is None return np log x / np log n else np log x out out np true divide out np log n out out return out
| null | null | null | null | Question:
What does the code calculate ?
Code:
def _logn(n, x, out=None):
if (out is None):
return (np.log(x) / np.log(n))
else:
np.log(x, out=out)
np.true_divide(out, np.log(n), out=out)
return out
|
null | null | null | What does the code raise if $ home is specified ?
| @with_environment
def test_get_home_dir_5():
env['HOME'] = abspath((HOME_TEST_DIR + 'garbage'))
os.name = 'posix'
nt.assert_raises(path.HomeDirError, path.get_home_dir, True)
| null | null | null | homedirerror
| codeqa | @with environmentdef test get home dir 5 env['HOME'] abspath HOME TEST DIR + 'garbage' os name 'posix'nt assert raises path Home Dir Error path get home dir True
| null | null | null | null | Question:
What does the code raise if $ home is specified ?
Code:
@with_environment
def test_get_home_dir_5():
env['HOME'] = abspath((HOME_TEST_DIR + 'garbage'))
os.name = 'posix'
nt.assert_raises(path.HomeDirError, path.get_home_dir, True)
|
null | null | null | What be added in the filter file ?
| def _AppendFiltersForMSBuild(parent_filter_name, sources, rule_dependencies, extension_to_rule_name, filter_group, source_group):
for source in sources:
if isinstance(source, MSVSProject.Filter):
if (not parent_filter_name):
filter_name = source.name
else:
filter_name = ('%s\\%s' % (parent_filter_name, source.name))
filter_group.append(['Filter', {'Include': filter_name}, ['UniqueIdentifier', MSVSNew.MakeGuid(source.name)]])
_AppendFiltersForMSBuild(filter_name, source.contents, rule_dependencies, extension_to_rule_name, filter_group, source_group)
else:
(_, element) = _MapFileToMsBuildSourceType(source, rule_dependencies, extension_to_rule_name)
source_entry = [element, {'Include': source}]
if parent_filter_name:
source_entry.append(['Filter', parent_filter_name])
source_group.append(source_entry)
| null | null | null | the list of filters and sources
| codeqa | def Append Filters For MS Build parent filter name sources rule dependencies extension to rule name filter group source group for source in sources if isinstance source MSVS Project Filter if not parent filter name filter name source nameelse filter name '%s\\%s' % parent filter name source name filter group append [' Filter' {' Include' filter name} [' Unique Identifier' MSVS New Make Guid source name ]] Append Filters For MS Build filter name source contents rule dependencies extension to rule name filter group source group else element Map File To Ms Build Source Type source rule dependencies extension to rule name source entry [element {' Include' source}]if parent filter name source entry append [' Filter' parent filter name] source group append source entry
| null | null | null | null | Question:
What be added in the filter file ?
Code:
def _AppendFiltersForMSBuild(parent_filter_name, sources, rule_dependencies, extension_to_rule_name, filter_group, source_group):
for source in sources:
if isinstance(source, MSVSProject.Filter):
if (not parent_filter_name):
filter_name = source.name
else:
filter_name = ('%s\\%s' % (parent_filter_name, source.name))
filter_group.append(['Filter', {'Include': filter_name}, ['UniqueIdentifier', MSVSNew.MakeGuid(source.name)]])
_AppendFiltersForMSBuild(filter_name, source.contents, rule_dependencies, extension_to_rule_name, filter_group, source_group)
else:
(_, element) = _MapFileToMsBuildSourceType(source, rule_dependencies, extension_to_rule_name)
source_entry = [element, {'Include': source}]
if parent_filter_name:
source_entry.append(['Filter', parent_filter_name])
source_group.append(source_entry)
|
null | null | null | What does the code create ?
| def _AppendFiltersForMSBuild(parent_filter_name, sources, rule_dependencies, extension_to_rule_name, filter_group, source_group):
for source in sources:
if isinstance(source, MSVSProject.Filter):
if (not parent_filter_name):
filter_name = source.name
else:
filter_name = ('%s\\%s' % (parent_filter_name, source.name))
filter_group.append(['Filter', {'Include': filter_name}, ['UniqueIdentifier', MSVSNew.MakeGuid(source.name)]])
_AppendFiltersForMSBuild(filter_name, source.contents, rule_dependencies, extension_to_rule_name, filter_group, source_group)
else:
(_, element) = _MapFileToMsBuildSourceType(source, rule_dependencies, extension_to_rule_name)
source_entry = [element, {'Include': source}]
if parent_filter_name:
source_entry.append(['Filter', parent_filter_name])
source_group.append(source_entry)
| null | null | null | the list of filters and sources to be added in the filter file
| codeqa | def Append Filters For MS Build parent filter name sources rule dependencies extension to rule name filter group source group for source in sources if isinstance source MSVS Project Filter if not parent filter name filter name source nameelse filter name '%s\\%s' % parent filter name source name filter group append [' Filter' {' Include' filter name} [' Unique Identifier' MSVS New Make Guid source name ]] Append Filters For MS Build filter name source contents rule dependencies extension to rule name filter group source group else element Map File To Ms Build Source Type source rule dependencies extension to rule name source entry [element {' Include' source}]if parent filter name source entry append [' Filter' parent filter name] source group append source entry
| null | null | null | null | Question:
What does the code create ?
Code:
def _AppendFiltersForMSBuild(parent_filter_name, sources, rule_dependencies, extension_to_rule_name, filter_group, source_group):
for source in sources:
if isinstance(source, MSVSProject.Filter):
if (not parent_filter_name):
filter_name = source.name
else:
filter_name = ('%s\\%s' % (parent_filter_name, source.name))
filter_group.append(['Filter', {'Include': filter_name}, ['UniqueIdentifier', MSVSNew.MakeGuid(source.name)]])
_AppendFiltersForMSBuild(filter_name, source.contents, rule_dependencies, extension_to_rule_name, filter_group, source_group)
else:
(_, element) = _MapFileToMsBuildSourceType(source, rule_dependencies, extension_to_rule_name)
source_entry = [element, {'Include': source}]
if parent_filter_name:
source_entry.append(['Filter', parent_filter_name])
source_group.append(source_entry)
|
null | null | null | Where be the list of filters and sources added ?
| def _AppendFiltersForMSBuild(parent_filter_name, sources, rule_dependencies, extension_to_rule_name, filter_group, source_group):
for source in sources:
if isinstance(source, MSVSProject.Filter):
if (not parent_filter_name):
filter_name = source.name
else:
filter_name = ('%s\\%s' % (parent_filter_name, source.name))
filter_group.append(['Filter', {'Include': filter_name}, ['UniqueIdentifier', MSVSNew.MakeGuid(source.name)]])
_AppendFiltersForMSBuild(filter_name, source.contents, rule_dependencies, extension_to_rule_name, filter_group, source_group)
else:
(_, element) = _MapFileToMsBuildSourceType(source, rule_dependencies, extension_to_rule_name)
source_entry = [element, {'Include': source}]
if parent_filter_name:
source_entry.append(['Filter', parent_filter_name])
source_group.append(source_entry)
| null | null | null | in the filter file
| codeqa | def Append Filters For MS Build parent filter name sources rule dependencies extension to rule name filter group source group for source in sources if isinstance source MSVS Project Filter if not parent filter name filter name source nameelse filter name '%s\\%s' % parent filter name source name filter group append [' Filter' {' Include' filter name} [' Unique Identifier' MSVS New Make Guid source name ]] Append Filters For MS Build filter name source contents rule dependencies extension to rule name filter group source group else element Map File To Ms Build Source Type source rule dependencies extension to rule name source entry [element {' Include' source}]if parent filter name source entry append [' Filter' parent filter name] source group append source entry
| null | null | null | null | Question:
Where be the list of filters and sources added ?
Code:
def _AppendFiltersForMSBuild(parent_filter_name, sources, rule_dependencies, extension_to_rule_name, filter_group, source_group):
for source in sources:
if isinstance(source, MSVSProject.Filter):
if (not parent_filter_name):
filter_name = source.name
else:
filter_name = ('%s\\%s' % (parent_filter_name, source.name))
filter_group.append(['Filter', {'Include': filter_name}, ['UniqueIdentifier', MSVSNew.MakeGuid(source.name)]])
_AppendFiltersForMSBuild(filter_name, source.contents, rule_dependencies, extension_to_rule_name, filter_group, source_group)
else:
(_, element) = _MapFileToMsBuildSourceType(source, rule_dependencies, extension_to_rule_name)
source_entry = [element, {'Include': source}]
if parent_filter_name:
source_entry.append(['Filter', parent_filter_name])
source_group.append(source_entry)
|
null | null | null | What can windows not encode ?
| def _clean_win_chars(string):
import urllib
if hasattr(urllib, 'quote'):
quote = urllib.quote
else:
import urllib.parse
quote = urllib.parse.quote
for char in ('<', '>', '!', ':', '\\'):
string = string.replace(char, quote(char))
return string
| null | null | null | some characters in filename
| codeqa | def clean win chars string import urllibif hasattr urllib 'quote' quote urllib quoteelse import urllib parsequote urllib parse quotefor char in '<' '>' ' ' ' ' '\\' string string replace char quote char return string
| null | null | null | null | Question:
What can windows not encode ?
Code:
def _clean_win_chars(string):
import urllib
if hasattr(urllib, 'quote'):
quote = urllib.quote
else:
import urllib.parse
quote = urllib.parse.quote
for char in ('<', '>', '!', ':', '\\'):
string = string.replace(char, quote(char))
return string
|
null | null | null | Can windows encode some characters in filename ?
| def _clean_win_chars(string):
import urllib
if hasattr(urllib, 'quote'):
quote = urllib.quote
else:
import urllib.parse
quote = urllib.parse.quote
for char in ('<', '>', '!', ':', '\\'):
string = string.replace(char, quote(char))
return string
| null | null | null | No
| codeqa | def clean win chars string import urllibif hasattr urllib 'quote' quote urllib quoteelse import urllib parsequote urllib parse quotefor char in '<' '>' ' ' ' ' '\\' string string replace char quote char return string
| null | null | null | null | Question:
Can windows encode some characters in filename ?
Code:
def _clean_win_chars(string):
import urllib
if hasattr(urllib, 'quote'):
quote = urllib.quote
else:
import urllib.parse
quote = urllib.parse.quote
for char in ('<', '>', '!', ':', '\\'):
string = string.replace(char, quote(char))
return string
|
null | null | null | What can not encode some characters in filename ?
| def _clean_win_chars(string):
import urllib
if hasattr(urllib, 'quote'):
quote = urllib.quote
else:
import urllib.parse
quote = urllib.parse.quote
for char in ('<', '>', '!', ':', '\\'):
string = string.replace(char, quote(char))
return string
| null | null | null | windows
| codeqa | def clean win chars string import urllibif hasattr urllib 'quote' quote urllib quoteelse import urllib parsequote urllib parse quotefor char in '<' '>' ' ' ' ' '\\' string string replace char quote char return string
| null | null | null | null | Question:
What can not encode some characters in filename ?
Code:
def _clean_win_chars(string):
import urllib
if hasattr(urllib, 'quote'):
quote = urllib.quote
else:
import urllib.parse
quote = urllib.parse.quote
for char in ('<', '>', '!', ':', '\\'):
string = string.replace(char, quote(char))
return string
|
null | null | null | What does the code convert into a comma separated string ?
| def format_value(value):
if isinstance(value, list):
value = u', '.join([v.strip() for v in value])
return value
| null | null | null | a list
| codeqa | def format value value if isinstance value list value u' ' join [v strip for v in value] return value
| null | null | null | null | Question:
What does the code convert into a comma separated string ?
Code:
def format_value(value):
if isinstance(value, list):
value = u', '.join([v.strip() for v in value])
return value
|
null | null | null | What does the code return ?
| def encrypt_string(s, key=''):
key += ' '
s = encode_utf8(s)
a = []
for i in xrange(len(s)):
try:
a.append(chr((ord(s[i]) + (ord(key[(i % len(key))]) % 256))))
except:
raise EncryptionError()
s = ''.join(a)
s = base64.urlsafe_b64encode(s)
return s
| null | null | null | the given string
| codeqa | def encrypt string s key '' key + ''s encode utf 8 s a []for i in xrange len s try a append chr ord s[i] + ord key[ i % len key ] % 256 except raise Encryption Error s '' join a s base 64 urlsafe b64 encode s return s
| null | null | null | null | Question:
What does the code return ?
Code:
def encrypt_string(s, key=''):
key += ' '
s = encode_utf8(s)
a = []
for i in xrange(len(s)):
try:
a.append(chr((ord(s[i]) + (ord(key[(i % len(key))]) % 256))))
except:
raise EncryptionError()
s = ''.join(a)
s = base64.urlsafe_b64encode(s)
return s
|
null | null | null | What does the code get ?
| def getmodetype(mode):
return ImageMode.getmode(mode).basetype
| null | null | null | the storage type mode
| codeqa | def getmodetype mode return Image Mode getmode mode basetype
| null | null | null | null | Question:
What does the code get ?
Code:
def getmodetype(mode):
return ImageMode.getmode(mode).basetype
|
null | null | null | What does the code convert to start ?
| def slice2gridspec(key):
if ((len(key) != 2) or (not isinstance(key[0], slice)) or (not isinstance(key[1], slice))):
raise ValueError('only 2-D slices, please')
x0 = key[1].start
x1 = key[1].stop
xstep = key[1].step
if ((not isinstance(xstep, complex)) or (int(xstep.real) != xstep.real)):
raise ValueError('only the [start:stop:numsteps*1j] form supported')
xstep = int(xstep.imag)
y0 = key[0].start
y1 = key[0].stop
ystep = key[0].step
if ((not isinstance(ystep, complex)) or (int(ystep.real) != ystep.real)):
raise ValueError('only the [start:stop:numsteps*1j] form supported')
ystep = int(ystep.imag)
return (x0, x1, xstep, y0, y1, ystep)
| null | null | null | a 2-tuple of slices
| codeqa | def slice 2 gridspec key if len key 2 or not isinstance key[ 0 ] slice or not isinstance key[ 1 ] slice raise Value Error 'only 2 - Dslices please' x0 key[ 1 ] startx 1 key[ 1 ] stopxstep key[ 1 ] stepif not isinstance xstep complex or int xstep real xstep real raise Value Error 'onlythe[start stop numsteps* 1 j]formsupported' xstep int xstep imag y0 key[ 0 ] starty 1 key[ 0 ] stopystep key[ 0 ] stepif not isinstance ystep complex or int ystep real ystep real raise Value Error 'onlythe[start stop numsteps* 1 j]formsupported' ystep int ystep imag return x0 x1 xstep y0 y1 ystep
| null | null | null | null | Question:
What does the code convert to start ?
Code:
def slice2gridspec(key):
if ((len(key) != 2) or (not isinstance(key[0], slice)) or (not isinstance(key[1], slice))):
raise ValueError('only 2-D slices, please')
x0 = key[1].start
x1 = key[1].stop
xstep = key[1].step
if ((not isinstance(xstep, complex)) or (int(xstep.real) != xstep.real)):
raise ValueError('only the [start:stop:numsteps*1j] form supported')
xstep = int(xstep.imag)
y0 = key[0].start
y1 = key[0].stop
ystep = key[0].step
if ((not isinstance(ystep, complex)) or (int(ystep.real) != ystep.real)):
raise ValueError('only the [start:stop:numsteps*1j] form supported')
ystep = int(ystep.imag)
return (x0, x1, xstep, y0, y1, ystep)
|
null | null | null | For what purpose does the code convert a 2-tuple of slices ?
| def slice2gridspec(key):
if ((len(key) != 2) or (not isinstance(key[0], slice)) or (not isinstance(key[1], slice))):
raise ValueError('only 2-D slices, please')
x0 = key[1].start
x1 = key[1].stop
xstep = key[1].step
if ((not isinstance(xstep, complex)) or (int(xstep.real) != xstep.real)):
raise ValueError('only the [start:stop:numsteps*1j] form supported')
xstep = int(xstep.imag)
y0 = key[0].start
y1 = key[0].stop
ystep = key[0].step
if ((not isinstance(ystep, complex)) or (int(ystep.real) != ystep.real)):
raise ValueError('only the [start:stop:numsteps*1j] form supported')
ystep = int(ystep.imag)
return (x0, x1, xstep, y0, y1, ystep)
| null | null | null | to start
| codeqa | def slice 2 gridspec key if len key 2 or not isinstance key[ 0 ] slice or not isinstance key[ 1 ] slice raise Value Error 'only 2 - Dslices please' x0 key[ 1 ] startx 1 key[ 1 ] stopxstep key[ 1 ] stepif not isinstance xstep complex or int xstep real xstep real raise Value Error 'onlythe[start stop numsteps* 1 j]formsupported' xstep int xstep imag y0 key[ 0 ] starty 1 key[ 0 ] stopystep key[ 0 ] stepif not isinstance ystep complex or int ystep real ystep real raise Value Error 'onlythe[start stop numsteps* 1 j]formsupported' ystep int ystep imag return x0 x1 xstep y0 y1 ystep
| null | null | null | null | Question:
For what purpose does the code convert a 2-tuple of slices ?
Code:
def slice2gridspec(key):
if ((len(key) != 2) or (not isinstance(key[0], slice)) or (not isinstance(key[1], slice))):
raise ValueError('only 2-D slices, please')
x0 = key[1].start
x1 = key[1].stop
xstep = key[1].step
if ((not isinstance(xstep, complex)) or (int(xstep.real) != xstep.real)):
raise ValueError('only the [start:stop:numsteps*1j] form supported')
xstep = int(xstep.imag)
y0 = key[0].start
y1 = key[0].stop
ystep = key[0].step
if ((not isinstance(ystep, complex)) or (int(ystep.real) != ystep.real)):
raise ValueError('only the [start:stop:numsteps*1j] form supported')
ystep = int(ystep.imag)
return (x0, x1, xstep, y0, y1, ystep)
|
null | null | null | How be which be visible to menus ?
| def inv_recv_crud_strings():
T = current.T
if (current.deployment_settings.get_inv_shipment_name() == 'order'):
ADD_RECV = T('Add Order')
current.response.s3.crud_strings['inv_recv'] = Storage(label_create=ADD_RECV, title_display=T('Order Details'), title_list=T('Orders'), title_update=T('Edit Order'), label_list_button=T('List Orders'), label_delete_button=T('Delete Order'), msg_record_created=T('Order Created'), msg_record_modified=T('Order updated'), msg_record_deleted=T('Order canceled'), msg_list_empty=T('No Orders registered'))
else:
ADD_RECV = T('Receive New Shipment')
current.response.s3.crud_strings['inv_recv'] = Storage(label_create=ADD_RECV, title_display=T('Received Shipment Details'), title_list=T('Received/Incoming Shipments'), title_update=T('Shipment to Receive'), label_list_button=T('List Received/Incoming Shipments'), label_delete_button=T('Delete Received Shipment'), msg_record_created=T('Shipment Created'), msg_record_modified=T('Received Shipment updated'), msg_record_deleted=T('Received Shipment canceled'), msg_list_empty=T('No Received Shipments'))
return
| null | null | null | without a model load
| codeqa | def inv recv crud strings T current Tif current deployment settings get inv shipment name 'order' ADD RECV T ' Add Order' current response s3 crud strings['inv recv'] Storage label create ADD RECV title display T ' Order Details' title list T ' Orders' title update T ' Edit Order' label list button T ' List Orders' label delete button T ' Delete Order' msg record created T ' Order Created' msg record modified T ' Orderupdated' msg record deleted T ' Ordercanceled' msg list empty T ' No Ordersregistered' else ADD RECV T ' Receive New Shipment' current response s3 crud strings['inv recv'] Storage label create ADD RECV title display T ' Received Shipment Details' title list T ' Received/ Incoming Shipments' title update T ' Shipmentto Receive' label list button T ' List Received/ Incoming Shipments' label delete button T ' Delete Received Shipment' msg record created T ' Shipment Created' msg record modified T ' Received Shipmentupdated' msg record deleted T ' Received Shipmentcanceled' msg list empty T ' No Received Shipments' return
| null | null | null | null | Question:
How be which be visible to menus ?
Code:
def inv_recv_crud_strings():
T = current.T
if (current.deployment_settings.get_inv_shipment_name() == 'order'):
ADD_RECV = T('Add Order')
current.response.s3.crud_strings['inv_recv'] = Storage(label_create=ADD_RECV, title_display=T('Order Details'), title_list=T('Orders'), title_update=T('Edit Order'), label_list_button=T('List Orders'), label_delete_button=T('Delete Order'), msg_record_created=T('Order Created'), msg_record_modified=T('Order updated'), msg_record_deleted=T('Order canceled'), msg_list_empty=T('No Orders registered'))
else:
ADD_RECV = T('Receive New Shipment')
current.response.s3.crud_strings['inv_recv'] = Storage(label_create=ADD_RECV, title_display=T('Received Shipment Details'), title_list=T('Received/Incoming Shipments'), title_update=T('Shipment to Receive'), label_list_button=T('List Received/Incoming Shipments'), label_delete_button=T('Delete Received Shipment'), msg_record_created=T('Shipment Created'), msg_record_modified=T('Received Shipment updated'), msg_record_deleted=T('Received Shipment canceled'), msg_list_empty=T('No Received Shipments'))
return
|
null | null | null | By how much did future statement form ?
| def is_future(stmt):
if (not isinstance(stmt, ast.From)):
return 0
if (stmt.modname == '__future__'):
return 1
else:
return 0
| null | null | null | well
| codeqa | def is future stmt if not isinstance stmt ast From return 0if stmt modname ' future ' return 1else return 0
| null | null | null | null | Question:
By how much did future statement form ?
Code:
def is_future(stmt):
if (not isinstance(stmt, ast.From)):
return 0
if (stmt.modname == '__future__'):
return 1
else:
return 0
|
null | null | null | What keeps one value from each iterable in memory only ?
| def merge_sorted(*seqs, **kwargs):
key = kwargs.get('key', None)
if (key is None):
return heapq.merge(*seqs)
else:
return _merge_sorted_key(seqs, key)
| null | null | null | this
| codeqa | def merge sorted *seqs **kwargs key kwargs get 'key' None if key is None return heapq merge *seqs else return merge sorted key seqs key
| null | null | null | null | Question:
What keeps one value from each iterable in memory only ?
Code:
def merge_sorted(*seqs, **kwargs):
key = kwargs.get('key', None)
if (key is None):
return heapq.merge(*seqs)
else:
return _merge_sorted_key(seqs, key)
|
null | null | null | How does this work ?
| def merge_sorted(*seqs, **kwargs):
key = kwargs.get('key', None)
if (key is None):
return heapq.merge(*seqs)
else:
return _merge_sorted_key(seqs, key)
| null | null | null | lazily
| codeqa | def merge sorted *seqs **kwargs key kwargs get 'key' None if key is None return heapq merge *seqs else return merge sorted key seqs key
| null | null | null | null | Question:
How does this work ?
Code:
def merge_sorted(*seqs, **kwargs):
key = kwargs.get('key', None)
if (key is None):
return heapq.merge(*seqs)
else:
return _merge_sorted_key(seqs, key)
|
null | null | null | What did the code use ?
| def get_features(app_module):
app_dir = get_app_dir(app_module)
features_dir = os.path.abspath(os.path.join(app_dir, 'features'))
if os.path.isdir(features_dir):
return features_dir
else:
return None
| null | null | null | to find feature directories for behave tests
| codeqa | def get features app module app dir get app dir app module features dir os path abspath os path join app dir 'features' if os path isdir features dir return features direlse return None
| null | null | null | null | Question:
What did the code use ?
Code:
def get_features(app_module):
app_dir = get_app_dir(app_module)
features_dir = os.path.abspath(os.path.join(app_dir, 'features'))
if os.path.isdir(features_dir):
return features_dir
else:
return None
|
null | null | null | How do two dictionaries merge ?
| def mergedefaults(d1, d2):
for k in d2:
if ((k in d1) and isinstance(d1[k], dict) and isinstance(d2[k], dict)):
mergedefaults(d1[k], d2[k])
else:
d1.setdefault(k, d2[k])
| null | null | null | recursively
| codeqa | def mergedefaults d1 d2 for k in d2 if k in d1 and isinstance d1 [k] dict and isinstance d2 [k] dict mergedefaults d1 [k] d2 [k] else d1 setdefault k d2 [k]
| null | null | null | null | Question:
How do two dictionaries merge ?
Code:
def mergedefaults(d1, d2):
for k in d2:
if ((k in d1) and isinstance(d1[k], dict) and isinstance(d2[k], dict)):
mergedefaults(d1[k], d2[k])
else:
d1.setdefault(k, d2[k])
|
null | null | null | What does return power want tuple t tuple t ?
| def pow_mid(p, max_denom=1024):
assert (0 < p < 1)
p = Fraction(p).limit_denominator(max_denom)
return (p, (p, (1 - p)))
| null | null | null | the epigraph variable t
| codeqa | def pow mid p max denom 1024 assert 0 < p < 1 p Fraction p limit denominator max denom return p p 1 - p
| null | null | null | null | Question:
What does return power want tuple t tuple t ?
Code:
def pow_mid(p, max_denom=1024):
assert (0 < p < 1)
p = Fraction(p).limit_denominator(max_denom)
return (p, (p, (1 - p)))
|
null | null | null | What wants the epigraph variable t tuple t tuple t ?
| def pow_mid(p, max_denom=1024):
assert (0 < p < 1)
p = Fraction(p).limit_denominator(max_denom)
return (p, (p, (1 - p)))
| null | null | null | return power
| codeqa | def pow mid p max denom 1024 assert 0 < p < 1 p Fraction p limit denominator max denom return p p 1 - p
| null | null | null | null | Question:
What wants the epigraph variable t tuple t tuple t ?
Code:
def pow_mid(p, max_denom=1024):
assert (0 < p < 1)
p = Fraction(p).limit_denominator(max_denom)
return (p, (p, (1 - p)))
|
null | null | null | How do input have full precision also ?
| def test_precision_epoch():
t_utc = Time(range(1980, 2001), format='jyear', scale='utc')
t_tai = Time(range(1980, 2001), format='jyear', scale='tai')
dt = (t_utc - t_tai)
assert allclose_sec(dt.sec, np.round(dt.sec))
| null | null | null | via epoch
| codeqa | def test precision epoch t utc Time range 1980 2001 format 'jyear' scale 'utc' t tai Time range 1980 2001 format 'jyear' scale 'tai' dt t utc - t tai assert allclose sec dt sec np round dt sec
| null | null | null | null | Question:
How do input have full precision also ?
Code:
def test_precision_epoch():
t_utc = Time(range(1980, 2001), format='jyear', scale='utc')
t_tai = Time(range(1980, 2001), format='jyear', scale='tai')
dt = (t_utc - t_tai)
assert allclose_sec(dt.sec, np.round(dt.sec))
|
null | null | null | How has that input check ?
| def test_precision_epoch():
t_utc = Time(range(1980, 2001), format='jyear', scale='utc')
t_tai = Time(range(1980, 2001), format='jyear', scale='tai')
dt = (t_utc - t_tai)
assert allclose_sec(dt.sec, np.round(dt.sec))
| null | null | null | via epoch also has full precision
| codeqa | def test precision epoch t utc Time range 1980 2001 format 'jyear' scale 'utc' t tai Time range 1980 2001 format 'jyear' scale 'tai' dt t utc - t tai assert allclose sec dt sec np round dt sec
| null | null | null | null | Question:
How has that input check ?
Code:
def test_precision_epoch():
t_utc = Time(range(1980, 2001), format='jyear', scale='utc')
t_tai = Time(range(1980, 2001), format='jyear', scale='tai')
dt = (t_utc - t_tai)
assert allclose_sec(dt.sec, np.round(dt.sec))
|
null | null | null | What do input have also via epoch ?
| def test_precision_epoch():
t_utc = Time(range(1980, 2001), format='jyear', scale='utc')
t_tai = Time(range(1980, 2001), format='jyear', scale='tai')
dt = (t_utc - t_tai)
assert allclose_sec(dt.sec, np.round(dt.sec))
| null | null | null | full precision
| codeqa | def test precision epoch t utc Time range 1980 2001 format 'jyear' scale 'utc' t tai Time range 1980 2001 format 'jyear' scale 'tai' dt t utc - t tai assert allclose sec dt sec np round dt sec
| null | null | null | null | Question:
What do input have also via epoch ?
Code:
def test_precision_epoch():
t_utc = Time(range(1980, 2001), format='jyear', scale='utc')
t_tai = Time(range(1980, 2001), format='jyear', scale='tai')
dt = (t_utc - t_tai)
assert allclose_sec(dt.sec, np.round(dt.sec))
|
null | null | null | What does the code get ?
| def libvlc_audio_get_channel(p_mi):
f = (_Cfunctions.get('libvlc_audio_get_channel', None) or _Cfunction('libvlc_audio_get_channel', ((1,),), None, ctypes.c_int, MediaPlayer))
return f(p_mi)
| null | null | null | current audio channel
| codeqa | def libvlc audio get channel p mi f Cfunctions get 'libvlc audio get channel' None or Cfunction 'libvlc audio get channel' 1 None ctypes c int Media Player return f p mi
| null | null | null | null | Question:
What does the code get ?
Code:
def libvlc_audio_get_channel(p_mi):
f = (_Cfunctions.get('libvlc_audio_get_channel', None) or _Cfunction('libvlc_audio_get_channel', ((1,),), None, ctypes.c_int, MediaPlayer))
return f(p_mi)
|
null | null | null | How are scalars and arrays handled ?
| def _scalar_tester(norm_instance, vals):
scalar_result = [norm_instance(float(v)) for v in vals]
assert_array_almost_equal(scalar_result, norm_instance(vals))
| null | null | null | the same way
| codeqa | def scalar tester norm instance vals scalar result [norm instance float v for v in vals]assert array almost equal scalar result norm instance vals
| null | null | null | null | Question:
How are scalars and arrays handled ?
Code:
def _scalar_tester(norm_instance, vals):
scalar_result = [norm_instance(float(v)) for v in vals]
assert_array_almost_equal(scalar_result, norm_instance(vals))
|
null | null | null | What does the code shelve ?
| @utils.arg('server', metavar='<server>', help=_('Name or ID of server.'))
def do_shelve(cs, args):
_find_server(cs, args.server).shelve()
| null | null | null | a server
| codeqa | @utils arg 'server' metavar '<server>' help ' Nameor I Dofserver ' def do shelve cs args find server cs args server shelve
| null | null | null | null | Question:
What does the code shelve ?
Code:
@utils.arg('server', metavar='<server>', help=_('Name or ID of server.'))
def do_shelve(cs, args):
_find_server(cs, args.server).shelve()
|
null | null | null | What stops auth audit being done ?
| def auth_audit_exempt(action):
@functools.wraps(action)
def wrapper(context, data_dict):
return action(context, data_dict)
wrapper.auth_audit_exempt = True
return wrapper
| null | null | null | dirty hack
| codeqa | def auth audit exempt action @functools wraps action def wrapper context data dict return action context data dict wrapper auth audit exempt Truereturn wrapper
| null | null | null | null | Question:
What stops auth audit being done ?
Code:
def auth_audit_exempt(action):
@functools.wraps(action)
def wrapper(context, data_dict):
return action(context, data_dict)
wrapper.auth_audit_exempt = True
return wrapper
|
null | null | null | What do dirty hack stop ?
| def auth_audit_exempt(action):
@functools.wraps(action)
def wrapper(context, data_dict):
return action(context, data_dict)
wrapper.auth_audit_exempt = True
return wrapper
| null | null | null | auth audit being done
| codeqa | def auth audit exempt action @functools wraps action def wrapper context data dict return action context data dict wrapper auth audit exempt Truereturn wrapper
| null | null | null | null | Question:
What do dirty hack stop ?
Code:
def auth_audit_exempt(action):
@functools.wraps(action)
def wrapper(context, data_dict):
return action(context, data_dict)
wrapper.auth_audit_exempt = True
return wrapper
|
null | null | null | What does the code create ?
| def new_class_from_gtype(gtype):
if gtype.is_a(PGType.from_name('GObject')):
parent = gtype.parent.pytype
if ((parent is None) or (parent == PGType.from_name('void'))):
return
interfaces = [i.pytype for i in gtype.interfaces]
bases = tuple(([parent] + interfaces))
cls = type(gtype.name, bases, dict())
cls.__gtype__ = gtype
return cls
elif gtype.is_a(PGType.from_name('GEnum')):
from pgi.enum import GEnumBase
return GEnumBase
| null | null | null | a new class
| codeqa | def new class from gtype gtype if gtype is a PG Type from name 'G Object' parent gtype parent pytypeif parent is None or parent PG Type from name 'void' returninterfaces [i pytype for i in gtype interfaces]bases tuple [parent] + interfaces cls type gtype name bases dict cls gtype gtypereturn clselif gtype is a PG Type from name 'G Enum' from pgi enum import G Enum Basereturn G Enum Base
| null | null | null | null | Question:
What does the code create ?
Code:
def new_class_from_gtype(gtype):
if gtype.is_a(PGType.from_name('GObject')):
parent = gtype.parent.pytype
if ((parent is None) or (parent == PGType.from_name('void'))):
return
interfaces = [i.pytype for i in gtype.interfaces]
bases = tuple(([parent] + interfaces))
cls = type(gtype.name, bases, dict())
cls.__gtype__ = gtype
return cls
elif gtype.is_a(PGType.from_name('GEnum')):
from pgi.enum import GEnumBase
return GEnumBase
|
null | null | null | How did axis define ?
| def rotation_matrix(angle, direction, point=None):
sina = math.sin(angle)
cosa = math.cos(angle)
direction = unit_vector(direction[:3])
R = numpy.diag([cosa, cosa, cosa])
R += (numpy.outer(direction, direction) * (1.0 - cosa))
direction *= sina
R += numpy.array([[0.0, (- direction[2]), direction[1]], [direction[2], 0.0, (- direction[0])], [(- direction[1]), direction[0], 0.0]])
M = numpy.identity(4)
M[:3, :3] = R
if (point is not None):
point = numpy.array(point[:3], dtype=numpy.float64, copy=False)
M[:3, 3] = (point - numpy.dot(R, point))
return M
| null | null | null | by point and direction
| codeqa | def rotation matrix angle direction point None sina math sin angle cosa math cos angle direction unit vector direction[ 3] R numpy diag [cosa cosa cosa] R + numpy outer direction direction * 1 0 - cosa direction * sina R + numpy array [[ 0 0 - direction[ 2 ] direction[ 1 ]] [direction[ 2 ] 0 0 - direction[ 0 ] ] [ - direction[ 1 ] direction[ 0 ] 0 0]] M numpy identity 4 M[ 3 3] Rif point is not None point numpy array point[ 3] dtype numpy float 64 copy False M[ 3 3] point - numpy dot R point return M
| null | null | null | null | Question:
How did axis define ?
Code:
def rotation_matrix(angle, direction, point=None):
sina = math.sin(angle)
cosa = math.cos(angle)
direction = unit_vector(direction[:3])
R = numpy.diag([cosa, cosa, cosa])
R += (numpy.outer(direction, direction) * (1.0 - cosa))
direction *= sina
R += numpy.array([[0.0, (- direction[2]), direction[1]], [direction[2], 0.0, (- direction[0])], [(- direction[1]), direction[0], 0.0]])
M = numpy.identity(4)
M[:3, :3] = R
if (point is not None):
point = numpy.array(point[:3], dtype=numpy.float64, copy=False)
M[:3, 3] = (point - numpy.dot(R, point))
return M
|
null | null | null | What does the code expect ?
| def unbox_usecase3(x):
(a, b) = x
res = a
for v in b:
res += v
return res
| null | null | null | a tuple
| codeqa | def unbox usecase 3 x a b xres afor v in b res + vreturn res
| null | null | null | null | Question:
What does the code expect ?
Code:
def unbox_usecase3(x):
(a, b) = x
res = a
for v in b:
res += v
return res
|
null | null | null | What does the code provide ?
| def in6_xor(a1, a2):
return _in6_bitops(a1, a2, 2)
| null | null | null | a bit to bit xor of provided addresses
| codeqa | def in 6 xor a1 a2 return in 6 bitops a1 a2 2
| null | null | null | null | Question:
What does the code provide ?
Code:
def in6_xor(a1, a2):
return _in6_bitops(a1, a2, 2)
|
null | null | null | What does the code classify into a class ?
| def classify(knn, x, weight_fn=equal_weight, distance_fn=None):
weights = calculate(knn, x, weight_fn=weight_fn, distance_fn=distance_fn)
most_class = None
most_weight = None
for (klass, weight) in weights.items():
if ((most_class is None) or (weight > most_weight)):
most_class = klass
most_weight = weight
return most_class
| null | null | null | an observation
| codeqa | def classify knn x weight fn equal weight distance fn None weights calculate knn x weight fn weight fn distance fn distance fn most class Nonemost weight Nonefor klass weight in weights items if most class is None or weight > most weight most class klassmost weight weightreturn most class
| null | null | null | null | Question:
What does the code classify into a class ?
Code:
def classify(knn, x, weight_fn=equal_weight, distance_fn=None):
weights = calculate(knn, x, weight_fn=weight_fn, distance_fn=distance_fn)
most_class = None
most_weight = None
for (klass, weight) in weights.items():
if ((most_class is None) or (weight > most_weight)):
most_class = klass
most_weight = weight
return most_class
|
null | null | null | Where does the code retrieve the certificate from the server ?
| def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
(host, port) = addr
if (ca_certs is not None):
cert_reqs = CERT_REQUIRED
else:
cert_reqs = CERT_NONE
context = _create_stdlib_context(ssl_version, cert_reqs=cert_reqs, cafile=ca_certs)
with closing(create_connection(addr)) as sock:
with closing(context.wrap_socket(sock)) as sslsock:
dercert = sslsock.getpeercert(True)
return DER_cert_to_PEM_cert(dercert)
| null | null | null | at the specified address
| codeqa | def get server certificate addr ssl version PROTOCOL SS Lv 23 ca certs None host port addrif ca certs is not None cert reqs CERT REQUIRE Delse cert reqs CERT NON Econtext create stdlib context ssl version cert reqs cert reqs cafile ca certs with closing create connection addr as sock with closing context wrap socket sock as sslsock dercert sslsock getpeercert True return DER cert to PEM cert dercert
| null | null | null | null | Question:
Where does the code retrieve the certificate from the server ?
Code:
def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
(host, port) = addr
if (ca_certs is not None):
cert_reqs = CERT_REQUIRED
else:
cert_reqs = CERT_NONE
context = _create_stdlib_context(ssl_version, cert_reqs=cert_reqs, cafile=ca_certs)
with closing(create_connection(addr)) as sock:
with closing(context.wrap_socket(sock)) as sslsock:
dercert = sslsock.getpeercert(True)
return DER_cert_to_PEM_cert(dercert)
|
null | null | null | What does the code retrieve from the server at the specified address ?
| def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
(host, port) = addr
if (ca_certs is not None):
cert_reqs = CERT_REQUIRED
else:
cert_reqs = CERT_NONE
context = _create_stdlib_context(ssl_version, cert_reqs=cert_reqs, cafile=ca_certs)
with closing(create_connection(addr)) as sock:
with closing(context.wrap_socket(sock)) as sslsock:
dercert = sslsock.getpeercert(True)
return DER_cert_to_PEM_cert(dercert)
| null | null | null | the certificate
| codeqa | def get server certificate addr ssl version PROTOCOL SS Lv 23 ca certs None host port addrif ca certs is not None cert reqs CERT REQUIRE Delse cert reqs CERT NON Econtext create stdlib context ssl version cert reqs cert reqs cafile ca certs with closing create connection addr as sock with closing context wrap socket sock as sslsock dercert sslsock getpeercert True return DER cert to PEM cert dercert
| null | null | null | null | Question:
What does the code retrieve from the server at the specified address ?
Code:
def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
(host, port) = addr
if (ca_certs is not None):
cert_reqs = CERT_REQUIRED
else:
cert_reqs = CERT_NONE
context = _create_stdlib_context(ssl_version, cert_reqs=cert_reqs, cafile=ca_certs)
with closing(create_connection(addr)) as sock:
with closing(context.wrap_socket(sock)) as sslsock:
dercert = sslsock.getpeercert(True)
return DER_cert_to_PEM_cert(dercert)
|
null | null | null | For what purpose does the table names modify ?
| def restore_long_table_names():
for table in metadata.tables.values():
table.name = table._original_name
del table._original_name
| null | null | null | to restore the long - naming
| codeqa | def restore long table names for table in metadata tables values table name table original namedel table original name
| null | null | null | null | Question:
For what purpose does the table names modify ?
Code:
def restore_long_table_names():
for table in metadata.tables.values():
table.name = table._original_name
del table._original_name
|
null | null | null | What can admin users access ?
| @pytest.mark.django_db
def test_admin_access(client):
client.login(username='admin', password='admin')
response = client.get(ADMIN_URL)
assert (response.status_code == 200)
| null | null | null | the admin site
| codeqa | @pytest mark django dbdef test admin access client client login username 'admin' password 'admin' response client get ADMIN URL assert response status code 200
| null | null | null | null | Question:
What can admin users access ?
Code:
@pytest.mark.django_db
def test_admin_access(client):
client.login(username='admin', password='admin')
response = client.get(ADMIN_URL)
assert (response.status_code == 200)
|
null | null | null | What can access the admin site ?
| @pytest.mark.django_db
def test_admin_access(client):
client.login(username='admin', password='admin')
response = client.get(ADMIN_URL)
assert (response.status_code == 200)
| null | null | null | admin users
| codeqa | @pytest mark django dbdef test admin access client client login username 'admin' password 'admin' response client get ADMIN URL assert response status code 200
| null | null | null | null | Question:
What can access the admin site ?
Code:
@pytest.mark.django_db
def test_admin_access(client):
client.login(username='admin', password='admin')
response = client.get(ADMIN_URL)
assert (response.status_code == 200)
|
null | null | null | What does the code add to either the insides or outsides ?
| def getInsidesAddToOutsides(loops, outsides):
insides = []
for loopIndex in xrange(len(loops)):
loop = loops[loopIndex]
if isInsideOtherLoops(loopIndex, loops):
insides.append(loop)
else:
outsides.append(loop)
return insides
| null | null | null | loops
| codeqa | def get Insides Add To Outsides loops outsides insides []for loop Index in xrange len loops loop loops[loop Index]if is Inside Other Loops loop Index loops insides append loop else outsides append loop return insides
| null | null | null | null | Question:
What does the code add to either the insides or outsides ?
Code:
def getInsidesAddToOutsides(loops, outsides):
insides = []
for loopIndex in xrange(len(loops)):
loop = loops[loopIndex]
if isInsideOtherLoops(loopIndex, loops):
insides.append(loop)
else:
outsides.append(loop)
return insides
|
null | null | null | What did the code read ?
| def process_multipart(entity):
ib = ''
if ('boundary' in entity.content_type.params):
ib = entity.content_type.params['boundary'].strip('"')
if (not re.match('^[ -~]{0,200}[!-~]$', ib)):
raise ValueError(('Invalid boundary in multipart form: %r' % (ib,)))
ib = ('--' + ib).encode('ascii')
while True:
b = entity.readline()
if (not b):
return
b = b.strip()
if (b == ib):
break
while True:
part = entity.part_class.from_fp(entity.fp, ib)
entity.parts.append(part)
part.process()
if part.fp.done:
break
| null | null | null | all multipart parts
| codeqa | def process multipart entity ib ''if 'boundary' in entity content type params ib entity content type params['boundary'] strip '"' if not re match '^[-~]{ 0 200 }[ -~]$' ib raise Value Error ' Invalidboundaryinmultipartform %r' % ib ib '--' + ib encode 'ascii' while True b entity readline if not b returnb b strip if b ib breakwhile True part entity part class from fp entity fp ib entity parts append part part process if part fp done break
| null | null | null | null | Question:
What did the code read ?
Code:
def process_multipart(entity):
ib = ''
if ('boundary' in entity.content_type.params):
ib = entity.content_type.params['boundary'].strip('"')
if (not re.match('^[ -~]{0,200}[!-~]$', ib)):
raise ValueError(('Invalid boundary in multipart form: %r' % (ib,)))
ib = ('--' + ib).encode('ascii')
while True:
b = entity.readline()
if (not b):
return
b = b.strip()
if (b == ib):
break
while True:
part = entity.part_class.from_fp(entity.fp, ib)
entity.parts.append(part)
part.process()
if part.fp.done:
break
|
null | null | null | How does all caches remove on a minion ?
| def clear_cache():
for (root, dirs, files) in salt.utils.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
os.remove(os.path.join(root, name))
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_cache FAILED with: {0}'.format(exc))
return False
return True
| null | null | null | forcibly
| codeqa | def clear cache for root dirs files in salt utils safe walk opts ['cachedir'] followlinks False for name in files try os remove os path join root name except OS Error as exc log error ' Attempttoclearcachewithsaltutil clear cache FAILE Dwith {0 }' format exc return Falsereturn True
| null | null | null | null | Question:
How does all caches remove on a minion ?
Code:
def clear_cache():
for (root, dirs, files) in salt.utils.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
os.remove(os.path.join(root, name))
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_cache FAILED with: {0}'.format(exc))
return False
return True
|
null | null | null | What does the code require ?
| def nopackages(pkg_list):
pkg_list = [pkg for pkg in pkg_list if is_installed(pkg)]
if pkg_list:
uninstall(pkg_list)
| null | null | null | several deb packages to be uninstalled
| codeqa | def nopackages pkg list pkg list [pkg for pkg in pkg list if is installed pkg ]if pkg list uninstall pkg list
| null | null | null | null | Question:
What does the code require ?
Code:
def nopackages(pkg_list):
pkg_list = [pkg for pkg in pkg_list if is_installed(pkg)]
if pkg_list:
uninstall(pkg_list)
|
null | null | null | What does the code return for the specified user ?
| def unread_count_for(user):
return InboxMessage.objects.filter(to=user, read=False).count()
| null | null | null | the number of unread messages
| codeqa | def unread count for user return Inbox Message objects filter to user read False count
| null | null | null | null | Question:
What does the code return for the specified user ?
Code:
def unread_count_for(user):
return InboxMessage.objects.filter(to=user, read=False).count()
|
null | null | null | What converts any tuple in the function arguments into a tuple ?
| def tuple_wrapper(method):
def wrap_tuples(*args, **kw_args):
newargs = []
for arg in args:
if (type(arg) is tuple):
newargs.append(Tuple(*arg))
else:
newargs.append(arg)
return method(*newargs, **kw_args)
return wrap_tuples
| null | null | null | decorator
| codeqa | def tuple wrapper method def wrap tuples *args **kw args newargs []for arg in args if type arg is tuple newargs append Tuple *arg else newargs append arg return method *newargs **kw args return wrap tuples
| null | null | null | null | Question:
What converts any tuple in the function arguments into a tuple ?
Code:
def tuple_wrapper(method):
def wrap_tuples(*args, **kw_args):
newargs = []
for arg in args:
if (type(arg) is tuple):
newargs.append(Tuple(*arg))
else:
newargs.append(arg)
return method(*newargs, **kw_args)
return wrap_tuples
|
null | null | null | What does the code require ?
| def locales(names):
family = distrib_family()
if (family == 'debian'):
command = 'dpkg-reconfigure --frontend=noninteractive locales'
config_file = '/etc/locale.gen'
_locales_generic(names, config_file=config_file, command=command)
elif (family in ['arch', 'gentoo']):
_locales_generic(names, config_file='/etc/locale.gen', command='locale-gen')
elif (distrib_family() == 'redhat'):
_locales_redhat(names)
else:
raise UnsupportedFamily(supported=['debian', 'arch', 'gentoo', 'redhat'])
| null | null | null | the list of locales to be available
| codeqa | def locales names family distrib family if family 'debian' command 'dpkg-reconfigure--frontend noninteractivelocales'config file '/etc/locale gen' locales generic names config file config file command command elif family in ['arch' 'gentoo'] locales generic names config file '/etc/locale gen' command 'locale-gen' elif distrib family 'redhat' locales redhat names else raise Unsupported Family supported ['debian' 'arch' 'gentoo' 'redhat']
| null | null | null | null | Question:
What does the code require ?
Code:
def locales(names):
family = distrib_family()
if (family == 'debian'):
command = 'dpkg-reconfigure --frontend=noninteractive locales'
config_file = '/etc/locale.gen'
_locales_generic(names, config_file=config_file, command=command)
elif (family in ['arch', 'gentoo']):
_locales_generic(names, config_file='/etc/locale.gen', command='locale-gen')
elif (distrib_family() == 'redhat'):
_locales_redhat(names)
else:
raise UnsupportedFamily(supported=['debian', 'arch', 'gentoo', 'redhat'])
|
null | null | null | What does the code get ?
| def flavor_extra_specs_get(context, flavor_id):
return IMPL.flavor_extra_specs_get(context, flavor_id)
| null | null | null | all extra specs for an instance type
| codeqa | def flavor extra specs get context flavor id return IMPL flavor extra specs get context flavor id
| null | null | null | null | Question:
What does the code get ?
Code:
def flavor_extra_specs_get(context, flavor_id):
return IMPL.flavor_extra_specs_get(context, flavor_id)
|
null | null | null | What does the code create ?
| def new_bookmark_collection(user):
Collection = apps.get_model('osf.Collection')
existing_bookmark_collection = Collection.find((Q('is_bookmark_collection', 'eq', True) & Q('creator', 'eq', user)))
if (existing_bookmark_collection.count() > 0):
raise NodeStateError('Users may only have one bookmark collection')
collection = Collection(title='Bookmarks', creator=user, is_bookmark_collection=True)
collection.save()
return collection
| null | null | null | a new bookmark collection project
| codeqa | def new bookmark collection user Collection apps get model 'osf Collection' existing bookmark collection Collection find Q 'is bookmark collection' 'eq' True & Q 'creator' 'eq' user if existing bookmark collection count > 0 raise Node State Error ' Usersmayonlyhaveonebookmarkcollection' collection Collection title ' Bookmarks' creator user is bookmark collection True collection save return collection
| null | null | null | null | Question:
What does the code create ?
Code:
def new_bookmark_collection(user):
Collection = apps.get_model('osf.Collection')
existing_bookmark_collection = Collection.find((Q('is_bookmark_collection', 'eq', True) & Q('creator', 'eq', user)))
if (existing_bookmark_collection.count() > 0):
raise NodeStateError('Users may only have one bookmark collection')
collection = Collection(title='Bookmarks', creator=user, is_bookmark_collection=True)
collection.save()
return collection
|
null | null | null | How do distribution parameters estimate ?
| def momentcondquant(distfn, params, mom2, quantile=None, shape=None):
if (len(params) == 2):
(loc, scale) = params
elif (len(params) == 3):
(shape, loc, scale) = params
else:
pass
(pq, xq) = quantile
cdfdiff = (distfn.cdf(xq, *params) - pq)
return cdfdiff
| null | null | null | by matching quantiles
| codeqa | def momentcondquant distfn params mom 2 quantile None shape None if len params 2 loc scale paramselif len params 3 shape loc scale paramselse pass pq xq quantilecdfdiff distfn cdf xq *params - pq return cdfdiff
| null | null | null | null | Question:
How do distribution parameters estimate ?
Code:
def momentcondquant(distfn, params, mom2, quantile=None, shape=None):
if (len(params) == 2):
(loc, scale) = params
elif (len(params) == 3):
(shape, loc, scale) = params
else:
pass
(pq, xq) = quantile
cdfdiff = (distfn.cdf(xq, *params) - pq)
return cdfdiff
|
null | null | null | How be functions not called ?
| def rate_limited(max_per_second):
lock = threading.Lock()
min_interval = (1.0 / float(max_per_second))
def decorate(func):
last_time_called = [0.0]
@wraps(func)
def rate_limited_function(*args, **kwargs):
lock.acquire()
elapsed = (time.clock() - last_time_called[0])
left_to_wait = (min_interval - elapsed)
if (left_to_wait > 0):
time.sleep(left_to_wait)
lock.release()
ret = func(*args, **kwargs)
last_time_called[0] = time.clock()
return ret
return rate_limited_function
return decorate
| null | null | null | faster than
| codeqa | def rate limited max per second lock threading Lock min interval 1 0 / float max per second def decorate func last time called [0 0]@wraps func def rate limited function *args **kwargs lock acquire elapsed time clock - last time called[ 0 ] left to wait min interval - elapsed if left to wait > 0 time sleep left to wait lock release ret func *args **kwargs last time called[ 0 ] time clock return retreturn rate limited functionreturn decorate
| null | null | null | null | Question:
How be functions not called ?
Code:
def rate_limited(max_per_second):
lock = threading.Lock()
min_interval = (1.0 / float(max_per_second))
def decorate(func):
last_time_called = [0.0]
@wraps(func)
def rate_limited_function(*args, **kwargs):
lock.acquire()
elapsed = (time.clock() - last_time_called[0])
left_to_wait = (min_interval - elapsed)
if (left_to_wait > 0):
time.sleep(left_to_wait)
lock.release()
ret = func(*args, **kwargs)
last_time_called[0] = time.clock()
return ret
return rate_limited_function
return decorate
|
null | null | null | What haves same elements ?
| def compare_elements(a, b):
if (a is None):
a = []
if (b is None):
b = []
return (set(a) == set(b))
| null | null | null | a and b
| codeqa | def compare elements a b if a is None a []if b is None b []return set a set b
| null | null | null | null | Question:
What haves same elements ?
Code:
def compare_elements(a, b):
if (a is None):
a = []
if (b is None):
b = []
return (set(a) == set(b))
|
null | null | null | Does this method consider ordering if a and b have same elements ?
| def compare_elements(a, b):
if (a is None):
a = []
if (b is None):
b = []
return (set(a) == set(b))
| null | null | null | No
| codeqa | def compare elements a b if a is None a []if b is None b []return set a set b
| null | null | null | null | Question:
Does this method consider ordering if a and b have same elements ?
Code:
def compare_elements(a, b):
if (a is None):
a = []
if (b is None):
b = []
return (set(a) == set(b))
|
null | null | null | What do a and b have ?
| def compare_elements(a, b):
if (a is None):
a = []
if (b is None):
b = []
return (set(a) == set(b))
| null | null | null | same elements
| codeqa | def compare elements a b if a is None a []if b is None b []return set a set b
| null | null | null | null | Question:
What do a and b have ?
Code:
def compare_elements(a, b):
if (a is None):
a = []
if (b is None):
b = []
return (set(a) == set(b))
|
null | null | null | What does the code retrieve from error ?
| def get_error_message(error):
try:
return error.args[0]
except IndexError:
return ''
| null | null | null | error message
| codeqa | def get error message error try return error args[ 0 ]except Index Error return ''
| null | null | null | null | Question:
What does the code retrieve from error ?
Code:
def get_error_message(error):
try:
return error.args[0]
except IndexError:
return ''
|
null | null | null | What does the code compute ?
| @not_implemented_for('undirected')
def in_degree_centrality(G):
centrality = {}
s = (1.0 / (len(G) - 1.0))
centrality = {n: (d * s) for (n, d) in G.in_degree()}
return centrality
| null | null | null | the in - degree centrality for nodes
| codeqa | @not implemented for 'undirected' def in degree centrality G centrality {}s 1 0 / len G - 1 0 centrality {n d * s for n d in G in degree }return centrality
| null | null | null | null | Question:
What does the code compute ?
Code:
@not_implemented_for('undirected')
def in_degree_centrality(G):
centrality = {}
s = (1.0 / (len(G) - 1.0))
centrality = {n: (d * s) for (n, d) in G.in_degree()}
return centrality
|
null | null | null | What does class decorator ensure ?
| def unique(enumeration):
duplicates = []
for (name, member) in enumeration.__members__.items():
if (name != member.name):
duplicates.append((name, member.name))
if duplicates:
duplicate_names = ', '.join([('%s -> %s' % (alias, name)) for (alias, name) in duplicates])
raise ValueError(('duplicate names found in %r: %s' % (enumeration, duplicate_names)))
return enumeration
| null | null | null | only unique members exist in an enumeration
| codeqa | def unique enumeration duplicates []for name member in enumeration members items if name member name duplicates append name member name if duplicates duplicate names ' ' join [ '%s->%s' % alias name for alias name in duplicates] raise Value Error 'duplicatenamesfoundin%r %s' % enumeration duplicate names return enumeration
| null | null | null | null | Question:
What does class decorator ensure ?
Code:
def unique(enumeration):
duplicates = []
for (name, member) in enumeration.__members__.items():
if (name != member.name):
duplicates.append((name, member.name))
if duplicates:
duplicate_names = ', '.join([('%s -> %s' % (alias, name)) for (alias, name) in duplicates])
raise ValueError(('duplicate names found in %r: %s' % (enumeration, duplicate_names)))
return enumeration
|
null | null | null | What ensures only unique members exist in an enumeration ?
| def unique(enumeration):
duplicates = []
for (name, member) in enumeration.__members__.items():
if (name != member.name):
duplicates.append((name, member.name))
if duplicates:
duplicate_names = ', '.join([('%s -> %s' % (alias, name)) for (alias, name) in duplicates])
raise ValueError(('duplicate names found in %r: %s' % (enumeration, duplicate_names)))
return enumeration
| null | null | null | class decorator
| codeqa | def unique enumeration duplicates []for name member in enumeration members items if name member name duplicates append name member name if duplicates duplicate names ' ' join [ '%s->%s' % alias name for alias name in duplicates] raise Value Error 'duplicatenamesfoundin%r %s' % enumeration duplicate names return enumeration
| null | null | null | null | Question:
What ensures only unique members exist in an enumeration ?
Code:
def unique(enumeration):
duplicates = []
for (name, member) in enumeration.__members__.items():
if (name != member.name):
duplicates.append((name, member.name))
if duplicates:
duplicate_names = ', '.join([('%s -> %s' % (alias, name)) for (alias, name) in duplicates])
raise ValueError(('duplicate names found in %r: %s' % (enumeration, duplicate_names)))
return enumeration
|
null | null | null | Where do only unique members exist ?
| def unique(enumeration):
duplicates = []
for (name, member) in enumeration.__members__.items():
if (name != member.name):
duplicates.append((name, member.name))
if duplicates:
duplicate_names = ', '.join([('%s -> %s' % (alias, name)) for (alias, name) in duplicates])
raise ValueError(('duplicate names found in %r: %s' % (enumeration, duplicate_names)))
return enumeration
| null | null | null | in an enumeration
| codeqa | def unique enumeration duplicates []for name member in enumeration members items if name member name duplicates append name member name if duplicates duplicate names ' ' join [ '%s->%s' % alias name for alias name in duplicates] raise Value Error 'duplicatenamesfoundin%r %s' % enumeration duplicate names return enumeration
| null | null | null | null | Question:
Where do only unique members exist ?
Code:
def unique(enumeration):
duplicates = []
for (name, member) in enumeration.__members__.items():
if (name != member.name):
duplicates.append((name, member.name))
if duplicates:
duplicate_names = ', '.join([('%s -> %s' % (alias, name)) for (alias, name) in duplicates])
raise ValueError(('duplicate names found in %r: %s' % (enumeration, duplicate_names)))
return enumeration
|
null | null | null | What does the code get ?
| def get_extended_due_date(node):
if isinstance(node, dict):
get = node.get
else:
get = partial(getattr, node)
due_date = get('due', None)
if (not due_date):
return due_date
extended = get('extended_due', None)
if ((not extended) or (extended < due_date)):
return due_date
return extended
| null | null | null | the actual due date for the logged in student for this node
| codeqa | def get extended due date node if isinstance node dict get node getelse get partial getattr node due date get 'due' None if not due date return due dateextended get 'extended due' None if not extended or extended < due date return due datereturn extended
| null | null | null | null | Question:
What does the code get ?
Code:
def get_extended_due_date(node):
if isinstance(node, dict):
get = node.get
else:
get = partial(getattr, node)
due_date = get('due', None)
if (not due_date):
return due_date
extended = get('extended_due', None)
if ((not extended) or (extended < due_date)):
return due_date
return extended
|
null | null | null | What does this function create ?
| def code_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
new_element = nodes.literal(rawtext, text)
new_element.set_class('code')
return ([new_element], [])
| null | null | null | an inline code block as defined in the twitter bootstrap documentation
| codeqa | def code role name rawtext text lineno inliner options {} content [] new element nodes literal rawtext text new element set class 'code' return [new element] []
| null | null | null | null | Question:
What does this function create ?
Code:
def code_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
new_element = nodes.literal(rawtext, text)
new_element.set_class('code')
return ([new_element], [])
|
null | null | null | What does the code compute ?
| def shape_index(image, sigma=1, mode='constant', cval=0):
(Hxx, Hxy, Hyy) = hessian_matrix(image, sigma=sigma, mode=mode, cval=cval, order='rc')
(l1, l2) = hessian_matrix_eigvals(Hxx, Hxy, Hyy)
return ((2.0 / np.pi) * np.arctan(((l2 + l1) / (l2 - l1))))
| null | null | null | the shape index
| codeqa | def shape index image sigma 1 mode 'constant' cval 0 Hxx Hxy Hyy hessian matrix image sigma sigma mode mode cval cval order 'rc' l1 l2 hessian matrix eigvals Hxx Hxy Hyy return 2 0 / np pi * np arctan l2 + l1 / l2 - l1
| null | null | null | null | Question:
What does the code compute ?
Code:
def shape_index(image, sigma=1, mode='constant', cval=0):
(Hxx, Hxy, Hyy) = hessian_matrix(image, sigma=sigma, mode=mode, cval=cval, order='rc')
(l1, l2) = hessian_matrix_eigvals(Hxx, Hxy, Hyy)
return ((2.0 / np.pi) * np.arctan(((l2 + l1) / (l2 - l1))))
|
null | null | null | How do host - block - lists empty ?
| def test_config_change_initial(config_stub, basedir, download_stub, data_tmpdir, tmpdir):
create_blocklist(tmpdir, blocked_hosts=BLOCKLIST_HOSTS, name='blocked-hosts', line_format='one_per_line')
config_stub.data = {'content': {'host-block-lists': None, 'host-blocking-enabled': True, 'host-blocking-whitelist': None}}
host_blocker = adblock.HostBlocker()
host_blocker.read_hosts()
for str_url in URLS_TO_CHECK:
assert (not host_blocker.is_blocked(QUrl(str_url)))
| null | null | null | on restart
| codeqa | def test config change initial config stub basedir download stub data tmpdir tmpdir create blocklist tmpdir blocked hosts BLOCKLIST HOSTS name 'blocked-hosts' line format 'one per line' config stub data {'content' {'host-block-lists' None 'host-blocking-enabled' True 'host-blocking-whitelist' None}}host blocker adblock Host Blocker host blocker read hosts for str url in URLS TO CHECK assert not host blocker is blocked Q Url str url
| null | null | null | null | Question:
How do host - block - lists empty ?
Code:
def test_config_change_initial(config_stub, basedir, download_stub, data_tmpdir, tmpdir):
create_blocklist(tmpdir, blocked_hosts=BLOCKLIST_HOSTS, name='blocked-hosts', line_format='one_per_line')
config_stub.data = {'content': {'host-block-lists': None, 'host-blocking-enabled': True, 'host-blocking-whitelist': None}}
host_blocker = adblock.HostBlocker()
host_blocker.read_hosts()
for str_url in URLS_TO_CHECK:
assert (not host_blocker.is_blocked(QUrl(str_url)))
|
null | null | null | What does the code configure ?
| def configure_context_processors(app):
@app.context_processor
def inject_flaskbb_config():
'Injects the ``flaskbb_config`` config variable into the\n templates.\n '
return dict(flaskbb_config=flaskbb_config)
| null | null | null | the context processors
| codeqa | def configure context processors app @app context processordef inject flaskbb config ' Injectsthe``flaskbb config``configvariableintothe\ntemplates \n'return dict flaskbb config flaskbb config
| null | null | null | null | Question:
What does the code configure ?
Code:
def configure_context_processors(app):
@app.context_processor
def inject_flaskbb_config():
'Injects the ``flaskbb_config`` config variable into the\n templates.\n '
return dict(flaskbb_config=flaskbb_config)
|
null | null | null | For what purpose does cache write in an integration test ?
| def ensure_cached(expected_num_artifacts=None):
def decorator(test_fn):
def wrapper(self, *args, **kwargs):
with temporary_dir() as artifact_cache:
cache_args = u'--cache-write-to=["{}"]'.format(artifact_cache)
test_fn(self, *(args + (cache_args,)), **kwargs)
num_artifacts = 0
for (root, _, files) in os.walk(artifact_cache):
print(root, files)
num_artifacts += len(files)
if (expected_num_artifacts is None):
self.assertNotEqual(num_artifacts, 0)
else:
self.assertEqual(num_artifacts, expected_num_artifacts)
return wrapper
return decorator
| null | null | null | for asserting
| codeqa | def ensure cached expected num artifacts None def decorator test fn def wrapper self *args **kwargs with temporary dir as artifact cache cache args u'--cache-write-to ["{}"]' format artifact cache test fn self * args + cache args **kwargs num artifacts 0for root files in os walk artifact cache print root files num artifacts + len files if expected num artifacts is None self assert Not Equal num artifacts 0 else self assert Equal num artifacts expected num artifacts return wrapperreturn decorator
| null | null | null | null | Question:
For what purpose does cache write in an integration test ?
Code:
def ensure_cached(expected_num_artifacts=None):
def decorator(test_fn):
def wrapper(self, *args, **kwargs):
with temporary_dir() as artifact_cache:
cache_args = u'--cache-write-to=["{}"]'.format(artifact_cache)
test_fn(self, *(args + (cache_args,)), **kwargs)
num_artifacts = 0
for (root, _, files) in os.walk(artifact_cache):
print(root, files)
num_artifacts += len(files)
if (expected_num_artifacts is None):
self.assertNotEqual(num_artifacts, 0)
else:
self.assertEqual(num_artifacts, expected_num_artifacts)
return wrapper
return decorator
|
null | null | null | What writes in an integration test ?
| def ensure_cached(expected_num_artifacts=None):
def decorator(test_fn):
def wrapper(self, *args, **kwargs):
with temporary_dir() as artifact_cache:
cache_args = u'--cache-write-to=["{}"]'.format(artifact_cache)
test_fn(self, *(args + (cache_args,)), **kwargs)
num_artifacts = 0
for (root, _, files) in os.walk(artifact_cache):
print(root, files)
num_artifacts += len(files)
if (expected_num_artifacts is None):
self.assertNotEqual(num_artifacts, 0)
else:
self.assertEqual(num_artifacts, expected_num_artifacts)
return wrapper
return decorator
| null | null | null | cache
| codeqa | def ensure cached expected num artifacts None def decorator test fn def wrapper self *args **kwargs with temporary dir as artifact cache cache args u'--cache-write-to ["{}"]' format artifact cache test fn self * args + cache args **kwargs num artifacts 0for root files in os walk artifact cache print root files num artifacts + len files if expected num artifacts is None self assert Not Equal num artifacts 0 else self assert Equal num artifacts expected num artifacts return wrapperreturn decorator
| null | null | null | null | Question:
What writes in an integration test ?
Code:
def ensure_cached(expected_num_artifacts=None):
def decorator(test_fn):
def wrapper(self, *args, **kwargs):
with temporary_dir() as artifact_cache:
cache_args = u'--cache-write-to=["{}"]'.format(artifact_cache)
test_fn(self, *(args + (cache_args,)), **kwargs)
num_artifacts = 0
for (root, _, files) in os.walk(artifact_cache):
print(root, files)
num_artifacts += len(files)
if (expected_num_artifacts is None):
self.assertNotEqual(num_artifacts, 0)
else:
self.assertEqual(num_artifacts, expected_num_artifacts)
return wrapper
return decorator
|
null | null | null | Where does cache write for asserting ?
| def ensure_cached(expected_num_artifacts=None):
def decorator(test_fn):
def wrapper(self, *args, **kwargs):
with temporary_dir() as artifact_cache:
cache_args = u'--cache-write-to=["{}"]'.format(artifact_cache)
test_fn(self, *(args + (cache_args,)), **kwargs)
num_artifacts = 0
for (root, _, files) in os.walk(artifact_cache):
print(root, files)
num_artifacts += len(files)
if (expected_num_artifacts is None):
self.assertNotEqual(num_artifacts, 0)
else:
self.assertEqual(num_artifacts, expected_num_artifacts)
return wrapper
return decorator
| null | null | null | in an integration test
| codeqa | def ensure cached expected num artifacts None def decorator test fn def wrapper self *args **kwargs with temporary dir as artifact cache cache args u'--cache-write-to ["{}"]' format artifact cache test fn self * args + cache args **kwargs num artifacts 0for root files in os walk artifact cache print root files num artifacts + len files if expected num artifacts is None self assert Not Equal num artifacts 0 else self assert Equal num artifacts expected num artifacts return wrapperreturn decorator
| null | null | null | null | Question:
Where does cache write for asserting ?
Code:
def ensure_cached(expected_num_artifacts=None):
def decorator(test_fn):
def wrapper(self, *args, **kwargs):
with temporary_dir() as artifact_cache:
cache_args = u'--cache-write-to=["{}"]'.format(artifact_cache)
test_fn(self, *(args + (cache_args,)), **kwargs)
num_artifacts = 0
for (root, _, files) in os.walk(artifact_cache):
print(root, files)
num_artifacts += len(files)
if (expected_num_artifacts is None):
self.assertNotEqual(num_artifacts, 0)
else:
self.assertEqual(num_artifacts, expected_num_artifacts)
return wrapper
return decorator
|
null | null | null | How do a graph color ?
| def greedy_color(G, strategy='largest_first', interchange=False):
if (len(G) == 0):
return {}
strategy = STRATEGIES.get(strategy, strategy)
if (not callable(strategy)):
raise nx.NetworkXError('strategy must be callable or a valid string. {0} not valid.'.format(strategy))
if interchange:
if (strategy is strategy_independent_set):
msg = 'interchange cannot be used with strategy_independent_set'
raise nx.NetworkXPointlessConcept(msg)
if (strategy is strategy_saturation_largest_first):
msg = 'interchange cannot be used with strategy_saturation_largest_first'
raise nx.NetworkXPointlessConcept(msg)
colors = {}
nodes = strategy(G, colors)
if interchange:
return _interchange.greedy_coloring_with_interchange(G, nodes)
for u in nodes:
neighbour_colors = {colors[v] for v in G[u] if (v in colors)}
for color in itertools.count():
if (color not in neighbour_colors):
break
colors[u] = color
return colors
| null | null | null | using various strategies of greedy graph coloring
| codeqa | def greedy color G strategy 'largest first' interchange False if len G 0 return {}strategy STRATEGIES get strategy strategy if not callable strategy raise nx Network X Error 'strategymustbecallableoravalidstring {0 }notvalid ' format strategy if interchange if strategy is strategy independent set msg 'interchangecannotbeusedwithstrategy independent set'raise nx Network X Pointless Concept msg if strategy is strategy saturation largest first msg 'interchangecannotbeusedwithstrategy saturation largest first'raise nx Network X Pointless Concept msg colors {}nodes strategy G colors if interchange return interchange greedy coloring with interchange G nodes for u in nodes neighbour colors {colors[v] for v in G[u] if v in colors }for color in itertools count if color not in neighbour colors breakcolors[u] colorreturn colors
| null | null | null | null | Question:
How do a graph color ?
Code:
def greedy_color(G, strategy='largest_first', interchange=False):
if (len(G) == 0):
return {}
strategy = STRATEGIES.get(strategy, strategy)
if (not callable(strategy)):
raise nx.NetworkXError('strategy must be callable or a valid string. {0} not valid.'.format(strategy))
if interchange:
if (strategy is strategy_independent_set):
msg = 'interchange cannot be used with strategy_independent_set'
raise nx.NetworkXPointlessConcept(msg)
if (strategy is strategy_saturation_largest_first):
msg = 'interchange cannot be used with strategy_saturation_largest_first'
raise nx.NetworkXPointlessConcept(msg)
colors = {}
nodes = strategy(G, colors)
if interchange:
return _interchange.greedy_coloring_with_interchange(G, nodes)
for u in nodes:
neighbour_colors = {colors[v] for v in G[u] if (v in colors)}
for color in itertools.count():
if (color not in neighbour_colors):
break
colors[u] = color
return colors
|
null | null | null | What is using various strategies of greedy graph coloring ?
| def greedy_color(G, strategy='largest_first', interchange=False):
if (len(G) == 0):
return {}
strategy = STRATEGIES.get(strategy, strategy)
if (not callable(strategy)):
raise nx.NetworkXError('strategy must be callable or a valid string. {0} not valid.'.format(strategy))
if interchange:
if (strategy is strategy_independent_set):
msg = 'interchange cannot be used with strategy_independent_set'
raise nx.NetworkXPointlessConcept(msg)
if (strategy is strategy_saturation_largest_first):
msg = 'interchange cannot be used with strategy_saturation_largest_first'
raise nx.NetworkXPointlessConcept(msg)
colors = {}
nodes = strategy(G, colors)
if interchange:
return _interchange.greedy_coloring_with_interchange(G, nodes)
for u in nodes:
neighbour_colors = {colors[v] for v in G[u] if (v in colors)}
for color in itertools.count():
if (color not in neighbour_colors):
break
colors[u] = color
return colors
| null | null | null | a graph
| codeqa | def greedy color G strategy 'largest first' interchange False if len G 0 return {}strategy STRATEGIES get strategy strategy if not callable strategy raise nx Network X Error 'strategymustbecallableoravalidstring {0 }notvalid ' format strategy if interchange if strategy is strategy independent set msg 'interchangecannotbeusedwithstrategy independent set'raise nx Network X Pointless Concept msg if strategy is strategy saturation largest first msg 'interchangecannotbeusedwithstrategy saturation largest first'raise nx Network X Pointless Concept msg colors {}nodes strategy G colors if interchange return interchange greedy coloring with interchange G nodes for u in nodes neighbour colors {colors[v] for v in G[u] if v in colors }for color in itertools count if color not in neighbour colors breakcolors[u] colorreturn colors
| null | null | null | null | Question:
What is using various strategies of greedy graph coloring ?
Code:
def greedy_color(G, strategy='largest_first', interchange=False):
if (len(G) == 0):
return {}
strategy = STRATEGIES.get(strategy, strategy)
if (not callable(strategy)):
raise nx.NetworkXError('strategy must be callable or a valid string. {0} not valid.'.format(strategy))
if interchange:
if (strategy is strategy_independent_set):
msg = 'interchange cannot be used with strategy_independent_set'
raise nx.NetworkXPointlessConcept(msg)
if (strategy is strategy_saturation_largest_first):
msg = 'interchange cannot be used with strategy_saturation_largest_first'
raise nx.NetworkXPointlessConcept(msg)
colors = {}
nodes = strategy(G, colors)
if interchange:
return _interchange.greedy_coloring_with_interchange(G, nodes)
for u in nodes:
neighbour_colors = {colors[v] for v in G[u] if (v in colors)}
for color in itertools.count():
if (color not in neighbour_colors):
break
colors[u] = color
return colors
|
null | null | null | What does the code ensure ?
| def test_compile_error():
try:
can_compile(u'(fn [] (in [1 2 3]))')
except HyTypeError as e:
assert (e.message == u"`in' needs at least 2 arguments, got 1.")
else:
assert False
| null | null | null | we get compile error in tricky cases
| codeqa | def test compile error try can compile u' fn[] in[ 123 ] ' except Hy Type Error as e assert e message u"`in'needsatleast 2 arguments got 1 " else assert False
| null | null | null | null | Question:
What does the code ensure ?
Code:
def test_compile_error():
try:
can_compile(u'(fn [] (in [1 2 3]))')
except HyTypeError as e:
assert (e.message == u"`in' needs at least 2 arguments, got 1.")
else:
assert False
|
null | null | null | What do we get ?
| def test_compile_error():
try:
can_compile(u'(fn [] (in [1 2 3]))')
except HyTypeError as e:
assert (e.message == u"`in' needs at least 2 arguments, got 1.")
else:
assert False
| null | null | null | compile error in tricky cases
| codeqa | def test compile error try can compile u' fn[] in[ 123 ] ' except Hy Type Error as e assert e message u"`in'needsatleast 2 arguments got 1 " else assert False
| null | null | null | null | Question:
What do we get ?
Code:
def test_compile_error():
try:
can_compile(u'(fn [] (in [1 2 3]))')
except HyTypeError as e:
assert (e.message == u"`in' needs at least 2 arguments, got 1.")
else:
assert False
|
null | null | null | What does a for loop convert ?
| def mangle_mako_loop(node, printer):
loop_variable = LoopVariable()
node.accept_visitor(loop_variable)
if loop_variable.detected:
node.nodes[(-1)].has_loop_context = True
match = _FOR_LOOP.match(node.text)
if match:
printer.writelines(('loop = __M_loop._enter(%s)' % match.group(2)), 'try:')
text = ('for %s in loop:' % match.group(1))
else:
raise SyntaxError(("Couldn't apply loop context: %s" % node.text))
else:
text = node.text
return text
| null | null | null | into a context manager wrapped around a for loop when access to the loop variable has been detected in the for loop body
| codeqa | def mangle mako loop node printer loop variable Loop Variable node accept visitor loop variable if loop variable detected node nodes[ -1 ] has loop context Truematch FOR LOOP match node text if match printer writelines 'loop M loop enter %s ' % match group 2 'try ' text 'for%sinloop ' % match group 1 else raise Syntax Error " Couldn'tapplyloopcontext %s" % node text else text node textreturn text
| null | null | null | null | Question:
What does a for loop convert ?
Code:
def mangle_mako_loop(node, printer):
loop_variable = LoopVariable()
node.accept_visitor(loop_variable)
if loop_variable.detected:
node.nodes[(-1)].has_loop_context = True
match = _FOR_LOOP.match(node.text)
if match:
printer.writelines(('loop = __M_loop._enter(%s)' % match.group(2)), 'try:')
text = ('for %s in loop:' % match.group(1))
else:
raise SyntaxError(("Couldn't apply loop context: %s" % node.text))
else:
text = node.text
return text
|
null | null | null | When did a context manager wrap around a for loop ?
| def mangle_mako_loop(node, printer):
loop_variable = LoopVariable()
node.accept_visitor(loop_variable)
if loop_variable.detected:
node.nodes[(-1)].has_loop_context = True
match = _FOR_LOOP.match(node.text)
if match:
printer.writelines(('loop = __M_loop._enter(%s)' % match.group(2)), 'try:')
text = ('for %s in loop:' % match.group(1))
else:
raise SyntaxError(("Couldn't apply loop context: %s" % node.text))
else:
text = node.text
return text
| null | null | null | when access to the loop variable has been detected in the for loop body
| codeqa | def mangle mako loop node printer loop variable Loop Variable node accept visitor loop variable if loop variable detected node nodes[ -1 ] has loop context Truematch FOR LOOP match node text if match printer writelines 'loop M loop enter %s ' % match group 2 'try ' text 'for%sinloop ' % match group 1 else raise Syntax Error " Couldn'tapplyloopcontext %s" % node text else text node textreturn text
| null | null | null | null | Question:
When did a context manager wrap around a for loop ?
Code:
def mangle_mako_loop(node, printer):
loop_variable = LoopVariable()
node.accept_visitor(loop_variable)
if loop_variable.detected:
node.nodes[(-1)].has_loop_context = True
match = _FOR_LOOP.match(node.text)
if match:
printer.writelines(('loop = __M_loop._enter(%s)' % match.group(2)), 'try:')
text = ('for %s in loop:' % match.group(1))
else:
raise SyntaxError(("Couldn't apply loop context: %s" % node.text))
else:
text = node.text
return text
|
null | null | null | What converts into a context manager wrapped around a for loop when access to the loop variable has been detected in the for loop body ?
| def mangle_mako_loop(node, printer):
loop_variable = LoopVariable()
node.accept_visitor(loop_variable)
if loop_variable.detected:
node.nodes[(-1)].has_loop_context = True
match = _FOR_LOOP.match(node.text)
if match:
printer.writelines(('loop = __M_loop._enter(%s)' % match.group(2)), 'try:')
text = ('for %s in loop:' % match.group(1))
else:
raise SyntaxError(("Couldn't apply loop context: %s" % node.text))
else:
text = node.text
return text
| null | null | null | a for loop
| codeqa | def mangle mako loop node printer loop variable Loop Variable node accept visitor loop variable if loop variable detected node nodes[ -1 ] has loop context Truematch FOR LOOP match node text if match printer writelines 'loop M loop enter %s ' % match group 2 'try ' text 'for%sinloop ' % match group 1 else raise Syntax Error " Couldn'tapplyloopcontext %s" % node text else text node textreturn text
| null | null | null | null | Question:
What converts into a context manager wrapped around a for loop when access to the loop variable has been detected in the for loop body ?
Code:
def mangle_mako_loop(node, printer):
loop_variable = LoopVariable()
node.accept_visitor(loop_variable)
if loop_variable.detected:
node.nodes[(-1)].has_loop_context = True
match = _FOR_LOOP.match(node.text)
if match:
printer.writelines(('loop = __M_loop._enter(%s)' % match.group(2)), 'try:')
text = ('for %s in loop:' % match.group(1))
else:
raise SyntaxError(("Couldn't apply loop context: %s" % node.text))
else:
text = node.text
return text
|
null | null | null | What has been detected in the for loop body ?
| def mangle_mako_loop(node, printer):
loop_variable = LoopVariable()
node.accept_visitor(loop_variable)
if loop_variable.detected:
node.nodes[(-1)].has_loop_context = True
match = _FOR_LOOP.match(node.text)
if match:
printer.writelines(('loop = __M_loop._enter(%s)' % match.group(2)), 'try:')
text = ('for %s in loop:' % match.group(1))
else:
raise SyntaxError(("Couldn't apply loop context: %s" % node.text))
else:
text = node.text
return text
| null | null | null | access to the loop variable
| codeqa | def mangle mako loop node printer loop variable Loop Variable node accept visitor loop variable if loop variable detected node nodes[ -1 ] has loop context Truematch FOR LOOP match node text if match printer writelines 'loop M loop enter %s ' % match group 2 'try ' text 'for%sinloop ' % match group 1 else raise Syntax Error " Couldn'tapplyloopcontext %s" % node text else text node textreturn text
| null | null | null | null | Question:
What has been detected in the for loop body ?
Code:
def mangle_mako_loop(node, printer):
loop_variable = LoopVariable()
node.accept_visitor(loop_variable)
if loop_variable.detected:
node.nodes[(-1)].has_loop_context = True
match = _FOR_LOOP.match(node.text)
if match:
printer.writelines(('loop = __M_loop._enter(%s)' % match.group(2)), 'try:')
text = ('for %s in loop:' % match.group(1))
else:
raise SyntaxError(("Couldn't apply loop context: %s" % node.text))
else:
text = node.text
return text
|
null | null | null | How do a file or directory move to another location ?
| def move(src, dst):
real_dst = dst
if os.path.isdir(dst):
real_dst = os.path.join(dst, _basename(src))
if os.path.exists(real_dst):
raise Error, ("Destination path '%s' already exists" % real_dst)
try:
os.rename(src, real_dst)
except OSError:
if os.path.isdir(src):
if _destinsrc(src, dst):
raise Error, ("Cannot move a directory '%s' into itself '%s'." % (src, dst))
copytree(src, real_dst, symlinks=True)
rmtree(src)
else:
copy2(src, real_dst)
os.unlink(src)
| null | null | null | recursively
| codeqa | def move src dst real dst dstif os path isdir dst real dst os path join dst basename src if os path exists real dst raise Error " Destinationpath'%s'alreadyexists" % real dst try os rename src real dst except OS Error if os path isdir src if destinsrc src dst raise Error " Cannotmoveadirectory'%s'intoitself'%s' " % src dst copytree src real dst symlinks True rmtree src else copy 2 src real dst os unlink src
| null | null | null | null | Question:
How do a file or directory move to another location ?
Code:
def move(src, dst):
real_dst = dst
if os.path.isdir(dst):
real_dst = os.path.join(dst, _basename(src))
if os.path.exists(real_dst):
raise Error, ("Destination path '%s' already exists" % real_dst)
try:
os.rename(src, real_dst)
except OSError:
if os.path.isdir(src):
if _destinsrc(src, dst):
raise Error, ("Cannot move a directory '%s' into itself '%s'." % (src, dst))
copytree(src, real_dst, symlinks=True)
rmtree(src)
else:
copy2(src, real_dst)
os.unlink(src)
|
null | null | null | What calculates on a file ?
| def hash_file(method, filepath):
f = open(filepath, 'rb')
h = method()
while True:
buf = f.read((1024 * 1024))
if (not buf):
break
h.update(buf)
return h.hexdigest()
| null | null | null | an hash
| codeqa | def hash file method filepath f open filepath 'rb' h method while True buf f read 1024 * 1024 if not buf breakh update buf return h hexdigest
| null | null | null | null | Question:
What calculates on a file ?
Code:
def hash_file(method, filepath):
f = open(filepath, 'rb')
h = method()
while True:
buf = f.read((1024 * 1024))
if (not buf):
break
h.update(buf)
return h.hexdigest()
|
null | null | null | What does the code convert to an integer ?
| def from_text(text):
import pdb
step = 1
cur = ''
state = 0
for c in text:
if ((c == '-') and (state == 0)):
start = int(cur)
cur = ''
state = 2
elif (c == '/'):
stop = int(cur)
cur = ''
state = 4
elif c.isdigit():
cur += c
else:
raise dns.exception.SyntaxError(('Could not parse %s' % c))
if (state in (1, 3)):
raise dns.exception.SyntaxError
if (state == 2):
stop = int(cur)
if (state == 4):
step = int(cur)
assert (step >= 1)
assert (start >= 0)
assert (start <= stop)
return (start, stop, step)
| null | null | null | the text form of a range in a generate statement
| codeqa | def from text text import pdbstep 1cur ''state 0for c in text if c '-' and state 0 start int cur cur ''state 2elif c '/' stop int cur cur ''state 4elif c isdigit cur + celse raise dns exception Syntax Error ' Couldnotparse%s' % c if state in 1 3 raise dns exception Syntax Errorif state 2 stop int cur if state 4 step int cur assert step > 1 assert start > 0 assert start < stop return start stop step
| null | null | null | null | Question:
What does the code convert to an integer ?
Code:
def from_text(text):
import pdb
step = 1
cur = ''
state = 0
for c in text:
if ((c == '-') and (state == 0)):
start = int(cur)
cur = ''
state = 2
elif (c == '/'):
stop = int(cur)
cur = ''
state = 4
elif c.isdigit():
cur += c
else:
raise dns.exception.SyntaxError(('Could not parse %s' % c))
if (state in (1, 3)):
raise dns.exception.SyntaxError
if (state == 2):
stop = int(cur)
if (state == 4):
step = int(cur)
assert (step >= 1)
assert (start >= 0)
assert (start <= stop)
return (start, stop, step)
|
null | null | null | What does the code capitalize ?
| def capfirst(value):
return (value and (value[0].upper() + value[1:]))
| null | null | null | the first character of the value
| codeqa | def capfirst value return value and value[ 0 ] upper + value[ 1 ]
| null | null | null | null | Question:
What does the code capitalize ?
Code:
def capfirst(value):
return (value and (value[0].upper() + value[1:]))
|
null | null | null | What registers a validator with a name for look - up ?
| def validate(**kwargs):
def decorator(func):
_VALIDATORS[kwargs.pop('name', func.__name__)] = func
return func
return decorator
| null | null | null | a decorator
| codeqa | def validate **kwargs def decorator func VALIDATORS[kwargs pop 'name' func name ] funcreturn funcreturn decorator
| null | null | null | null | Question:
What registers a validator with a name for look - up ?
Code:
def validate(**kwargs):
def decorator(func):
_VALIDATORS[kwargs.pop('name', func.__name__)] = func
return func
return decorator
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.