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 does the code return a single version string ?
| def _norm_version(version, build=''):
l = string.split(version, '.')
if build:
l.append(build)
try:
ints = map(int, l)
except ValueError:
strings = l
else:
strings = map(str, ints)
version = string.join(strings[:3], '.')
return version
| null | null | null | using the format major
| codeqa | def norm version version build '' l string split version ' ' if build l append build try ints map int l except Value Error strings lelse strings map str ints version string join strings[ 3] ' ' return version
| null | null | null | null | Question:
How does the code return a single version string ?
Code:
def _norm_version(version, build=''):
l = string.split(version, '.')
if build:
l.append(build)
try:
ints = map(int, l)
except ValueError:
strings = l
else:
strings = map(str, ints)
version = string.join(strings[:3], '.')
return versio... |
null | null | null | What does the code get ?
| def getCraftSequence():
return 'carve scale bottom preface widen inset fill multiply speed temperature raft skirt chamber tower jitter clip smooth stretch skin comb cool hop wipe oozebane splodge home lash fillet limit unpause dimension altshell alteration export'.split()
| null | null | null | the extrusion craft sequence
| codeqa | def get Craft Sequence return 'carvescalebottomprefacewideninsetfillmultiplyspeedtemperatureraftskirtchambertowerjitterclipsmoothstretchskincombcoolhopwipeoozebanesplodgehomelashfilletlimitunpausedimensionaltshellalterationexport' split
| null | null | null | null | Question:
What does the code get ?
Code:
def getCraftSequence():
return 'carve scale bottom preface widen inset fill multiply speed temperature raft skirt chamber tower jitter clip smooth stretch skin comb cool hop wipe oozebane splodge home lash fillet limit unpause dimension altshe... |
null | null | null | What does the code destroy if it does not exist ?
| @retry(retry_on_exception=_retry_on_deadlock, wait_fixed=500, stop_max_attempt_number=50)
def image_destroy(context, image_id):
session = get_session()
with session.begin():
image_ref = _image_get(context, image_id, session=session)
_check_mutate_authorization(context, image_ref)
image_ref.delete(session=sessio... | null | null | null | the image
| codeqa | @retry retry on exception retry on deadlock wait fixed 500 stop max attempt number 50 def image destroy context image id session get session with session begin image ref image get context image id session session check mutate authorization context image ref image ref delete session session delete time image ref deleted... | null | null | null | null | Question:
What does the code destroy if it does not exist ?
Code:
@retry(retry_on_exception=_retry_on_deadlock, wait_fixed=500, stop_max_attempt_number=50)
def image_destroy(context, image_id):
session = get_session()
with session.begin():
image_ref = _image_get(context, image_id, session=session)
_check_muta... |
null | null | null | What does the code take from the tree ?
| def _process_node(node, aliases, duplicates):
stack = _post_order(node)
key = list()
for item in stack:
if ((type(item[0]) is str) and (item not in aliases)):
key.append(item[0])
else:
key.append(item[0:2])
key = tuple(key)
dup_node = duplicates.get(key, False)
if dup_node:
node[0] = dup_node
stack ... | null | null | null | a node
| codeqa | def process node node aliases duplicates stack post order node key list for item in stack if type item[ 0 ] is str and item not in aliases key append item[ 0 ] else key append item[ 0 2] key tuple key dup node duplicates get key False if dup node node[ 0 ] dup nodestack Noneelse duplicates[key] stack[ -1 ]aliases add s... | null | null | null | null | Question:
What does the code take from the tree ?
Code:
def _process_node(node, aliases, duplicates):
stack = _post_order(node)
key = list()
for item in stack:
if ((type(item[0]) is str) and (item not in aliases)):
key.append(item[0])
else:
key.append(item[0:2])
key = tuple(key)
dup_node = duplicates... |
null | null | null | What does the code get ?
| def get_filepaths(dire):
return read_in(os.path.join(dire, 'FILEPATHS'))
| null | null | null | filepaths
| codeqa | def get filepaths dire return read in os path join dire 'FILEPATHS'
| null | null | null | null | Question:
What does the code get ?
Code:
def get_filepaths(dire):
return read_in(os.path.join(dire, 'FILEPATHS'))
|
null | null | null | What does the code save to the specified location ?
| def save_dictionary(worddict, wordcount, loc):
with open(loc, 'wb') as f:
pkl.dump(worddict, f)
pkl.dump(wordcount, f)
| null | null | null | a dictionary
| codeqa | def save dictionary worddict wordcount loc with open loc 'wb' as f pkl dump worddict f pkl dump wordcount f
| null | null | null | null | Question:
What does the code save to the specified location ?
Code:
def save_dictionary(worddict, wordcount, loc):
with open(loc, 'wb') as f:
pkl.dump(worddict, f)
pkl.dump(wordcount, f)
|
null | null | null | What does the code update ?
| def update_org_prefs(orgname=None, profile='grafana', **kwargs):
if isinstance(profile, string_types):
profile = __salt__['config.option'](profile)
if orgname:
switch_org(orgname, profile)
response = requests.put('{0}/api/org/preferences'.format(profile['grafana_url']), json=kwargs, auth=_get_auth(profile), head... | null | null | null | the organization preferences
| codeqa | def update org prefs orgname None profile 'grafana' **kwargs if isinstance profile string types profile salt ['config option'] profile if orgname switch org orgname profile response requests put '{ 0 }/api/org/preferences' format profile['grafana url'] json kwargs auth get auth profile headers get headers profile timeo... | null | null | null | null | Question:
What does the code update ?
Code:
def update_org_prefs(orgname=None, profile='grafana', **kwargs):
if isinstance(profile, string_types):
profile = __salt__['config.option'](profile)
if orgname:
switch_org(orgname, profile)
response = requests.put('{0}/api/org/preferences'.format(profile['grafana_ur... |
null | null | null | What does the code exemplify ?
| def demo_repr_rule_format():
postag(ruleformat='repr')
| null | null | null | repr
| codeqa | def demo repr rule format postag ruleformat 'repr'
| null | null | null | null | Question:
What does the code exemplify ?
Code:
def demo_repr_rule_format():
postag(ruleformat='repr')
|
null | null | null | How do all functions take ?
| def Radian(radians):
return radians
| null | null | null | in radians
| codeqa | def Radian radians return radians
| null | null | null | null | Question:
How do all functions take ?
Code:
def Radian(radians):
return radians
|
null | null | null | By how much do mode exist ?
| def test_slices_overlap_wrong_mode():
with pytest.raises(ValueError) as e:
overlap_slices((5,), (3,), (0,), mode=u'full')
assert (u'Mode can be only' in str(e.value))
| null | null | null | non
| codeqa | def test slices overlap wrong mode with pytest raises Value Error as e overlap slices 5 3 0 mode u'full' assert u' Modecanbeonly' in str e value
| null | null | null | null | Question:
By how much do mode exist ?
Code:
def test_slices_overlap_wrong_mode():
with pytest.raises(ValueError) as e:
overlap_slices((5,), (3,), (0,), mode=u'full')
assert (u'Mode can be only' in str(e.value))
|
null | null | null | What does the code add ?
| def addToMenu(master, menu, repository, window):
path = settings.getPathInFabmetheusFromFileNameHelp(repository.fileNameHelp)
capitalizedBasename = os.path.basename(path).capitalize()
helpRepository = settings.getReadRepository(skeinforge_help.HelpRepository())
if ((repository.openWikiManualHelpPage != None) and he... | null | null | null | a tool plugin menu
| codeqa | def add To Menu master menu repository window path settings get Path In Fabmetheus From File Name Help repository file Name Help capitalized Basename os path basename path capitalize help Repository settings get Read Repository skeinforge help Help Repository if repository open Wiki Manual Help Page None and help Repos... | null | null | null | null | Question:
What does the code add ?
Code:
def addToMenu(master, menu, repository, window):
path = settings.getPathInFabmetheusFromFileNameHelp(repository.fileNameHelp)
capitalizedBasename = os.path.basename(path).capitalize()
helpRepository = settings.getReadRepository(skeinforge_help.HelpRepository())
if ((repo... |
null | null | null | What does variable have ?
| def make_name(variable, anon='anonymous_variable'):
if (hasattr(variable, 'name') and (variable.name is not None)):
return variable.name
return anon
| null | null | null | a name
| codeqa | def make name variable anon 'anonymous variable' if hasattr variable 'name' and variable name is not None return variable namereturn anon
| null | null | null | null | Question:
What does variable have ?
Code:
def make_name(variable, anon='anonymous_variable'):
if (hasattr(variable, 'name') and (variable.name is not None)):
return variable.name
return anon
|
null | null | null | What has a name ?
| def make_name(variable, anon='anonymous_variable'):
if (hasattr(variable, 'name') and (variable.name is not None)):
return variable.name
return anon
| null | null | null | variable
| codeqa | def make name variable anon 'anonymous variable' if hasattr variable 'name' and variable name is not None return variable namereturn anon
| null | null | null | null | Question:
What has a name ?
Code:
def make_name(variable, anon='anonymous_variable'):
if (hasattr(variable, 'name') and (variable.name is not None)):
return variable.name
return anon
|
null | null | null | What does the code retrieve back to words ?
| def get_word_index(path='imdb_word_index.pkl'):
path = get_file(path, origin='https://s3.amazonaws.com/text-datasets/imdb_word_index.pkl', md5_hash='72d94b01291be4ff843198d3b0e1e4d7')
f = open(path, 'rb')
if (sys.version_info < (3,)):
data = cPickle.load(f)
else:
data = cPickle.load(f, encoding='latin1')
f.clo... | null | null | null | the dictionary mapping word indices
| codeqa | def get word index path 'imdb word index pkl' path get file path origin 'https //s 3 amazonaws com/text-datasets/imdb word index pkl' md 5 hash '72 d 94 b 01291 be 4 ff 843198 d 3 b 0 e 1 e 4 d 7 ' f open path 'rb' if sys version info < 3 data c Pickle load f else data c Pickle load f encoding 'latin 1 ' f close return... | null | null | null | null | Question:
What does the code retrieve back to words ?
Code:
def get_word_index(path='imdb_word_index.pkl'):
path = get_file(path, origin='https://s3.amazonaws.com/text-datasets/imdb_word_index.pkl', md5_hash='72d94b01291be4ff843198d3b0e1e4d7')
f = open(path, 'rb')
if (sys.version_info < (3,)):
data = cPickle.l... |
null | null | null | What does the code send to the given user immediately following a moderator action ?
| def send_moderator_action_email(sender_id, recipient_id, intent, exploration_title, email_body):
require_moderator_email_prereqs_are_satisfied()
email_config = feconf.VALID_MODERATOR_ACTIONS[intent]
recipient_user_settings = user_services.get_user_settings(recipient_id)
sender_user_settings = user_services.get_user... | null | null | null | a email
| codeqa | def send moderator action email sender id recipient id intent exploration title email body require moderator email prereqs are satisfied email config feconf VALID MODERATOR ACTIONS[intent]recipient user settings user services get user settings recipient id sender user settings user services get user settings sender id ... | null | null | null | null | Question:
What does the code send to the given user immediately following a moderator action ?
Code:
def send_moderator_action_email(sender_id, recipient_id, intent, exploration_title, email_body):
require_moderator_email_prereqs_are_satisfied()
email_config = feconf.VALID_MODERATOR_ACTIONS[intent]
recipient_use... |
null | null | null | How is g -connected ?
| def is_kl_connected(G, k, l, low_memory=False):
graphOK = True
for edge in G.edges():
(u, v) = edge
if low_memory:
verts = set([u, v])
for i in range(k):
[verts.update(G.neighbors(w)) for w in verts.copy()]
G2 = G.subgraph(verts)
else:
G2 = copy.deepcopy(G)
path = [u, v]
cnt = 0
accept = 0... | null | null | null | locally
| codeqa | def is kl connected G k l low memory False graph OK Truefor edge in G edges u v edgeif low memory verts set [u v] for i in range k [verts update G neighbors w for w in verts copy ]G 2 G subgraph verts else G2 copy deepcopy G path [u v]cnt 0accept 0while path cnt + 1if cnt > l accept 1breakprev ufor w in path if w prev ... | null | null | null | null | Question:
How is g -connected ?
Code:
def is_kl_connected(G, k, l, low_memory=False):
graphOK = True
for edge in G.edges():
(u, v) = edge
if low_memory:
verts = set([u, v])
for i in range(k):
[verts.update(G.neighbors(w)) for w in verts.copy()]
G2 = G.subgraph(verts)
else:
G2 = copy.deepcopy... |
null | null | null | What does the code delete ?
| def delete_snapshot(name, snap_name, runas=None, all=False):
strict = (not all)
name = _sdecode(name)
snap_ids = _validate_snap_name(name, snap_name, strict=strict, runas=runas)
if isinstance(snap_ids, six.string_types):
snap_ids = [snap_ids]
ret = {}
for snap_id in snap_ids:
snap_id = snap_id.strip('{}')
a... | null | null | null | a snapshot
| codeqa | def delete snapshot name snap name runas None all False strict not all name sdecode name snap ids validate snap name name snap name strict strict runas runas if isinstance snap ids six string types snap ids [snap ids]ret {}for snap id in snap ids snap id snap id strip '{}' args [name '--id' snap id]ret[snap id] prlctl ... | null | null | null | null | Question:
What does the code delete ?
Code:
def delete_snapshot(name, snap_name, runas=None, all=False):
strict = (not all)
name = _sdecode(name)
snap_ids = _validate_snap_name(name, snap_name, strict=strict, runas=runas)
if isinstance(snap_ids, six.string_types):
snap_ids = [snap_ids]
ret = {}
for snap_id ... |
null | null | null | What does the code check ?
| def exists_or_mkdir(path, verbose=True):
if (not os.path.exists(path)):
if verbose:
print ('[!] Create %s ...' % path)
os.makedirs(path)
return False
else:
if verbose:
print ('[*] %s exists ...' % path)
return True
| null | null | null | a directory
| codeqa | def exists or mkdir path verbose True if not os path exists path if verbose print '[ ] Create%s ' % path os makedirs path return Falseelse if verbose print '[*]%sexists ' % path return True
| null | null | null | null | Question:
What does the code check ?
Code:
def exists_or_mkdir(path, verbose=True):
if (not os.path.exists(path)):
if verbose:
print ('[!] Create %s ...' % path)
os.makedirs(path)
return False
else:
if verbose:
print ('[*] %s exists ...' % path)
return True
|
null | null | null | What does the code start ?
| def transact():
ctx.db.commit()
ctx.db_transaction = True
| null | null | null | a transaction
| codeqa | def transact ctx db commit ctx db transaction True
| null | null | null | null | Question:
What does the code start ?
Code:
def transact():
ctx.db.commit()
ctx.db_transaction = True
|
null | null | null | In which direction is the user logged ?
| def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
actual_decorator = user_passes_test((lambda u: u.is_authenticated()), login_url=login_url, redirect_field_name=redirect_field_name)
if function:
return actual_decorator(function)
return actual_decorator
| null | null | null | in
| codeqa | def login required function None redirect field name REDIRECT FIELD NAME login url None actual decorator user passes test lambda u u is authenticated login url login url redirect field name redirect field name if function return actual decorator function return actual decorator
| null | null | null | null | Question:
In which direction is the user logged ?
Code:
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
actual_decorator = user_passes_test((lambda u: u.is_authenticated()), login_url=login_url, redirect_field_name=redirect_field_name)
if function:
return actual_decor... |
null | null | null | What does decorator for views check ?
| def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
actual_decorator = user_passes_test((lambda u: u.is_authenticated()), login_url=login_url, redirect_field_name=redirect_field_name)
if function:
return actual_decorator(function)
return actual_decorator
| null | null | null | that the user is logged in
| codeqa | def login required function None redirect field name REDIRECT FIELD NAME login url None actual decorator user passes test lambda u u is authenticated login url login url redirect field name redirect field name if function return actual decorator function return actual decorator
| null | null | null | null | Question:
What does decorator for views check ?
Code:
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
actual_decorator = user_passes_test((lambda u: u.is_authenticated()), login_url=login_url, redirect_field_name=redirect_field_name)
if function:
return actual_decorat... |
null | null | null | What checks that the user is logged in ?
| def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
actual_decorator = user_passes_test((lambda u: u.is_authenticated()), login_url=login_url, redirect_field_name=redirect_field_name)
if function:
return actual_decorator(function)
return actual_decorator
| null | null | null | decorator for views
| codeqa | def login required function None redirect field name REDIRECT FIELD NAME login url None actual decorator user passes test lambda u u is authenticated login url login url redirect field name redirect field name if function return actual decorator function return actual decorator
| null | null | null | null | Question:
What checks that the user is logged in ?
Code:
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
actual_decorator = user_passes_test((lambda u: u.is_authenticated()), login_url=login_url, redirect_field_name=redirect_field_name)
if function:
return actual_deco... |
null | null | null | What does the code get ?
| def _get_objects(obj_type):
lst_objs = []
for key in _db_content[obj_type]:
lst_objs.append(_db_content[obj_type][key])
return lst_objs
| null | null | null | objects of the type
| codeqa | def get objects obj type lst objs []for key in db content[obj type] lst objs append db content[obj type][key] return lst objs
| null | null | null | null | Question:
What does the code get ?
Code:
def _get_objects(obj_type):
lst_objs = []
for key in _db_content[obj_type]:
lst_objs.append(_db_content[obj_type][key])
return lst_objs
|
null | null | null | What does the code create ?
| def make_test_environ_builder(app, path='/', base_url=None, *args, **kwargs):
http_host = app.config.get('SERVER_NAME')
app_root = app.config.get('APPLICATION_ROOT')
if (base_url is None):
url = url_parse(path)
base_url = ('http://%s/' % (url.netloc or http_host or 'localhost'))
if app_root:
base_url += app... | null | null | null | a new test builder with some application defaults thrown in
| codeqa | def make test environ builder app path '/' base url None *args **kwargs http host app config get 'SERVER NAME' app root app config get 'APPLICATION ROOT' if base url is None url url parse path base url 'http //%s/' % url netloc or http host or 'localhost' if app root base url + app root lstrip '/' if url netloc path ur... | null | null | null | null | Question:
What does the code create ?
Code:
def make_test_environ_builder(app, path='/', base_url=None, *args, **kwargs):
http_host = app.config.get('SERVER_NAME')
app_root = app.config.get('APPLICATION_ROOT')
if (base_url is None):
url = url_parse(path)
base_url = ('http://%s/' % (url.netloc or http_host or... |
null | null | null | In which direction did some application defaults throw ?
| def make_test_environ_builder(app, path='/', base_url=None, *args, **kwargs):
http_host = app.config.get('SERVER_NAME')
app_root = app.config.get('APPLICATION_ROOT')
if (base_url is None):
url = url_parse(path)
base_url = ('http://%s/' % (url.netloc or http_host or 'localhost'))
if app_root:
base_url += app... | null | null | null | in
| codeqa | def make test environ builder app path '/' base url None *args **kwargs http host app config get 'SERVER NAME' app root app config get 'APPLICATION ROOT' if base url is None url url parse path base url 'http //%s/' % url netloc or http host or 'localhost' if app root base url + app root lstrip '/' if url netloc path ur... | null | null | null | null | Question:
In which direction did some application defaults throw ?
Code:
def make_test_environ_builder(app, path='/', base_url=None, *args, **kwargs):
http_host = app.config.get('SERVER_NAME')
app_root = app.config.get('APPLICATION_ROOT')
if (base_url is None):
url = url_parse(path)
base_url = ('http://%s/' ... |
null | null | null | What does the code get ?
| def getNewRepository():
return MultiplyRepository()
| null | null | null | new repository
| codeqa | def get New Repository return Multiply Repository
| null | null | null | null | Question:
What does the code get ?
Code:
def getNewRepository():
return MultiplyRepository()
|
null | null | null | What does the code create ?
| def create_connection(conf, new=True):
return rpc_amqp.create_connection(conf, new, rpc_amqp.get_connection_pool(conf, Connection))
| null | null | null | a connection
| codeqa | def create connection conf new True return rpc amqp create connection conf new rpc amqp get connection pool conf Connection
| null | null | null | null | Question:
What does the code create ?
Code:
def create_connection(conf, new=True):
return rpc_amqp.create_connection(conf, new, rpc_amqp.get_connection_pool(conf, Connection))
|
null | null | null | What found in the path ?
| def get_language_from_path(path, supported=None):
if (supported is None):
from django.conf import settings
supported = dict(settings.LANGUAGES)
regex_match = language_code_prefix_re.match(path)
if regex_match:
lang_code = regex_match.group(1)
if ((lang_code in supported) and check_for_language(lang_code)):
... | null | null | null | a valid language - code
| codeqa | def get language from path path supported None if supported is None from django conf import settingssupported dict settings LANGUAGES regex match language code prefix re match path if regex match lang code regex match group 1 if lang code in supported and check for language lang code return lang code
| null | null | null | null | Question:
What found in the path ?
Code:
def get_language_from_path(path, supported=None):
if (supported is None):
from django.conf import settings
supported = dict(settings.LANGUAGES)
regex_match = language_code_prefix_re.match(path)
if regex_match:
lang_code = regex_match.group(1)
if ((lang_code in sup... |
null | null | null | Where did a valid language - code find ?
| def get_language_from_path(path, supported=None):
if (supported is None):
from django.conf import settings
supported = dict(settings.LANGUAGES)
regex_match = language_code_prefix_re.match(path)
if regex_match:
lang_code = regex_match.group(1)
if ((lang_code in supported) and check_for_language(lang_code)):
... | null | null | null | in the path
| codeqa | def get language from path path supported None if supported is None from django conf import settingssupported dict settings LANGUAGES regex match language code prefix re match path if regex match lang code regex match group 1 if lang code in supported and check for language lang code return lang code
| null | null | null | null | Question:
Where did a valid language - code find ?
Code:
def get_language_from_path(path, supported=None):
if (supported is None):
from django.conf import settings
supported = dict(settings.LANGUAGES)
regex_match = language_code_prefix_re.match(path)
if regex_match:
lang_code = regex_match.group(1)
if ((... |
null | null | null | What does the code get ?
| def _get_src(tree_base, source, saltenv='base'):
parsed = _urlparse(source)
sbase = os.path.basename(source)
dest = os.path.join(tree_base, 'SOURCES', sbase)
if parsed.scheme:
lsrc = __salt__['cp.get_url'](source, dest, saltenv=saltenv)
else:
shutil.copy(source, dest)
| null | null | null | the named sources
| codeqa | def get src tree base source saltenv 'base' parsed urlparse source sbase os path basename source dest os path join tree base 'SOURCES' sbase if parsed scheme lsrc salt ['cp get url'] source dest saltenv saltenv else shutil copy source dest
| null | null | null | null | Question:
What does the code get ?
Code:
def _get_src(tree_base, source, saltenv='base'):
parsed = _urlparse(source)
sbase = os.path.basename(source)
dest = os.path.join(tree_base, 'SOURCES', sbase)
if parsed.scheme:
lsrc = __salt__['cp.get_url'](source, dest, saltenv=saltenv)
else:
shutil.copy(source, des... |
null | null | null | Where did the tokens match ?
| def matchPreviousExpr(expr):
rep = Forward()
e2 = expr.copy()
rep <<= e2
def copyTokenToRepeater(s, l, t):
matchTokens = _flatten(t.asList())
def mustMatchTheseTokens(s, l, t):
theseTokens = _flatten(t.asList())
if (theseTokens != matchTokens):
raise ParseException('', 0, '')
rep.setParseAction(must... | null | null | null | in a previous expression
| codeqa | def match Previous Expr expr rep Forward e2 expr copy rep << e2 def copy Token To Repeater s l t match Tokens flatten t as List def must Match These Tokens s l t these Tokens flatten t as List if these Tokens match Tokens raise Parse Exception '' 0 '' rep set Parse Action must Match These Tokens call During Try True ex... | null | null | null | null | Question:
Where did the tokens match ?
Code:
def matchPreviousExpr(expr):
rep = Forward()
e2 = expr.copy()
rep <<= e2
def copyTokenToRepeater(s, l, t):
matchTokens = _flatten(t.asList())
def mustMatchTheseTokens(s, l, t):
theseTokens = _flatten(t.asList())
if (theseTokens != matchTokens):
raise Pa... |
null | null | null | How is an expression defined from the tokens matched in a previous expression ?
| def matchPreviousExpr(expr):
rep = Forward()
e2 = expr.copy()
rep <<= e2
def copyTokenToRepeater(s, l, t):
matchTokens = _flatten(t.asList())
def mustMatchTheseTokens(s, l, t):
theseTokens = _flatten(t.asList())
if (theseTokens != matchTokens):
raise ParseException('', 0, '')
rep.setParseAction(must... | null | null | null | indirectly
| codeqa | def match Previous Expr expr rep Forward e2 expr copy rep << e2 def copy Token To Repeater s l t match Tokens flatten t as List def must Match These Tokens s l t these Tokens flatten t as List if these Tokens match Tokens raise Parse Exception '' 0 '' rep set Parse Action must Match These Tokens call During Try True ex... | null | null | null | null | Question:
How is an expression defined from the tokens matched in a previous expression ?
Code:
def matchPreviousExpr(expr):
rep = Forward()
e2 = expr.copy()
rep <<= e2
def copyTokenToRepeater(s, l, t):
matchTokens = _flatten(t.asList())
def mustMatchTheseTokens(s, l, t):
theseTokens = _flatten(t.asList(... |
null | null | null | What matched in a previous expression ?
| def matchPreviousExpr(expr):
rep = Forward()
e2 = expr.copy()
rep <<= e2
def copyTokenToRepeater(s, l, t):
matchTokens = _flatten(t.asList())
def mustMatchTheseTokens(s, l, t):
theseTokens = _flatten(t.asList())
if (theseTokens != matchTokens):
raise ParseException('', 0, '')
rep.setParseAction(must... | null | null | null | the tokens
| codeqa | def match Previous Expr expr rep Forward e2 expr copy rep << e2 def copy Token To Repeater s l t match Tokens flatten t as List def must Match These Tokens s l t these Tokens flatten t as List if these Tokens match Tokens raise Parse Exception '' 0 '' rep set Parse Action must Match These Tokens call During Try True ex... | null | null | null | null | Question:
What matched in a previous expression ?
Code:
def matchPreviousExpr(expr):
rep = Forward()
e2 = expr.copy()
rep <<= e2
def copyTokenToRepeater(s, l, t):
matchTokens = _flatten(t.asList())
def mustMatchTheseTokens(s, l, t):
theseTokens = _flatten(t.asList())
if (theseTokens != matchTokens):
... |
null | null | null | What does the code get ?
| def getlines(filename, module_globals=None):
if (filename in cache):
return cache[filename][2]
try:
return updatecache(filename, module_globals)
except MemoryError:
clearcache()
return []
| null | null | null | the lines for a file from the cache
| codeqa | def getlines filename module globals None if filename in cache return cache[filename][ 2 ]try return updatecache filename module globals except Memory Error clearcache return []
| null | null | null | null | Question:
What does the code get ?
Code:
def getlines(filename, module_globals=None):
if (filename in cache):
return cache[filename][2]
try:
return updatecache(filename, module_globals)
except MemoryError:
clearcache()
return []
|
null | null | null | How does the code generate the file names in a stored directory tree ?
| def walk_storage(path, topdown=True, onerror=None, followlinks=False, storage=default_storage):
if (not topdown):
raise NotImplementedError
if onerror:
raise NotImplementedError
roots = [path]
while len(roots):
new_roots = []
for root in roots:
(dirs, files) = storage.listdir(root)
files = [force_byte... | null | null | null | by walking the tree top - down
| codeqa | def walk storage path topdown True onerror None followlinks False storage default storage if not topdown raise Not Implemented Errorif onerror raise Not Implemented Errorroots [path]while len roots new roots []for root in roots dirs files storage listdir root files [force bytes f for f in files]dirs [force bytes d for ... | null | null | null | null | Question:
How does the code generate the file names in a stored directory tree ?
Code:
def walk_storage(path, topdown=True, onerror=None, followlinks=False, storage=default_storage):
if (not topdown):
raise NotImplementedError
if onerror:
raise NotImplementedError
roots = [path]
while len(roots):
new_root... |
null | null | null | What does the code generate by walking the tree top - down ?
| def walk_storage(path, topdown=True, onerror=None, followlinks=False, storage=default_storage):
if (not topdown):
raise NotImplementedError
if onerror:
raise NotImplementedError
roots = [path]
while len(roots):
new_roots = []
for root in roots:
(dirs, files) = storage.listdir(root)
files = [force_byte... | null | null | null | the file names in a stored directory tree
| codeqa | def walk storage path topdown True onerror None followlinks False storage default storage if not topdown raise Not Implemented Errorif onerror raise Not Implemented Errorroots [path]while len roots new roots []for root in roots dirs files storage listdir root files [force bytes f for f in files]dirs [force bytes d for ... | null | null | null | null | Question:
What does the code generate by walking the tree top - down ?
Code:
def walk_storage(path, topdown=True, onerror=None, followlinks=False, storage=default_storage):
if (not topdown):
raise NotImplementedError
if onerror:
raise NotImplementedError
roots = [path]
while len(roots):
new_roots = []
f... |
null | null | null | How does the code walk the tree ?
| def walk_storage(path, topdown=True, onerror=None, followlinks=False, storage=default_storage):
if (not topdown):
raise NotImplementedError
if onerror:
raise NotImplementedError
roots = [path]
while len(roots):
new_roots = []
for root in roots:
(dirs, files) = storage.listdir(root)
files = [force_byte... | null | null | null | top - down
| codeqa | def walk storage path topdown True onerror None followlinks False storage default storage if not topdown raise Not Implemented Errorif onerror raise Not Implemented Errorroots [path]while len roots new roots []for root in roots dirs files storage listdir root files [force bytes f for f in files]dirs [force bytes d for ... | null | null | null | null | Question:
How does the code walk the tree ?
Code:
def walk_storage(path, topdown=True, onerror=None, followlinks=False, storage=default_storage):
if (not topdown):
raise NotImplementedError
if onerror:
raise NotImplementedError
roots = [path]
while len(roots):
new_roots = []
for root in roots:
(dirs,... |
null | null | null | What matches the pattern for info files ?
| def is_valid_info_file(path):
if six.PY2:
digest_size = (hashlib.sha1().digestsize * 2)
else:
digest_size = (hashlib.sha1().digest_size * 2)
regexp = (CONF.libvirt.image_info_filename_pattern % {'image': ('([0-9a-f]{%(digest_size)d}|[0-9a-f]{%(digest_size)d}_sm|[0-9a-f]{%(digest_size)d}_[0-9]+)' % {'digest_size'... | null | null | null | a given path
| codeqa | def is valid info file path if six PY 2 digest size hashlib sha 1 digestsize * 2 else digest size hashlib sha 1 digest size * 2 regexp CONF libvirt image info filename pattern % {'image' ' [0 - 9 a-f]{% digest size d} [0 - 9 a-f]{% digest size d} sm [0 - 9 a-f]{% digest size d} [0 - 9 ]+ ' % {'digest size' digest size}... | null | null | null | null | Question:
What matches the pattern for info files ?
Code:
def is_valid_info_file(path):
if six.PY2:
digest_size = (hashlib.sha1().digestsize * 2)
else:
digest_size = (hashlib.sha1().digest_size * 2)
regexp = (CONF.libvirt.image_info_filename_pattern % {'image': ('([0-9a-f]{%(digest_size)d}|[0-9a-f]{%(digest_... |
null | null | null | What does a given path match ?
| def is_valid_info_file(path):
if six.PY2:
digest_size = (hashlib.sha1().digestsize * 2)
else:
digest_size = (hashlib.sha1().digest_size * 2)
regexp = (CONF.libvirt.image_info_filename_pattern % {'image': ('([0-9a-f]{%(digest_size)d}|[0-9a-f]{%(digest_size)d}_sm|[0-9a-f]{%(digest_size)d}_[0-9]+)' % {'digest_size'... | null | null | null | the pattern for info files
| codeqa | def is valid info file path if six PY 2 digest size hashlib sha 1 digestsize * 2 else digest size hashlib sha 1 digest size * 2 regexp CONF libvirt image info filename pattern % {'image' ' [0 - 9 a-f]{% digest size d} [0 - 9 a-f]{% digest size d} sm [0 - 9 a-f]{% digest size d} [0 - 9 ]+ ' % {'digest size' digest size}... | null | null | null | null | Question:
What does a given path match ?
Code:
def is_valid_info_file(path):
if six.PY2:
digest_size = (hashlib.sha1().digestsize * 2)
else:
digest_size = (hashlib.sha1().digest_size * 2)
regexp = (CONF.libvirt.image_info_filename_pattern % {'image': ('([0-9a-f]{%(digest_size)d}|[0-9a-f]{%(digest_size)d}_sm|... |
null | null | null | How did feature represent ?
| def test_feature_representation_without_colors():
feature_file = ojoin('..', 'simple_features', '1st_feature_dir', 'some.feature')
feature = Feature.from_file(feature_file)
assert_lines(feature.represented(), 'Feature: Addition # tests/functional/simple_features/1st_feature_di... | null | null | null | without colors
| codeqa | def test feature representation without colors feature file ojoin ' ' 'simple features' '1 st feature dir' 'some feature' feature Feature from file feature file assert lines feature represented ' Feature Addition#tests/functional/simple features/ 1 st feature dir/some feature 5\n Inordertoavoidsillymistakes#tests/funct... | null | null | null | null | Question:
How did feature represent ?
Code:
def test_feature_representation_without_colors():
feature_file = ojoin('..', 'simple_features', '1st_feature_dir', 'some.feature')
feature = Feature.from_file(feature_file)
assert_lines(feature.represented(), 'Feature: Addition # ... |
null | null | null | What does the code build ?
| def Point(*args, **kwargs):
model = modelcontext(kwargs.pop('model', None))
args = list(args)
try:
d = dict(*args, **kwargs)
except Exception as e:
raise TypeError("can't turn {} and {} into a dict. {}".format(args, kwargs, e))
return dict(((str(k), np.array(v)) for (k, v) in d.items() if (str(k) in ma... | null | null | null | a point
| codeqa | def Point *args **kwargs model modelcontext kwargs pop 'model' None args list args try d dict *args **kwargs except Exception as e raise Type Error "can'tturn{}and{}intoadict {}" format args kwargs e return dict str k np array v for k v in d items if str k in map str model vars
| null | null | null | null | Question:
What does the code build ?
Code:
def Point(*args, **kwargs):
model = modelcontext(kwargs.pop('model', None))
args = list(args)
try:
d = dict(*args, **kwargs)
except Exception as e:
raise TypeError("can't turn {} and {} into a dict. {}".format(args, kwargs, e))
return dict(((str(k), np.arr... |
null | null | null | How do non - maximum suppression apply to all predicted boxes output ?
| def apply_nms(all_boxes, thresh):
num_classes = len(all_boxes)
num_images = len(all_boxes[0])
nms_boxes = [[[] for _ in xrange(num_images)] for _ in xrange(num_classes)]
for cls_ind in xrange(num_classes):
for im_ind in xrange(num_images):
dets = all_boxes[cls_ind][im_ind]
if (dets == []):
continue
k... | null | null | null | by the test_net method
| codeqa | def apply nms all boxes thresh num classes len all boxes num images len all boxes[ 0 ] nms boxes [[[] for in xrange num images ] for in xrange num classes ]for cls ind in xrange num classes for im ind in xrange num images dets all boxes[cls ind][im ind]if dets [] continuekeep nms dets thresh if len keep 0 continuenms b... | null | null | null | null | Question:
How do non - maximum suppression apply to all predicted boxes output ?
Code:
def apply_nms(all_boxes, thresh):
num_classes = len(all_boxes)
num_images = len(all_boxes[0])
nms_boxes = [[[] for _ in xrange(num_images)] for _ in xrange(num_classes)]
for cls_ind in xrange(num_classes):
for im_ind in xra... |
null | null | null | What did the code set ?
| def ylabel(s, *args, **kwargs):
return gca().set_ylabel(s, *args, **kwargs)
| null | null | null | the * y * axis label of the current axis
| codeqa | def ylabel s *args **kwargs return gca set ylabel s *args **kwargs
| null | null | null | null | Question:
What did the code set ?
Code:
def ylabel(s, *args, **kwargs):
return gca().set_ylabel(s, *args, **kwargs)
|
null | null | null | How do the shuffling shuffle seed ?
| def shuffle(lol, seed):
for l in lol:
random.seed(seed)
random.shuffle(l)
| null | null | null | in the same order
| codeqa | def shuffle lol seed for l in lol random seed seed random shuffle l
| null | null | null | null | Question:
How do the shuffling shuffle seed ?
Code:
def shuffle(lol, seed):
for l in lol:
random.seed(seed)
random.shuffle(l)
|
null | null | null | What does the code get ?
| def getWidenedLoop(loop, loopList, outsetLoop, radius):
intersectingWithinLoops = getIntersectingWithinLoops(loop, loopList, outsetLoop)
if (len(intersectingWithinLoops) < 1):
return loop
loopsUnified = boolean_solid.getLoopsUnion(radius, [[loop], intersectingWithinLoops])
if (len(loopsUnified) < 1):
return loo... | null | null | null | the widened loop
| codeqa | def get Widened Loop loop loop List outset Loop radius intersecting Within Loops get Intersecting Within Loops loop loop List outset Loop if len intersecting Within Loops < 1 return looploops Unified boolean solid get Loops Union radius [[loop] intersecting Within Loops] if len loops Unified < 1 return loopreturn eucli... | null | null | null | null | Question:
What does the code get ?
Code:
def getWidenedLoop(loop, loopList, outsetLoop, radius):
intersectingWithinLoops = getIntersectingWithinLoops(loop, loopList, outsetLoop)
if (len(intersectingWithinLoops) < 1):
return loop
loopsUnified = boolean_solid.getLoopsUnion(radius, [[loop], intersectingWithinLoop... |
null | null | null | What does the code get ?
| def getWidenedLoop(loop, loopList, outsetLoop, radius):
intersectingWithinLoops = getIntersectingWithinLoops(loop, loopList, outsetLoop)
if (len(intersectingWithinLoops) < 1):
return loop
loopsUnified = booleansolid.getLoopsUnified(radius, [[loop], intersectingWithinLoops])
if (len(loopsUnified) < 1):
return lo... | null | null | null | the widened loop
| codeqa | def get Widened Loop loop loop List outset Loop radius intersecting Within Loops get Intersecting Within Loops loop loop List outset Loop if len intersecting Within Loops < 1 return looploops Unified booleansolid get Loops Unified radius [[loop] intersecting Within Loops] if len loops Unified < 1 return loopreturn eucl... | null | null | null | null | Question:
What does the code get ?
Code:
def getWidenedLoop(loop, loopList, outsetLoop, radius):
intersectingWithinLoops = getIntersectingWithinLoops(loop, loopList, outsetLoop)
if (len(intersectingWithinLoops) < 1):
return loop
loopsUnified = booleansolid.getLoopsUnified(radius, [[loop], intersectingWithinLoo... |
null | null | null | How did all the classes pass ?
| @memoize
def mixin(*args):
if (len(args) == 1):
return args[0]
name = ('Mixin_%s' % '_'.join((cls.__name__ for cls in args)))
return type(name, args, {})
| null | null | null | as parameters
| codeqa | @memoizedef mixin *args if len args 1 return args[ 0 ]name ' Mixin %s' % ' ' join cls name for cls in args return type name args {}
| null | null | null | null | Question:
How did all the classes pass ?
Code:
@memoize
def mixin(*args):
if (len(args) == 1):
return args[0]
name = ('Mixin_%s' % '_'.join((cls.__name__ for cls in args)))
return type(name, args, {})
|
null | null | null | How does a class that inherits from all the classes passed as parameters create ?
| @memoize
def mixin(*args):
if (len(args) == 1):
return args[0]
name = ('Mixin_%s' % '_'.join((cls.__name__ for cls in args)))
return type(name, args, {})
| null | null | null | dynamically
| codeqa | @memoizedef mixin *args if len args 1 return args[ 0 ]name ' Mixin %s' % ' ' join cls name for cls in args return type name args {}
| null | null | null | null | Question:
How does a class that inherits from all the classes passed as parameters create ?
Code:
@memoize
def mixin(*args):
if (len(args) == 1):
return args[0]
name = ('Mixin_%s' % '_'.join((cls.__name__ for cls in args)))
return type(name, args, {})
|
null | null | null | What does the code convert to seconds ?
| def utctotimestamp(dt):
return total_seconds((dt - epoch))
| null | null | null | a timestamp
| codeqa | def utctotimestamp dt return total seconds dt - epoch
| null | null | null | null | Question:
What does the code convert to seconds ?
Code:
def utctotimestamp(dt):
return total_seconds((dt - epoch))
|
null | null | null | What does the code add to decorated function ?
| def unauthenticated(fnc):
fnc.unauthenticated = True
return fnc
| null | null | null | unauthenticated attribute
| codeqa | def unauthenticated fnc fnc unauthenticated Truereturn fnc
| null | null | null | null | Question:
What does the code add to decorated function ?
Code:
def unauthenticated(fnc):
fnc.unauthenticated = True
return fnc
|
null | null | null | What is setting dictionary to a setting line ?
| def setRepositoryToLine(lineIndex, lines, shortDictionary):
line = lines[lineIndex]
splitLine = line.split(globalSpreadsheetSeparator)
if (len(splitLine) < 2):
return
fileSettingName = splitLine[0]
for shortDictionaryKey in shortDictionary:
if (fileSettingName[:len(shortDictionaryKey)] == shortDictionaryKey):
... | null | null | null | the code set
| codeqa | def set Repository To Line line Index lines short Dictionary line lines[line Index]split Line line split global Spreadsheet Separator if len split Line < 2 returnfile Setting Name split Line[ 0 ]for short Dictionary Key in short Dictionary if file Setting Name[ len short Dictionary Key ] short Dictionary Key short Dict... | null | null | null | null | Question:
What is setting dictionary to a setting line ?
Code:
def setRepositoryToLine(lineIndex, lines, shortDictionary):
line = lines[lineIndex]
splitLine = line.split(globalSpreadsheetSeparator)
if (len(splitLine) < 2):
return
fileSettingName = splitLine[0]
for shortDictionaryKey in shortDictionary:
if ... |
null | null | null | What does the code pull from the site_query data ?
| @non_atomic_requests
def site_series(request, format, group, start, end, field):
(start, end) = get_daterange_or_404(start, end)
group = ('date' if (group == 'day') else group)
series = []
(full_series, keys) = _site_query(group, start, end, field, request)
for row in full_series:
if (field in row['data']):
s... | null | null | null | a single field
| codeqa | @non atomic requestsdef site series request format group start end field start end get daterange or 404 start end group 'date' if group 'day' else group series [] full series keys site query group start end field request for row in full series if field in row['data'] series append {'date' row['date'] 'count' row['data'... | null | null | null | null | Question:
What does the code pull from the site_query data ?
Code:
@non_atomic_requests
def site_series(request, format, group, start, end, field):
(start, end) = get_daterange_or_404(start, end)
group = ('date' if (group == 'day') else group)
series = []
(full_series, keys) = _site_query(group, start, end, fie... |
null | null | null | What do helper create ?
| def _require_user(username, fullname, password=None, is_superuser=False, email=None, alt_src_lang=None):
from accounts.utils import verify_user
from django.contrib.auth import get_user_model
User = get_user_model()
criteria = {'username': username, 'full_name': fullname, 'is_active': True, 'is_superuser': is_superu... | null | null | null | a new user
| codeqa | def require user username fullname password None is superuser False email None alt src lang None from accounts utils import verify userfrom django contrib auth import get user model User get user model criteria {'username' username 'full name' fullname 'is active' True 'is superuser' is superuser} user created User obj... | null | null | null | null | Question:
What do helper create ?
Code:
def _require_user(username, fullname, password=None, is_superuser=False, email=None, alt_src_lang=None):
from accounts.utils import verify_user
from django.contrib.auth import get_user_model
User = get_user_model()
criteria = {'username': username, 'full_name': fullname, ... |
null | null | null | What creates a new user ?
| def _require_user(username, fullname, password=None, is_superuser=False, email=None, alt_src_lang=None):
from accounts.utils import verify_user
from django.contrib.auth import get_user_model
User = get_user_model()
criteria = {'username': username, 'full_name': fullname, 'is_active': True, 'is_superuser': is_superu... | null | null | null | helper
| codeqa | def require user username fullname password None is superuser False email None alt src lang None from accounts utils import verify userfrom django contrib auth import get user model User get user model criteria {'username' username 'full name' fullname 'is active' True 'is superuser' is superuser} user created User obj... | null | null | null | null | Question:
What creates a new user ?
Code:
def _require_user(username, fullname, password=None, is_superuser=False, email=None, alt_src_lang=None):
from accounts.utils import verify_user
from django.contrib.auth import get_user_model
User = get_user_model()
criteria = {'username': username, 'full_name': fullname... |
null | null | null | What passes the given test ?
| def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if test_func(request):
return view_func(request, *args, **kwargs)
path = request.build_ab... | null | null | null | the user
| codeqa | def user passes test test func login url None redirect field name REDIRECT FIELD NAME def decorator view func @wraps view func assigned available attrs view func def wrapped view request *args **kwargs if test func request return view func request *args **kwargs path request build absolute uri resolved login url resolv... | null | null | null | null | Question:
What passes the given test ?
Code:
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if test_func(request):
return view_func(req... |
null | null | null | What does decorator for views check ?
| def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if test_func(request):
return view_func(request, *args, **kwargs)
path = request.build_ab... | null | null | null | that the user passes the given test
| codeqa | def user passes test test func login url None redirect field name REDIRECT FIELD NAME def decorator view func @wraps view func assigned available attrs view func def wrapped view request *args **kwargs if test func request return view func request *args **kwargs path request build absolute uri resolved login url resolv... | null | null | null | null | Question:
What does decorator for views check ?
Code:
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if test_func(request):
return view... |
null | null | null | What does the user pass ?
| def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if test_func(request):
return view_func(request, *args, **kwargs)
path = request.build_ab... | null | null | null | the given test
| codeqa | def user passes test test func login url None redirect field name REDIRECT FIELD NAME def decorator view func @wraps view func assigned available attrs view func def wrapped view request *args **kwargs if test func request return view func request *args **kwargs path request build absolute uri resolved login url resolv... | null | null | null | null | Question:
What does the user pass ?
Code:
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if test_func(request):
return view_func(reques... |
null | null | null | What checks that the user passes the given test ?
| def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if test_func(request):
return view_func(request, *args, **kwargs)
path = request.build_ab... | null | null | null | decorator for views
| codeqa | def user passes test test func login url None redirect field name REDIRECT FIELD NAME def decorator view func @wraps view func assigned available attrs view func def wrapped view request *args **kwargs if test func request return view func request *args **kwargs path request build absolute uri resolved login url resolv... | null | null | null | null | Question:
What checks that the user passes the given test ?
Code:
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if test_func(request):
... |
null | null | null | What does the code convert ?
| def boolify(value, nullable=False, return_string=False):
if isinstance(value, BOOL_COERCEABLE_TYPES):
return bool(value)
val = text_type(value).strip().lower().replace('.', '', 1)
if val.isnumeric():
return bool(float(val))
elif (val in BOOLISH_TRUE):
return True
elif (nullable and (val in NULL_STRINGS)):
... | null | null | null | a number
| codeqa | def boolify value nullable False return string False if isinstance value BOOL COERCEABLE TYPES return bool value val text type value strip lower replace ' ' '' 1 if val isnumeric return bool float val elif val in BOOLISH TRUE return Trueelif nullable and val in NULL STRINGS return Noneelif val in BOOLISH FALSE return F... | null | null | null | null | Question:
What does the code convert ?
Code:
def boolify(value, nullable=False, return_string=False):
if isinstance(value, BOOL_COERCEABLE_TYPES):
return bool(value)
val = text_type(value).strip().lower().replace('.', '', 1)
if val.isnumeric():
return bool(float(val))
elif (val in BOOLISH_TRUE):
return Tr... |
null | null | null | What does the code create ?
| def new_figure_manager_given_figure(num, figure):
canvas = FigureCanvasGTKCairo(figure)
return FigureManagerGTK(canvas, num)
| null | null | null | a new figure manager instance for the given figure
| codeqa | def new figure manager given figure num figure canvas Figure Canvas GTK Cairo figure return Figure Manager GTK canvas num
| null | null | null | null | Question:
What does the code create ?
Code:
def new_figure_manager_given_figure(num, figure):
canvas = FigureCanvasGTKCairo(figure)
return FigureManagerGTK(canvas, num)
|
null | null | null | What does the code normalize ?
| def normalize_excludes(rootpath, excludes):
sep = os.path.sep
f_excludes = []
for exclude in excludes:
if ((not os.path.isabs(exclude)) and (not exclude.startswith(rootpath))):
exclude = os.path.join(rootpath, exclude)
if (not exclude.endswith(sep)):
exclude += sep
f_excludes.append(exclude)
return f_ex... | null | null | null | the excluded directory list
| codeqa | def normalize excludes rootpath excludes sep os path sepf excludes []for exclude in excludes if not os path isabs exclude and not exclude startswith rootpath exclude os path join rootpath exclude if not exclude endswith sep exclude + sepf excludes append exclude return f excludes
| null | null | null | null | Question:
What does the code normalize ?
Code:
def normalize_excludes(rootpath, excludes):
sep = os.path.sep
f_excludes = []
for exclude in excludes:
if ((not os.path.isabs(exclude)) and (not exclude.startswith(rootpath))):
exclude = os.path.join(rootpath, exclude)
if (not exclude.endswith(sep)):
exclu... |
null | null | null | What does the code execute ?
| def capture(context, callable_, *args, **kwargs):
if (not callable(callable_)):
raise exceptions.RuntimeException('capture() function expects a callable as its argument (i.e. capture(func, *args, **kwargs))')
context._push_buffer()
try:
callable_(*args, **kwargs)
finally:
buf = context._pop_buffer(... | null | null | null | the given template def
| codeqa | def capture context callable *args **kwargs if not callable callable raise exceptions Runtime Exception 'capture functionexpectsacallableasitsargument i e capture func *args **kwargs ' context push buffer try callable *args **kwargs finally buf context pop buffer return buf getvalue
| null | null | null | null | Question:
What does the code execute ?
Code:
def capture(context, callable_, *args, **kwargs):
if (not callable(callable_)):
raise exceptions.RuntimeException('capture() function expects a callable as its argument (i.e. capture(func, *args, **kwargs))')
context._push_buffer()
try:
callable_(*args,... |
null | null | null | How do image fetch from glance ?
| def _fetch_image(context, session, instance, name_label, image_id, image_type):
if (image_type == ImageType.DISK_VHD):
vdis = _fetch_vhd_image(context, session, instance, image_id)
else:
if CONF.xenserver.independent_compute:
raise exception.NotSupportedWithOption(operation='Non-VHD images', option='CONF.xens... | null | null | null | based on image type
| codeqa | def fetch image context session instance name label image id image type if image type Image Type DISK VHD vdis fetch vhd image context session instance image id else if CONF xenserver independent compute raise exception Not Supported With Option operation ' Non-VH Dimages' option 'CONF xenserver independent compute' vd... | null | null | null | null | Question:
How do image fetch from glance ?
Code:
def _fetch_image(context, session, instance, name_label, image_id, image_type):
if (image_type == ImageType.DISK_VHD):
vdis = _fetch_vhd_image(context, session, instance, image_id)
else:
if CONF.xenserver.independent_compute:
raise exception.NotSupportedWith... |
null | null | null | What does the code take ?
| def _snapshot_service(service):
_apply_service(service, SonosDevice.snapshot)
| null | null | null | a snapshot
| codeqa | def snapshot service service apply service service Sonos Device snapshot
| null | null | null | null | Question:
What does the code take ?
Code:
def _snapshot_service(service):
_apply_service(service, SonosDevice.snapshot)
|
null | null | null | What does the code generate ?
| def _GenerateMSBuildRulePropsFile(props_path, msbuild_rules):
content = ['Project', {'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003'}]
for rule in msbuild_rules:
content.extend([['PropertyGroup', {'Condition': ("'$(%s)' == '' and '$(%s)' == '' and '$(ConfigurationType)' != 'Makefile'" % (ru... | null | null | null | the
| codeqa | def Generate MS Build Rule Props File props path msbuild rules content [' Project' {'xmlns' 'http //schemas microsoft com/developer/msbuild/ 2003 '}]for rule in msbuild rules content extend [[' Property Group' {' Condition' "'$ %s ' ''and'$ %s ' ''and'$ Configuration Type ' ' Makefile'" % rule before targets rule after... | null | null | null | null | Question:
What does the code generate ?
Code:
def _GenerateMSBuildRulePropsFile(props_path, msbuild_rules):
content = ['Project', {'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003'}]
for rule in msbuild_rules:
content.extend([['PropertyGroup', {'Condition': ("'$(%s)' == '' and '$(%s)' == '' ... |
null | null | null | How does random integer value return ?
| def randomInt(length=4, seed=None):
choice = (random.WichmannHill(seed).choice if (seed is not None) else random.choice)
return int(''.join((choice((string.digits if (_ != 0) else string.digits.replace('0', ''))) for _ in xrange(0, length))))
| null | null | null | with provided number of digits
| codeqa | def random Int length 4 seed None choice random Wichmann Hill seed choice if seed is not None else random choice return int '' join choice string digits if 0 else string digits replace '0 ' '' for in xrange 0 length
| null | null | null | null | Question:
How does random integer value return ?
Code:
def randomInt(length=4, seed=None):
choice = (random.WichmannHill(seed).choice if (seed is not None) else random.choice)
return int(''.join((choice((string.digits if (_ != 0) else string.digits.replace('0', ''))) for _ in xrange(0, length))))
|
null | null | null | Where do hosts define ?
| def test_roles_stripped_env_hosts():
@roles('r1')
def command():
pass
eq_hosts(command, ['a', 'b'], env={'roledefs': spaced_roles})
| null | null | null | in env
| codeqa | def test roles stripped env hosts @roles 'r 1 ' def command passeq hosts command ['a' 'b'] env {'roledefs' spaced roles}
| null | null | null | null | Question:
Where do hosts define ?
Code:
def test_roles_stripped_env_hosts():
@roles('r1')
def command():
pass
eq_hosts(command, ['a', 'b'], env={'roledefs': spaced_roles})
|
null | null | null | What defined in env ?
| def test_roles_stripped_env_hosts():
@roles('r1')
def command():
pass
eq_hosts(command, ['a', 'b'], env={'roledefs': spaced_roles})
| null | null | null | hosts
| codeqa | def test roles stripped env hosts @roles 'r 1 ' def command passeq hosts command ['a' 'b'] env {'roledefs' spaced roles}
| null | null | null | null | Question:
What defined in env ?
Code:
def test_roles_stripped_env_hosts():
@roles('r1')
def command():
pass
eq_hosts(command, ['a', 'b'], env={'roledefs': spaced_roles})
|
null | null | null | What does the code generate ?
| def generate_random_mac(old_mac):
random.seed()
new_mac = old_mac[:8].lower().replace('-', ':')
for i in xrange(0, 6):
if ((i % 2) == 0):
new_mac += ':'
new_mac += '0123456789abcdef'[random.randint(0, 15)]
if (new_mac == old_mac):
new_mac = generate_random_mac(old_mac)
return new_mac
| null | null | null | a random mac address
| codeqa | def generate random mac old mac random seed new mac old mac[ 8] lower replace '-' ' ' for i in xrange 0 6 if i % 2 0 new mac + ' 'new mac + '0123456789 abcdef'[random randint 0 15 ]if new mac old mac new mac generate random mac old mac return new mac
| null | null | null | null | Question:
What does the code generate ?
Code:
def generate_random_mac(old_mac):
random.seed()
new_mac = old_mac[:8].lower().replace('-', ':')
for i in xrange(0, 6):
if ((i % 2) == 0):
new_mac += ':'
new_mac += '0123456789abcdef'[random.randint(0, 15)]
if (new_mac == old_mac):
new_mac = generate_random_... |
null | null | null | When did callback register ?
| def unregister(fn):
callbacks.remove(fn)
| null | null | null | previously
| codeqa | def unregister fn callbacks remove fn
| null | null | null | null | Question:
When did callback register ?
Code:
def unregister(fn):
callbacks.remove(fn)
|
null | null | null | How do chart data source create from array - like list data ?
| def test_area_base_values(test_data):
x = pd.Series(test_data.array_data[0])
y = pd.Series(test_data.array_data[1])
ag = AreaGlyph(x=x, y=y)
assert (ag.source.data['y_values'][0][0] == 0)
assert (ag.source.data['y_values'][0][(-1)] == 0)
| null | null | null | test
| codeqa | def test area base values test data x pd Series test data array data[ 0 ] y pd Series test data array data[ 1 ] ag Area Glyph x x y y assert ag source data['y values'][ 0 ][ 0 ] 0 assert ag source data['y values'][ 0 ][ -1 ] 0
| null | null | null | null | Question:
How do chart data source create from array - like list data ?
Code:
def test_area_base_values(test_data):
x = pd.Series(test_data.array_data[0])
y = pd.Series(test_data.array_data[1])
ag = AreaGlyph(x=x, y=y)
assert (ag.source.data['y_values'][0][0] == 0)
assert (ag.source.data['y_values'][0][(-1)] =... |
null | null | null | How do whitespace transform ?
| def filter_whitespace(mode, text):
if (mode == 'all'):
return text
elif (mode == 'single'):
text = re.sub('([\\t ]+)', ' ', text)
text = re.sub('(\\s*\\n\\s*)', '\n', text)
return text
elif (mode == 'oneline'):
return re.sub('(\\s+)', ' ', text)
else:
raise Exception(('invalid whitespace mode %s' ... | null | null | null | in text
| codeqa | def filter whitespace mode text if mode 'all' return textelif mode 'single' text re sub ' [\\t]+ ' '' text text re sub ' \\s*\\n\\s* ' '\n' text return textelif mode 'oneline' return re sub ' \\s+ ' '' text else raise Exception 'invalidwhitespacemode%s' % mode
| null | null | null | null | Question:
How do whitespace transform ?
Code:
def filter_whitespace(mode, text):
if (mode == 'all'):
return text
elif (mode == 'single'):
text = re.sub('([\\t ]+)', ' ', text)
text = re.sub('(\\s*\\n\\s*)', '\n', text)
return text
elif (mode == 'oneline'):
return re.sub('(\\s+)', ' ', text)
else:
... |
null | null | null | What does it need ?
| def _DoesTargetTypeRequireBuild(target_dict):
return bool(((target_dict['type'] != 'none') or target_dict.get('actions') or target_dict.get('rules')))
| null | null | null | to be built
| codeqa | def Does Target Type Require Build target dict return bool target dict['type'] 'none' or target dict get 'actions' or target dict get 'rules'
| null | null | null | null | Question:
What does it need ?
Code:
def _DoesTargetTypeRequireBuild(target_dict):
return bool(((target_dict['type'] != 'none') or target_dict.get('actions') or target_dict.get('rules')))
|
null | null | null | In which direction does a user log ?
| def logout_user():
user = _get_user()
if ('user_id' in session):
session.pop('user_id')
if ('_fresh' in session):
session.pop('_fresh')
cookie_name = current_app.config.get('REMEMBER_COOKIE_NAME', COOKIE_NAME)
if (cookie_name in request.cookies):
session['remember'] = 'clear'
user_logged_out.send(current_ap... | null | null | null | out
| codeqa | def logout user user get user if 'user id' in session session pop 'user id' if ' fresh' in session session pop ' fresh' cookie name current app config get 'REMEMBER COOKIE NAME' COOKIE NAME if cookie name in request cookies session['remember'] 'clear'user logged out send current app get current object user user current... | null | null | null | null | Question:
In which direction does a user log ?
Code:
def logout_user():
user = _get_user()
if ('user_id' in session):
session.pop('user_id')
if ('_fresh' in session):
session.pop('_fresh')
cookie_name = current_app.config.get('REMEMBER_COOKIE_NAME', COOKIE_NAME)
if (cookie_name in request.cookies):
sessi... |
null | null | null | What does the code delete ?
| def delete(name, runas=None):
return prlctl('delete', _sdecode(name), runas=runas)
| null | null | null | a vm
| codeqa | def delete name runas None return prlctl 'delete' sdecode name runas runas
| null | null | null | null | Question:
What does the code delete ?
Code:
def delete(name, runas=None):
return prlctl('delete', _sdecode(name), runas=runas)
|
null | null | null | What do all tasks match ?
| @log_call
def task_get_all(context, filters=None, marker=None, limit=None, sort_key='created_at', sort_dir='desc'):
_task_soft_delete(context)
filters = (filters or {})
tasks = DATA['tasks'].values()
tasks = _filter_tasks(tasks, filters, context)
tasks = _sort_tasks(tasks, sort_key, sort_dir)
tasks = _paginate_ta... | null | null | null | zero or more filters
| codeqa | @log calldef task get all context filters None marker None limit None sort key 'created at' sort dir 'desc' task soft delete context filters filters or {} tasks DATA['tasks'] values tasks filter tasks tasks filters context tasks sort tasks tasks sort key sort dir tasks paginate tasks context tasks marker limit filters ... | null | null | null | null | Question:
What do all tasks match ?
Code:
@log_call
def task_get_all(context, filters=None, marker=None, limit=None, sort_key='created_at', sort_dir='desc'):
_task_soft_delete(context)
filters = (filters or {})
tasks = DATA['tasks'].values()
tasks = _filter_tasks(tasks, filters, context)
tasks = _sort_tasks(ta... |
null | null | null | What does the code get ?
| @log_call
def task_get_all(context, filters=None, marker=None, limit=None, sort_key='created_at', sort_dir='desc'):
_task_soft_delete(context)
filters = (filters or {})
tasks = DATA['tasks'].values()
tasks = _filter_tasks(tasks, filters, context)
tasks = _sort_tasks(tasks, sort_key, sort_dir)
tasks = _paginate_ta... | null | null | null | all tasks that match zero or more filters
| codeqa | @log calldef task get all context filters None marker None limit None sort key 'created at' sort dir 'desc' task soft delete context filters filters or {} tasks DATA['tasks'] values tasks filter tasks tasks filters context tasks sort tasks tasks sort key sort dir tasks paginate tasks context tasks marker limit filters ... | null | null | null | null | Question:
What does the code get ?
Code:
@log_call
def task_get_all(context, filters=None, marker=None, limit=None, sort_key='created_at', sort_dir='desc'):
_task_soft_delete(context)
filters = (filters or {})
tasks = DATA['tasks'].values()
tasks = _filter_tasks(tasks, filters, context)
tasks = _sort_tasks(tas... |
null | null | null | What match zero or more filters ?
| @log_call
def task_get_all(context, filters=None, marker=None, limit=None, sort_key='created_at', sort_dir='desc'):
_task_soft_delete(context)
filters = (filters or {})
tasks = DATA['tasks'].values()
tasks = _filter_tasks(tasks, filters, context)
tasks = _sort_tasks(tasks, sort_key, sort_dir)
tasks = _paginate_ta... | null | null | null | all tasks
| codeqa | @log calldef task get all context filters None marker None limit None sort key 'created at' sort dir 'desc' task soft delete context filters filters or {} tasks DATA['tasks'] values tasks filter tasks tasks filters context tasks sort tasks tasks sort key sort dir tasks paginate tasks context tasks marker limit filters ... | null | null | null | null | Question:
What match zero or more filters ?
Code:
@log_call
def task_get_all(context, filters=None, marker=None, limit=None, sort_key='created_at', sort_dir='desc'):
_task_soft_delete(context)
filters = (filters or {})
tasks = DATA['tasks'].values()
tasks = _filter_tasks(tasks, filters, context)
tasks = _sort_... |
null | null | null | How is it run ?
| @nottest
def run_tests_if_main():
local_vars = inspect.currentframe().f_back.f_locals
if (not (local_vars.get('__name__', '') == '__main__')):
return
fname = local_vars['__file__']
try:
import faulthandler
faulthandler.enable()
except Exception:
pass
import __main__
try:
import pytest
pytest.main(['-... | null | null | null | as a script
| codeqa | @nottestdef run tests if main local vars inspect currentframe f back f localsif not local vars get ' name ' '' ' main ' returnfname local vars[' file ']try import faulthandlerfaulthandler enable except Exception passimport main try import pytestpytest main ['-s' '--tb short' fname] except Import Error print ' Runningte... | null | null | null | null | Question:
How is it run ?
Code:
@nottest
def run_tests_if_main():
local_vars = inspect.currentframe().f_back.f_locals
if (not (local_vars.get('__name__', '') == '__main__')):
return
fname = local_vars['__file__']
try:
import faulthandler
faulthandler.enable()
except Exception:
pass
import __main__
tr... |
null | null | null | What do point correspondences use ?
| def F_from_ransac(x1, x2, model, maxiter=5000, match_theshold=1e-06):
import ransac
data = vstack((x1, x2))
(F, ransac_data) = ransac.ransac(data.T, model, 8, maxiter, match_theshold, 20, return_all=True)
return (F, ransac_data['inliers'])
| null | null | null | ransac
| codeqa | def F from ransac x1 x2 model maxiter 5000 match theshold 1e- 06 import ransacdata vstack x1 x2 F ransac data ransac ransac data T model 8 maxiter match theshold 20 return all True return F ransac data['inliers']
| null | null | null | null | Question:
What do point correspondences use ?
Code:
def F_from_ransac(x1, x2, model, maxiter=5000, match_theshold=1e-06):
import ransac
data = vstack((x1, x2))
(F, ransac_data) = ransac.ransac(data.T, model, 8, maxiter, match_theshold, 20, return_all=True)
return (F, ransac_data['inliers'])
|
null | null | null | When do total rows grab ?
| def _rows_page_start(iterator, page, response):
total_rows = response.get('totalRows')
if (total_rows is not None):
total_rows = int(total_rows)
iterator.total_rows = total_rows
| null | null | null | after a : class :~ google
| codeqa | def rows page start iterator page response total rows response get 'total Rows' if total rows is not None total rows int total rows iterator total rows total rows
| null | null | null | null | Question:
When do total rows grab ?
Code:
def _rows_page_start(iterator, page, response):
total_rows = response.get('totalRows')
if (total_rows is not None):
total_rows = int(total_rows)
iterator.total_rows = total_rows
|
null | null | null | In which direction do extra content - type parameters echo ?
| def file_upload_content_type_extra(request):
params = {}
for (file_name, uploadedfile) in request.FILES.items():
params[file_name] = {k: force_text(v) for (k, v) in uploadedfile.content_type_extra.items()}
return HttpResponse(json.dumps(params))
| null | null | null | back
| codeqa | def file upload content type extra request params {}for file name uploadedfile in request FILES items params[file name] {k force text v for k v in uploadedfile content type extra items }return Http Response json dumps params
| null | null | null | null | Question:
In which direction do extra content - type parameters echo ?
Code:
def file_upload_content_type_extra(request):
params = {}
for (file_name, uploadedfile) in request.FILES.items():
params[file_name] = {k: force_text(v) for (k, v) in uploadedfile.content_type_extra.items()}
return HttpResponse(json.dum... |
null | null | null | What does the code get ?
| def get_objects(vim, type, properties_to_collect=None, all=False):
if (not properties_to_collect):
properties_to_collect = ['name']
client_factory = vim.client.factory
object_spec = build_object_spec(client_factory, vim.get_service_content().rootFolder, [build_recursive_traversal_spec(client_factory)])
property_s... | null | null | null | the list of objects of the type specified
| codeqa | def get objects vim type properties to collect None all False if not properties to collect properties to collect ['name']client factory vim client factoryobject spec build object spec client factory vim get service content root Folder [build recursive traversal spec client factory ] property spec build property spec cl... | null | null | null | null | Question:
What does the code get ?
Code:
def get_objects(vim, type, properties_to_collect=None, all=False):
if (not properties_to_collect):
properties_to_collect = ['name']
client_factory = vim.client.factory
object_spec = build_object_spec(client_factory, vim.get_service_content().rootFolder, [build_recursive... |
null | null | null | What does the code ensure ?
| def ensure_not_null(obj):
if obj.isNull():
raise QtValueError(obj, null=True)
| null | null | null | a qt object with an
| codeqa | def ensure not null obj if obj is Null raise Qt Value Error obj null True
| null | null | null | null | Question:
What does the code ensure ?
Code:
def ensure_not_null(obj):
if obj.isNull():
raise QtValueError(obj, null=True)
|
null | null | null | When are inline lists used only ?
| def inline_singleton_lists(dsk, dependencies=None):
if (dependencies is None):
dependencies = {k: get_dependencies(dsk, task=v) for (k, v) in dsk.items()}
dependents = reverse_dict(dependencies)
keys = [k for (k, v) in dsk.items() if (istask(v) and v and (v[0] is list) and (len(dependents[k]) == 1))]
dsk = inline... | null | null | null | once
| codeqa | def inline singleton lists dsk dependencies None if dependencies is None dependencies {k get dependencies dsk task v for k v in dsk items }dependents reverse dict dependencies keys [k for k v in dsk items if istask v and v and v[ 0 ] is list and len dependents[k] 1 ]dsk inline dsk keys inline constants False for k in k... | null | null | null | null | Question:
When are inline lists used only ?
Code:
def inline_singleton_lists(dsk, dependencies=None):
if (dependencies is None):
dependencies = {k: get_dependencies(dsk, task=v) for (k, v) in dsk.items()}
dependents = reverse_dict(dependencies)
keys = [k for (k, v) in dsk.items() if (istask(v) and v and (v[0] ... |
null | null | null | What does the code create ?
| def get_remote_image_service(context, image_href):
if ('/' not in str(image_href)):
image_service = get_default_image_service()
return (image_service, image_href)
try:
(image_id, glance_netloc, use_ssl) = _parse_image_ref(image_href)
glance_client = GlanceClientWrapper(context=context, netloc=glance_netloc, u... | null | null | null | an image_service
| codeqa | def get remote image service context image href if '/' not in str image href image service get default image service return image service image href try image id glance netloc use ssl parse image ref image href glance client Glance Client Wrapper context context netloc glance netloc use ssl use ssl except Value Error r... | null | null | null | null | Question:
What does the code create ?
Code:
def get_remote_image_service(context, image_href):
if ('/' not in str(image_href)):
image_service = get_default_image_service()
return (image_service, image_href)
try:
(image_id, glance_netloc, use_ssl) = _parse_image_ref(image_href)
glance_client = GlanceClient... |
null | null | null | What does the code remove from input ?
| def remove_accents(input_str):
nkfd_form = unicodedata.normalize('NFKD', unicode(input_str))
return u''.join([c for c in nkfd_form if (not unicodedata.combining(c))])
| null | null | null | accents
| codeqa | def remove accents input str nkfd form unicodedata normalize 'NFKD' unicode input str return u'' join [c for c in nkfd form if not unicodedata combining c ]
| null | null | null | null | Question:
What does the code remove from input ?
Code:
def remove_accents(input_str):
nkfd_form = unicodedata.normalize('NFKD', unicode(input_str))
return u''.join([c for c in nkfd_form if (not unicodedata.combining(c))])
|
null | null | null | How does the code open a file ?
| def _launch(appfile):
_finder.open(_application_file(('ID ', appfile)))
| null | null | null | thru the finder
| codeqa | def launch appfile finder open application file 'ID' appfile
| null | null | null | null | Question:
How does the code open a file ?
Code:
def _launch(appfile):
_finder.open(_application_file(('ID ', appfile)))
|
null | null | null | How do linear transform apply to data ?
| def test_transform_data():
(n_sensors, n_vertices, n_times) = (10, 20, 4)
kernel = rng.randn(n_vertices, n_sensors)
sens_data = rng.randn(n_sensors, n_times)
vertices = np.arange(n_vertices)
data = np.dot(kernel, sens_data)
for (idx, tmin_idx, tmax_idx) in zip([None, np.arange((n_vertices // 2), n_vertices)], [No... | null | null | null | test
| codeqa | def test transform data n sensors n vertices n times 10 20 4 kernel rng randn n vertices n sensors sens data rng randn n sensors n times vertices np arange n vertices data np dot kernel sens data for idx tmin idx tmax idx in zip [ None np arange n vertices // 2 n vertices ] [ None 1] [ None 3] if idx is None idx use sl... | null | null | null | null | Question:
How do linear transform apply to data ?
Code:
def test_transform_data():
(n_sensors, n_vertices, n_times) = (10, 20, 4)
kernel = rng.randn(n_vertices, n_sensors)
sens_data = rng.randn(n_sensors, n_times)
vertices = np.arange(n_vertices)
data = np.dot(kernel, sens_data)
for (idx, tmin_idx, tmax_idx) ... |
null | null | null | How do the degrees of the two node sets in the bipartite graph b return ?
| def degrees(B, nodes, weight=None):
bottom = set(nodes)
top = (set(B) - bottom)
return (B.degree(top, weight), B.degree(bottom, weight))
| null | null | null | code
| codeqa | def degrees B nodes weight None bottom set nodes top set B - bottom return B degree top weight B degree bottom weight
| null | null | null | null | Question:
How do the degrees of the two node sets in the bipartite graph b return ?
Code:
def degrees(B, nodes, weight=None):
bottom = set(nodes)
top = (set(B) - bottom)
return (B.degree(top, weight), B.degree(bottom, weight))
|
null | null | null | What does the code render ?
| def render_cheetah_tmpl(tmplstr, context, tmplpath=None):
from Cheetah.Template import Template
return str(Template(tmplstr, searchList=[context]))
| null | null | null | a cheetah template
| codeqa | def render cheetah tmpl tmplstr context tmplpath None from Cheetah Template import Templatereturn str Template tmplstr search List [context]
| null | null | null | null | Question:
What does the code render ?
Code:
def render_cheetah_tmpl(tmplstr, context, tmplpath=None):
from Cheetah.Template import Template
return str(Template(tmplstr, searchList=[context]))
|
null | null | null | What did the code set ?
| def set_log_format(log_format, server=_DEFAULT_SERVER):
setting = 'LogPluginClsid'
log_format_types = get_log_format_types()
format_id = log_format_types.get(log_format, None)
if (not format_id):
message = "Invalid log format '{0}' specified. Valid formats: {1}".format(log_format, log_format_types.keys())
... | null | null | null | the active log format
| codeqa | def set log format log format server DEFAULT SERVER setting ' Log Plugin Clsid'log format types get log format types format id log format types get log format None if not format id message " Invalidlogformat'{ 0 }'specified Validformats {1 }" format log format log format types keys raise Salt Invocation Error message L... | null | null | null | null | Question:
What did the code set ?
Code:
def set_log_format(log_format, server=_DEFAULT_SERVER):
setting = 'LogPluginClsid'
log_format_types = get_log_format_types()
format_id = log_format_types.get(log_format, None)
if (not format_id):
message = "Invalid log format '{0}' specified. Valid formats: {1}".... |
null | null | null | What does the code suspend ?
| @utils.arg('server', metavar='<server>', help=_('Name or ID of server.'))
def do_suspend(cs, args):
_find_server(cs, args.server).suspend()
| null | null | null | a server
| codeqa | @utils arg 'server' metavar '<server>' help ' Nameor I Dofserver ' def do suspend cs args find server cs args server suspend
| null | null | null | null | Question:
What does the code suspend ?
Code:
@utils.arg('server', metavar='<server>', help=_('Name or ID of server.'))
def do_suspend(cs, args):
_find_server(cs, args.server).suspend()
|
null | null | null | What did the code set on a backup ?
| def backup_update(context, backup_id, values):
return IMPL.backup_update(context, backup_id, values)
| null | null | null | the given properties
| codeqa | def backup update context backup id values return IMPL backup update context backup id values
| null | null | null | null | Question:
What did the code set on a backup ?
Code:
def backup_update(context, backup_id, values):
return IMPL.backup_update(context, backup_id, values)
|
null | null | null | For what purpose do cover art download ?
| def get_image(mbid, coverid, size=None, entitytype='release'):
if isinstance(coverid, int):
coverid = ('%d' % (coverid,))
if isinstance(size, int):
size = ('%d' % (size,))
return _caa_request(mbid, coverid, size=size, entitytype=entitytype)
| null | null | null | for a release
| codeqa | def get image mbid coverid size None entitytype 'release' if isinstance coverid int coverid '%d' % coverid if isinstance size int size '%d' % size return caa request mbid coverid size size entitytype entitytype
| null | null | null | null | Question:
For what purpose do cover art download ?
Code:
def get_image(mbid, coverid, size=None, entitytype='release'):
if isinstance(coverid, int):
coverid = ('%d' % (coverid,))
if isinstance(size, int):
size = ('%d' % (size,))
return _caa_request(mbid, coverid, size=size, entitytype=entitytype)
|
null | null | null | What do size in pixels convert for a given monitor object in degrees ?
| def pix2deg(pixels, monitor, correctFlat=False):
scrWidthCm = monitor.getWidth()
scrSizePix = monitor.getSizePix()
if (scrSizePix is None):
msg = 'Monitor %s has no known size in pixels (SEE MONITOR CENTER)'
raise ValueError((msg % monitor.name))
if (scrWidthCm is None):
msg = 'Monitor %s has no ... | null | null | null | to size
| codeqa | def pix 2 deg pixels monitor correct Flat False scr Width Cm monitor get Width scr Size Pix monitor get Size Pix if scr Size Pix is None msg ' Monitor%shasnoknownsizeinpixels SEEMONITORCENTER 'raise Value Error msg % monitor name if scr Width Cm is None msg ' Monitor%shasnoknownwidthincm SEEMONITORCENTER 'raise Value E... | null | null | null | null | Question:
What do size in pixels convert for a given monitor object in degrees ?
Code:
def pix2deg(pixels, monitor, correctFlat=False):
scrWidthCm = monitor.getWidth()
scrSizePix = monitor.getSizePix()
if (scrSizePix is None):
msg = 'Monitor %s has no known size in pixels (SEE MONITOR CENTER)'
rais... |
null | null | null | What converts to size for a given monitor object in degrees ?
| def pix2deg(pixels, monitor, correctFlat=False):
scrWidthCm = monitor.getWidth()
scrSizePix = monitor.getSizePix()
if (scrSizePix is None):
msg = 'Monitor %s has no known size in pixels (SEE MONITOR CENTER)'
raise ValueError((msg % monitor.name))
if (scrWidthCm is None):
msg = 'Monitor %s has no ... | null | null | null | size in pixels
| codeqa | def pix 2 deg pixels monitor correct Flat False scr Width Cm monitor get Width scr Size Pix monitor get Size Pix if scr Size Pix is None msg ' Monitor%shasnoknownsizeinpixels SEEMONITORCENTER 'raise Value Error msg % monitor name if scr Width Cm is None msg ' Monitor%shasnoknownwidthincm SEEMONITORCENTER 'raise Value E... | null | null | null | null | Question:
What converts to size for a given monitor object in degrees ?
Code:
def pix2deg(pixels, monitor, correctFlat=False):
scrWidthCm = monitor.getWidth()
scrSizePix = monitor.getSizePix()
if (scrSizePix is None):
msg = 'Monitor %s has no known size in pixels (SEE MONITOR CENTER)'
raise ValueEr... |
null | null | null | What converts to size in degrees ?
| def pix2deg(pixels, monitor, correctFlat=False):
scrWidthCm = monitor.getWidth()
scrSizePix = monitor.getSizePix()
if (scrSizePix is None):
msg = 'Monitor %s has no known size in pixels (SEE MONITOR CENTER)'
raise ValueError((msg % monitor.name))
if (scrWidthCm is None):
msg = 'Monitor %s has no ... | null | null | null | size in pixels
| codeqa | def pix 2 deg pixels monitor correct Flat False scr Width Cm monitor get Width scr Size Pix monitor get Size Pix if scr Size Pix is None msg ' Monitor%shasnoknownsizeinpixels SEEMONITORCENTER 'raise Value Error msg % monitor name if scr Width Cm is None msg ' Monitor%shasnoknownwidthincm SEEMONITORCENTER 'raise Value E... | null | null | null | null | Question:
What converts to size in degrees ?
Code:
def pix2deg(pixels, monitor, correctFlat=False):
scrWidthCm = monitor.getWidth()
scrSizePix = monitor.getSizePix()
if (scrSizePix is None):
msg = 'Monitor %s has no known size in pixels (SEE MONITOR CENTER)'
raise ValueError((msg % monitor.name))
... |
null | null | null | Where do size in pixels convert to size for a given monitor object ?
| def pix2deg(pixels, monitor, correctFlat=False):
scrWidthCm = monitor.getWidth()
scrSizePix = monitor.getSizePix()
if (scrSizePix is None):
msg = 'Monitor %s has no known size in pixels (SEE MONITOR CENTER)'
raise ValueError((msg % monitor.name))
if (scrWidthCm is None):
msg = 'Monitor %s has no ... | null | null | null | in degrees
| codeqa | def pix 2 deg pixels monitor correct Flat False scr Width Cm monitor get Width scr Size Pix monitor get Size Pix if scr Size Pix is None msg ' Monitor%shasnoknownsizeinpixels SEEMONITORCENTER 'raise Value Error msg % monitor name if scr Width Cm is None msg ' Monitor%shasnoknownwidthincm SEEMONITORCENTER 'raise Value E... | null | null | null | null | Question:
Where do size in pixels convert to size for a given monitor object ?
Code:
def pix2deg(pixels, monitor, correctFlat=False):
scrWidthCm = monitor.getWidth()
scrSizePix = monitor.getSizePix()
if (scrSizePix is None):
msg = 'Monitor %s has no known size in pixels (SEE MONITOR CENTER)'
raise ... |
null | null | null | What will an example function turn into a flat list ?
| def flatten_errors(cfg, res, levels=None, results=None):
if (levels is None):
levels = []
results = []
if (res == True):
return sorted(results)
if ((res == False) or isinstance(res, Exception)):
results.append((levels[:], None, res))
if levels:
levels.pop()
return sorted(results)
for (key, val) in li... | null | null | null | a nested dictionary of results
| codeqa | def flatten errors cfg res levels None results None if levels is None levels []results []if res True return sorted results if res False or isinstance res Exception results append levels[ ] None res if levels levels pop return sorted results for key val in list res items if val True continueif isinstance cfg get key col... | null | null | null | null | Question:
What will an example function turn into a flat list ?
Code:
def flatten_errors(cfg, res, levels=None, results=None):
if (levels is None):
levels = []
results = []
if (res == True):
return sorted(results)
if ((res == False) or isinstance(res, Exception)):
results.append((levels[:], None, res))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.