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 | When did indentation level save ?
| def set_indent(TokenClass, implicit=False):
def callback(lexer, match, context):
text = match.group()
if (context.indent < context.next_indent):
context.indent_stack.append(context.indent)
context.indent = context.next_indent
if (not implicit):
context.next_indent += len(text)
(yield (match.start(), TokenClass, text))
context.pos = match.end()
return callback
| null | null | null | previously
| codeqa | def set indent Token Class implicit False def callback lexer match context text match group if context indent < context next indent context indent stack append context indent context indent context next indentif not implicit context next indent + len text yield match start Token Class text context pos match end return callback
| null | null | null | null | Question:
When did indentation level save ?
Code:
def set_indent(TokenClass, implicit=False):
def callback(lexer, match, context):
text = match.group()
if (context.indent < context.next_indent):
context.indent_stack.append(context.indent)
context.indent = context.next_indent
if (not implicit):
context.next_indent += len(text)
(yield (match.start(), TokenClass, text))
context.pos = match.end()
return callback
|
null | null | null | What displays much more information ?
| def DEBUG(x):
LOG_LEVEL('debug')
| null | null | null | the logging verbosity
| codeqa | def DEBUG x LOG LEVEL 'debug'
| null | null | null | null | Question:
What displays much more information ?
Code:
def DEBUG(x):
LOG_LEVEL('debug')
|
null | null | null | What does the logging verbosity display ?
| def DEBUG(x):
LOG_LEVEL('debug')
| null | null | null | much more information
| codeqa | def DEBUG x LOG LEVEL 'debug'
| null | null | null | null | Question:
What does the logging verbosity display ?
Code:
def DEBUG(x):
LOG_LEVEL('debug')
|
null | null | null | What does the code get ?
| def listMediaFiles(path):
if ((not dir) or (not os.path.isdir(path))):
return []
files = []
for curFile in os.listdir(path):
fullCurFile = os.path.join(path, curFile)
if (os.path.isdir(fullCurFile) and (not curFile.startswith(u'.')) and (not (curFile == u'Extras'))):
files += listMediaFiles(fullCurFile)
elif isMediaFile(curFile):
files.append(fullCurFile)
return files
| null | null | null | a list of files possibly containing media in a path
| codeqa | def list Media Files path if not dir or not os path isdir path return []files []for cur File in os listdir path full Cur File os path join path cur File if os path isdir full Cur File and not cur File startswith u' ' and not cur File u' Extras' files + list Media Files full Cur File elif is Media File cur File files append full Cur File return files
| null | null | null | null | Question:
What does the code get ?
Code:
def listMediaFiles(path):
if ((not dir) or (not os.path.isdir(path))):
return []
files = []
for curFile in os.listdir(path):
fullCurFile = os.path.join(path, curFile)
if (os.path.isdir(fullCurFile) and (not curFile.startswith(u'.')) and (not (curFile == u'Extras'))):
files += listMediaFiles(fullCurFile)
elif isMediaFile(curFile):
files.append(fullCurFile)
return files
|
null | null | null | What is containing media in a path ?
| def listMediaFiles(path):
if ((not dir) or (not os.path.isdir(path))):
return []
files = []
for curFile in os.listdir(path):
fullCurFile = os.path.join(path, curFile)
if (os.path.isdir(fullCurFile) and (not curFile.startswith(u'.')) and (not (curFile == u'Extras'))):
files += listMediaFiles(fullCurFile)
elif isMediaFile(curFile):
files.append(fullCurFile)
return files
| null | null | null | files
| codeqa | def list Media Files path if not dir or not os path isdir path return []files []for cur File in os listdir path full Cur File os path join path cur File if os path isdir full Cur File and not cur File startswith u' ' and not cur File u' Extras' files + list Media Files full Cur File elif is Media File cur File files append full Cur File return files
| null | null | null | null | Question:
What is containing media in a path ?
Code:
def listMediaFiles(path):
if ((not dir) or (not os.path.isdir(path))):
return []
files = []
for curFile in os.listdir(path):
fullCurFile = os.path.join(path, curFile)
if (os.path.isdir(fullCurFile) and (not curFile.startswith(u'.')) and (not (curFile == u'Extras'))):
files += listMediaFiles(fullCurFile)
elif isMediaFile(curFile):
files.append(fullCurFile)
return files
|
null | null | null | What is containing media possibly in a path ?
| def listMediaFiles(path):
if ((not dir) or (not os.path.isdir(path))):
return []
files = []
for curFile in os.listdir(path):
fullCurFile = os.path.join(path, curFile)
if (os.path.isdir(fullCurFile) and (not curFile.startswith(u'.')) and (not (curFile == u'Extras'))):
files += listMediaFiles(fullCurFile)
elif isMediaFile(curFile):
files.append(fullCurFile)
return files
| null | null | null | files
| codeqa | def list Media Files path if not dir or not os path isdir path return []files []for cur File in os listdir path full Cur File os path join path cur File if os path isdir full Cur File and not cur File startswith u' ' and not cur File u' Extras' files + list Media Files full Cur File elif is Media File cur File files append full Cur File return files
| null | null | null | null | Question:
What is containing media possibly in a path ?
Code:
def listMediaFiles(path):
if ((not dir) or (not os.path.isdir(path))):
return []
files = []
for curFile in os.listdir(path):
fullCurFile = os.path.join(path, curFile)
if (os.path.isdir(fullCurFile) and (not curFile.startswith(u'.')) and (not (curFile == u'Extras'))):
files += listMediaFiles(fullCurFile)
elif isMediaFile(curFile):
files.append(fullCurFile)
return files
|
null | null | null | What does the code get ?
| @api_versions.wraps('2.23')
@utils.arg('server', metavar='<server>', help=_('Name or ID of server.'))
@utils.arg('migration', metavar='<migration>', help=_('ID of migration.'))
def do_server_migration_show(cs, args):
server = _find_server(cs, args.server)
migration = cs.server_migrations.get(server, args.migration)
utils.print_dict(migration.to_dict())
| null | null | null | the migration of specified server
| codeqa | @api versions wraps '2 23 ' @utils arg 'server' metavar '<server>' help ' Nameor I Dofserver ' @utils arg 'migration' metavar '<migration>' help 'I Dofmigration ' def do server migration show cs args server find server cs args server migration cs server migrations get server args migration utils print dict migration to dict
| null | null | null | null | Question:
What does the code get ?
Code:
@api_versions.wraps('2.23')
@utils.arg('server', metavar='<server>', help=_('Name or ID of server.'))
@utils.arg('migration', metavar='<migration>', help=_('ID of migration.'))
def do_server_migration_show(cs, args):
server = _find_server(cs, args.server)
migration = cs.server_migrations.get(server, args.migration)
utils.print_dict(migration.to_dict())
|
null | null | null | Where are mutated resources discarded ?
| def _protect_original_resources(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
ctx = request.context
if ('resources' in ctx):
orig = ctx.get('protected_resources')
if (not orig):
ctx['protected_resources'] = ctx['resources']
memo = {id(constants.ATTR_NOT_SPECIFIED): constants.ATTR_NOT_SPECIFIED}
ctx['resources'] = copy.deepcopy(ctx['protected_resources'], memo=memo)
return f(*args, **kwargs)
return wrapped
| null | null | null | on retries
| codeqa | def protect original resources f @functools wraps f def wrapped *args **kwargs ctx request contextif 'resources' in ctx orig ctx get 'protected resources' if not orig ctx['protected resources'] ctx['resources']memo {id constants ATTR NOT SPECIFIED constants ATTR NOT SPECIFIED}ctx['resources'] copy deepcopy ctx['protected resources'] memo memo return f *args **kwargs return wrapped
| null | null | null | null | Question:
Where are mutated resources discarded ?
Code:
def _protect_original_resources(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
ctx = request.context
if ('resources' in ctx):
orig = ctx.get('protected_resources')
if (not orig):
ctx['protected_resources'] = ctx['resources']
memo = {id(constants.ATTR_NOT_SPECIFIED): constants.ATTR_NOT_SPECIFIED}
ctx['resources'] = copy.deepcopy(ctx['protected_resources'], memo=memo)
return f(*args, **kwargs)
return wrapped
|
null | null | null | What are discarded on retries ?
| def _protect_original_resources(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
ctx = request.context
if ('resources' in ctx):
orig = ctx.get('protected_resources')
if (not orig):
ctx['protected_resources'] = ctx['resources']
memo = {id(constants.ATTR_NOT_SPECIFIED): constants.ATTR_NOT_SPECIFIED}
ctx['resources'] = copy.deepcopy(ctx['protected_resources'], memo=memo)
return f(*args, **kwargs)
return wrapped
| null | null | null | mutated resources
| codeqa | def protect original resources f @functools wraps f def wrapped *args **kwargs ctx request contextif 'resources' in ctx orig ctx get 'protected resources' if not orig ctx['protected resources'] ctx['resources']memo {id constants ATTR NOT SPECIFIED constants ATTR NOT SPECIFIED}ctx['resources'] copy deepcopy ctx['protected resources'] memo memo return f *args **kwargs return wrapped
| null | null | null | null | Question:
What are discarded on retries ?
Code:
def _protect_original_resources(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
ctx = request.context
if ('resources' in ctx):
orig = ctx.get('protected_resources')
if (not orig):
ctx['protected_resources'] = ctx['resources']
memo = {id(constants.ATTR_NOT_SPECIFIED): constants.ATTR_NOT_SPECIFIED}
ctx['resources'] = copy.deepcopy(ctx['protected_resources'], memo=memo)
return f(*args, **kwargs)
return wrapped
|
null | null | null | What does the code combine to amount ?
| def _sum_counters(*counters_list):
result = {}
for counters in counters_list:
for (group, counter_to_amount) in counters.items():
for (counter, amount) in counter_to_amount.items():
result.setdefault(group, {})
result[group].setdefault(counter, 0)
result[group][counter] += amount
return result
| null | null | null | many maps from group to counter
| codeqa | def sum counters *counters list result {}for counters in counters list for group counter to amount in counters items for counter amount in counter to amount items result setdefault group {} result[group] setdefault counter 0 result[group][counter] + amountreturn result
| null | null | null | null | Question:
What does the code combine to amount ?
Code:
def _sum_counters(*counters_list):
result = {}
for counters in counters_list:
for (group, counter_to_amount) in counters.items():
for (counter, amount) in counter_to_amount.items():
result.setdefault(group, {})
result[group].setdefault(counter, 0)
result[group][counter] += amount
return result
|
null | null | null | For what purpose does the code combine many maps from group to counter ?
| def _sum_counters(*counters_list):
result = {}
for counters in counters_list:
for (group, counter_to_amount) in counters.items():
for (counter, amount) in counter_to_amount.items():
result.setdefault(group, {})
result[group].setdefault(counter, 0)
result[group][counter] += amount
return result
| null | null | null | to amount
| codeqa | def sum counters *counters list result {}for counters in counters list for group counter to amount in counters items for counter amount in counter to amount items result setdefault group {} result[group] setdefault counter 0 result[group][counter] + amountreturn result
| null | null | null | null | Question:
For what purpose does the code combine many maps from group to counter ?
Code:
def _sum_counters(*counters_list):
result = {}
for counters in counters_list:
for (group, counter_to_amount) in counters.items():
for (counter, amount) in counter_to_amount.items():
result.setdefault(group, {})
result[group].setdefault(counter, 0)
result[group][counter] += amount
return result
|
null | null | null | What do we get ?
| def test_reader_macro_error():
try:
macroexpand(tokenize("(dispatch_reader_macro '- '())")[0], HyASTCompiler(__name__))
except HyTypeError as e:
assert ('with the character `-`' in str(e))
| null | null | null | correct error with wrong dispatch character
| codeqa | def test reader macro error try macroexpand tokenize " dispatch reader macro'-' " [0 ] Hy AST Compiler name except Hy Type Error as e assert 'withthecharacter`-`' in str e
| null | null | null | null | Question:
What do we get ?
Code:
def test_reader_macro_error():
try:
macroexpand(tokenize("(dispatch_reader_macro '- '())")[0], HyASTCompiler(__name__))
except HyTypeError as e:
assert ('with the character `-`' in str(e))
|
null | null | null | What returns sessions ?
| def get_sessions_to_clear(user=None, keep_current=False, device=None):
if (not user):
user = frappe.session.user
if (not device):
device = (frappe.session.data.device or u'desktop')
limit = 0
if (user == frappe.session.user):
simultaneous_sessions = (frappe.db.get_value(u'User', user, u'simultaneous_sessions') or 1)
limit = (simultaneous_sessions - 1)
condition = u''
if keep_current:
condition = u' and sid != "{0}"'.format(frappe.db.escape(frappe.session.sid))
return frappe.db.sql_list(u'select sid from tabSessions\n DCTB DCTB where user=%s and device=%s {condition}\n DCTB DCTB order by lastupdate desc limit {limit}, 100'.format(condition=condition, limit=limit), (user, device))
| null | null | null | of the current user
| codeqa | def get sessions to clear user None keep current False device None if not user user frappe session userif not device device frappe session data device or u'desktop' limit 0if user frappe session user simultaneous sessions frappe db get value u' User' user u'simultaneous sessions' or 1 limit simultaneous sessions - 1 condition u''if keep current condition u'andsid "{ 0 }"' format frappe db escape frappe session sid return frappe db sql list u'selectsidfromtab Sessions\n DCTB DCTB whereuser %sanddevice %s{condition}\n DCTB DCTB orderbylastupdatedesclimit{limit} 100 ' format condition condition limit limit user device
| null | null | null | null | Question:
What returns sessions ?
Code:
def get_sessions_to_clear(user=None, keep_current=False, device=None):
if (not user):
user = frappe.session.user
if (not device):
device = (frappe.session.data.device or u'desktop')
limit = 0
if (user == frappe.session.user):
simultaneous_sessions = (frappe.db.get_value(u'User', user, u'simultaneous_sessions') or 1)
limit = (simultaneous_sessions - 1)
condition = u''
if keep_current:
condition = u' and sid != "{0}"'.format(frappe.db.escape(frappe.session.sid))
return frappe.db.sql_list(u'select sid from tabSessions\n DCTB DCTB where user=%s and device=%s {condition}\n DCTB DCTB order by lastupdate desc limit {limit}, 100'.format(condition=condition, limit=limit), (user, device))
|
null | null | null | What does of the current user return ?
| def get_sessions_to_clear(user=None, keep_current=False, device=None):
if (not user):
user = frappe.session.user
if (not device):
device = (frappe.session.data.device or u'desktop')
limit = 0
if (user == frappe.session.user):
simultaneous_sessions = (frappe.db.get_value(u'User', user, u'simultaneous_sessions') or 1)
limit = (simultaneous_sessions - 1)
condition = u''
if keep_current:
condition = u' and sid != "{0}"'.format(frappe.db.escape(frappe.session.sid))
return frappe.db.sql_list(u'select sid from tabSessions\n DCTB DCTB where user=%s and device=%s {condition}\n DCTB DCTB order by lastupdate desc limit {limit}, 100'.format(condition=condition, limit=limit), (user, device))
| null | null | null | sessions
| codeqa | def get sessions to clear user None keep current False device None if not user user frappe session userif not device device frappe session data device or u'desktop' limit 0if user frappe session user simultaneous sessions frappe db get value u' User' user u'simultaneous sessions' or 1 limit simultaneous sessions - 1 condition u''if keep current condition u'andsid "{ 0 }"' format frappe db escape frappe session sid return frappe db sql list u'selectsidfromtab Sessions\n DCTB DCTB whereuser %sanddevice %s{condition}\n DCTB DCTB orderbylastupdatedesclimit{limit} 100 ' format condition condition limit limit user device
| null | null | null | null | Question:
What does of the current user return ?
Code:
def get_sessions_to_clear(user=None, keep_current=False, device=None):
if (not user):
user = frappe.session.user
if (not device):
device = (frappe.session.data.device or u'desktop')
limit = 0
if (user == frappe.session.user):
simultaneous_sessions = (frappe.db.get_value(u'User', user, u'simultaneous_sessions') or 1)
limit = (simultaneous_sessions - 1)
condition = u''
if keep_current:
condition = u' and sid != "{0}"'.format(frappe.db.escape(frappe.session.sid))
return frappe.db.sql_list(u'select sid from tabSessions\n DCTB DCTB where user=%s and device=%s {condition}\n DCTB DCTB order by lastupdate desc limit {limit}, 100'.format(condition=condition, limit=limit), (user, device))
|
null | null | null | How do information on the logged - in user retrieve from ?
| def current():
url = build_url(RESOURCE, route='current')
return request('get', url)
| null | null | null | plotly
| codeqa | def current url build url RESOURCE route 'current' return request 'get' url
| null | null | null | null | Question:
How do information on the logged - in user retrieve from ?
Code:
def current():
url = build_url(RESOURCE, route='current')
return request('get', url)
|
null | null | null | What can have any number of maxima ?
| def shekel(individual, a, c):
return (sum(((1.0 / (c[i] + sum((((individual[j] - aij) ** 2) for (j, aij) in enumerate(a[i]))))) for i in range(len(c)))),)
| null | null | null | the shekel multimodal function
| codeqa | def shekel individual a c return sum 1 0 / c[i] + sum individual[j] - aij ** 2 for j aij in enumerate a[i] for i in range len c
| null | null | null | null | Question:
What can have any number of maxima ?
Code:
def shekel(individual, a, c):
return (sum(((1.0 / (c[i] + sum((((individual[j] - aij) ** 2) for (j, aij) in enumerate(a[i]))))) for i in range(len(c)))),)
|
null | null | null | What can the shekel multimodal function have ?
| def shekel(individual, a, c):
return (sum(((1.0 / (c[i] + sum((((individual[j] - aij) ** 2) for (j, aij) in enumerate(a[i]))))) for i in range(len(c)))),)
| null | null | null | any number of maxima
| codeqa | def shekel individual a c return sum 1 0 / c[i] + sum individual[j] - aij ** 2 for j aij in enumerate a[i] for i in range len c
| null | null | null | null | Question:
What can the shekel multimodal function have ?
Code:
def shekel(individual, a, c):
return (sum(((1.0 / (c[i] + sum((((individual[j] - aij) ** 2) for (j, aij) in enumerate(a[i]))))) for i in range(len(c)))),)
|
null | null | null | How do if possible fix ?
| def checkCompatibility(old, new, prefs=None, fix=True):
if (old == new):
return (1, '')
if (old > new):
(old, new) = (new, old)
msg = ('From %s to %s:' % (old, new))
warning = False
if (old[0:4] < '1.74'):
msg += '\n\nThere were many changes in version 1.74.00 that will break\ncompatibility with older versions. Make sure you read the changelog carefully\nbefore using this version. Do not upgrade to this version halfway through an experiment.\n'
if (fix and ('PatchComponent' not in prefs.builder['hiddenComponents'])):
prefs.builder['hiddenComponents'].append('PatchComponent')
warning = True
if (not warning):
msg += '\nNo known compatibility issues'
return ((not warning), msg)
| null | null | null | automatically
| codeqa | def check Compatibility old new prefs None fix True if old new return 1 '' if old > new old new new old msg ' From%sto%s ' % old new warning Falseif old[ 0 4] < '1 74 ' msg + '\n\n Thereweremanychangesinversion 1 74 00 thatwillbreak\ncompatibilitywitholderversions Makesureyoureadthechangelogcarefully\nbeforeusingthisversion Donotupgradetothisversionhalfwaythroughanexperiment \n'if fix and ' Patch Component' not in prefs builder['hidden Components'] prefs builder['hidden Components'] append ' Patch Component' warning Trueif not warning msg + '\n Noknowncompatibilityissues'return not warning msg
| null | null | null | null | Question:
How do if possible fix ?
Code:
def checkCompatibility(old, new, prefs=None, fix=True):
if (old == new):
return (1, '')
if (old > new):
(old, new) = (new, old)
msg = ('From %s to %s:' % (old, new))
warning = False
if (old[0:4] < '1.74'):
msg += '\n\nThere were many changes in version 1.74.00 that will break\ncompatibility with older versions. Make sure you read the changelog carefully\nbefore using this version. Do not upgrade to this version halfway through an experiment.\n'
if (fix and ('PatchComponent' not in prefs.builder['hiddenComponents'])):
prefs.builder['hiddenComponents'].append('PatchComponent')
warning = True
if (not warning):
msg += '\nNo known compatibility issues'
return ((not warning), msg)
|
null | null | null | How can a class be used ?
| def versioned_base(plugin, version):
return Meta(u'VersionedBase', (object,), {u'__metaclass__': Meta, u'plugin': plugin, u'version': version})
| null | null | null | like base
| codeqa | def versioned base plugin version return Meta u' Versioned Base' object {u' metaclass ' Meta u'plugin' plugin u'version' version}
| null | null | null | null | Question:
How can a class be used ?
Code:
def versioned_base(plugin, version):
return Meta(u'VersionedBase', (object,), {u'__metaclass__': Meta, u'plugin': plugin, u'version': version})
|
null | null | null | What does the code add ?
| def add_taps(module, brew_path, taps):
(failed, unchanged, added, msg) = (False, 0, 0, '')
for tap in taps:
(failed, changed, msg) = add_tap(module, brew_path, tap)
if failed:
break
if changed:
added += 1
else:
unchanged += 1
if failed:
msg = ('added: %d, unchanged: %d, error: ' + msg)
msg = (msg % (added, unchanged))
elif added:
changed = True
msg = ('added: %d, unchanged: %d' % (added, unchanged))
else:
msg = ('added: %d, unchanged: %d' % (added, unchanged))
return (failed, changed, msg)
| null | null | null | one or more taps
| codeqa | def add taps module brew path taps failed unchanged added msg False 0 0 '' for tap in taps failed changed msg add tap module brew path tap if failed breakif changed added + 1else unchanged + 1if failed msg 'added %d unchanged %d error ' + msg msg msg % added unchanged elif added changed Truemsg 'added %d unchanged %d' % added unchanged else msg 'added %d unchanged %d' % added unchanged return failed changed msg
| null | null | null | null | Question:
What does the code add ?
Code:
def add_taps(module, brew_path, taps):
(failed, unchanged, added, msg) = (False, 0, 0, '')
for tap in taps:
(failed, changed, msg) = add_tap(module, brew_path, tap)
if failed:
break
if changed:
added += 1
else:
unchanged += 1
if failed:
msg = ('added: %d, unchanged: %d, error: ' + msg)
msg = (msg % (added, unchanged))
elif added:
changed = True
msg = ('added: %d, unchanged: %d' % (added, unchanged))
else:
msg = ('added: %d, unchanged: %d' % (added, unchanged))
return (failed, changed, msg)
|
null | null | null | What do group add ?
| @require_role(role='super')
def group_add(request):
error = ''
msg = ''
(header_title, path1, path2) = ('\xe6\xb7\xbb\xe5\x8a\xa0\xe7\x94\xa8\xe6\x88\xb7\xe7\xbb\x84', '\xe7\x94\xa8\xe6\x88\xb7\xe7\xae\xa1\xe7\x90\x86', '\xe6\xb7\xbb\xe5\x8a\xa0\xe7\x94\xa8\xe6\x88\xb7\xe7\xbb\x84')
user_all = User.objects.all()
if (request.method == 'POST'):
group_name = request.POST.get('group_name', '')
users_selected = request.POST.getlist('users_selected', '')
comment = request.POST.get('comment', '')
try:
if (not group_name):
error = u'\u7ec4\u540d \u4e0d\u80fd\u4e3a\u7a7a'
raise ServerError(error)
if UserGroup.objects.filter(name=group_name):
error = u'\u7ec4\u540d\u5df2\u5b58\u5728'
raise ServerError(error)
db_add_group(name=group_name, users_id=users_selected, comment=comment)
except ServerError:
pass
except TypeError:
error = u'\u6dfb\u52a0\u5c0f\u7ec4\u5931\u8d25'
else:
msg = (u'\u6dfb\u52a0\u7ec4 %s \u6210\u529f' % group_name)
return my_render('juser/group_add.html', locals(), request)
| null | null | null | view for route
| codeqa | @require role role 'super' def group add request error ''msg '' header title path 1 path 2 '\xe 6 \xb 7 \xbb\xe 5 \x 8 a\xa 0 \xe 7 \x 94 \xa 8 \xe 6 \x 88 \xb 7 \xe 7 \xbb\x 84 ' '\xe 7 \x 94 \xa 8 \xe 6 \x 88 \xb 7 \xe 7 \xae\xa 1 \xe 7 \x 90 \x 86 ' '\xe 6 \xb 7 \xbb\xe 5 \x 8 a\xa 0 \xe 7 \x 94 \xa 8 \xe 6 \x 88 \xb 7 \xe 7 \xbb\x 84 ' user all User objects all if request method 'POST' group name request POST get 'group name' '' users selected request POST getlist 'users selected' '' comment request POST get 'comment' '' try if not group name error u'\u 7 ec 4 \u 540 d\u 4 e 0 d\u 80 fd\u 4 e 3 a\u 7 a 7 a'raise Server Error error if User Group objects filter name group name error u'\u 7 ec 4 \u 540 d\u 5 df 2 \u 5 b 58 \u 5728 'raise Server Error error db add group name group name users id users selected comment comment except Server Error passexcept Type Error error u'\u 6 dfb\u 52 a 0 \u 5 c 0 f\u 7 ec 4 \u 5931 \u 8 d 25 'else msg u'\u 6 dfb\u 52 a 0 \u 7 ec 4 %s\u 6210 \u 529 f' % group name return my render 'juser/group add html' locals request
| null | null | null | null | Question:
What do group add ?
Code:
@require_role(role='super')
def group_add(request):
error = ''
msg = ''
(header_title, path1, path2) = ('\xe6\xb7\xbb\xe5\x8a\xa0\xe7\x94\xa8\xe6\x88\xb7\xe7\xbb\x84', '\xe7\x94\xa8\xe6\x88\xb7\xe7\xae\xa1\xe7\x90\x86', '\xe6\xb7\xbb\xe5\x8a\xa0\xe7\x94\xa8\xe6\x88\xb7\xe7\xbb\x84')
user_all = User.objects.all()
if (request.method == 'POST'):
group_name = request.POST.get('group_name', '')
users_selected = request.POST.getlist('users_selected', '')
comment = request.POST.get('comment', '')
try:
if (not group_name):
error = u'\u7ec4\u540d \u4e0d\u80fd\u4e3a\u7a7a'
raise ServerError(error)
if UserGroup.objects.filter(name=group_name):
error = u'\u7ec4\u540d\u5df2\u5b58\u5728'
raise ServerError(error)
db_add_group(name=group_name, users_id=users_selected, comment=comment)
except ServerError:
pass
except TypeError:
error = u'\u6dfb\u52a0\u5c0f\u7ec4\u5931\u8d25'
else:
msg = (u'\u6dfb\u52a0\u7ec4 %s \u6210\u529f' % group_name)
return my_render('juser/group_add.html', locals(), request)
|
null | null | null | What add view for route ?
| @require_role(role='super')
def group_add(request):
error = ''
msg = ''
(header_title, path1, path2) = ('\xe6\xb7\xbb\xe5\x8a\xa0\xe7\x94\xa8\xe6\x88\xb7\xe7\xbb\x84', '\xe7\x94\xa8\xe6\x88\xb7\xe7\xae\xa1\xe7\x90\x86', '\xe6\xb7\xbb\xe5\x8a\xa0\xe7\x94\xa8\xe6\x88\xb7\xe7\xbb\x84')
user_all = User.objects.all()
if (request.method == 'POST'):
group_name = request.POST.get('group_name', '')
users_selected = request.POST.getlist('users_selected', '')
comment = request.POST.get('comment', '')
try:
if (not group_name):
error = u'\u7ec4\u540d \u4e0d\u80fd\u4e3a\u7a7a'
raise ServerError(error)
if UserGroup.objects.filter(name=group_name):
error = u'\u7ec4\u540d\u5df2\u5b58\u5728'
raise ServerError(error)
db_add_group(name=group_name, users_id=users_selected, comment=comment)
except ServerError:
pass
except TypeError:
error = u'\u6dfb\u52a0\u5c0f\u7ec4\u5931\u8d25'
else:
msg = (u'\u6dfb\u52a0\u7ec4 %s \u6210\u529f' % group_name)
return my_render('juser/group_add.html', locals(), request)
| null | null | null | group
| codeqa | @require role role 'super' def group add request error ''msg '' header title path 1 path 2 '\xe 6 \xb 7 \xbb\xe 5 \x 8 a\xa 0 \xe 7 \x 94 \xa 8 \xe 6 \x 88 \xb 7 \xe 7 \xbb\x 84 ' '\xe 7 \x 94 \xa 8 \xe 6 \x 88 \xb 7 \xe 7 \xae\xa 1 \xe 7 \x 90 \x 86 ' '\xe 6 \xb 7 \xbb\xe 5 \x 8 a\xa 0 \xe 7 \x 94 \xa 8 \xe 6 \x 88 \xb 7 \xe 7 \xbb\x 84 ' user all User objects all if request method 'POST' group name request POST get 'group name' '' users selected request POST getlist 'users selected' '' comment request POST get 'comment' '' try if not group name error u'\u 7 ec 4 \u 540 d\u 4 e 0 d\u 80 fd\u 4 e 3 a\u 7 a 7 a'raise Server Error error if User Group objects filter name group name error u'\u 7 ec 4 \u 540 d\u 5 df 2 \u 5 b 58 \u 5728 'raise Server Error error db add group name group name users id users selected comment comment except Server Error passexcept Type Error error u'\u 6 dfb\u 52 a 0 \u 5 c 0 f\u 7 ec 4 \u 5931 \u 8 d 25 'else msg u'\u 6 dfb\u 52 a 0 \u 7 ec 4 %s\u 6210 \u 529 f' % group name return my render 'juser/group add html' locals request
| null | null | null | null | Question:
What add view for route ?
Code:
@require_role(role='super')
def group_add(request):
error = ''
msg = ''
(header_title, path1, path2) = ('\xe6\xb7\xbb\xe5\x8a\xa0\xe7\x94\xa8\xe6\x88\xb7\xe7\xbb\x84', '\xe7\x94\xa8\xe6\x88\xb7\xe7\xae\xa1\xe7\x90\x86', '\xe6\xb7\xbb\xe5\x8a\xa0\xe7\x94\xa8\xe6\x88\xb7\xe7\xbb\x84')
user_all = User.objects.all()
if (request.method == 'POST'):
group_name = request.POST.get('group_name', '')
users_selected = request.POST.getlist('users_selected', '')
comment = request.POST.get('comment', '')
try:
if (not group_name):
error = u'\u7ec4\u540d \u4e0d\u80fd\u4e3a\u7a7a'
raise ServerError(error)
if UserGroup.objects.filter(name=group_name):
error = u'\u7ec4\u540d\u5df2\u5b58\u5728'
raise ServerError(error)
db_add_group(name=group_name, users_id=users_selected, comment=comment)
except ServerError:
pass
except TypeError:
error = u'\u6dfb\u52a0\u5c0f\u7ec4\u5931\u8d25'
else:
msg = (u'\u6dfb\u52a0\u7ec4 %s \u6210\u529f' % group_name)
return my_render('juser/group_add.html', locals(), request)
|
null | null | null | What did the code set to be used when instantiating a logger ?
| def setLoggerClass(klass):
if (klass != Logger):
if (not issubclass(klass, Logger)):
raise TypeError(('logger not derived from logging.Logger: ' + klass.__name__))
global _loggerClass
_loggerClass = klass
| null | null | null | the class
| codeqa | def set Logger Class klass if klass Logger if not issubclass klass Logger raise Type Error 'loggernotderivedfromlogging Logger ' + klass name global logger Class logger Class klass
| null | null | null | null | Question:
What did the code set to be used when instantiating a logger ?
Code:
def setLoggerClass(klass):
if (klass != Logger):
if (not issubclass(klass, Logger)):
raise TypeError(('logger not derived from logging.Logger: ' + klass.__name__))
global _loggerClass
_loggerClass = klass
|
null | null | null | For what purpose did the code set the class when instantiating a logger ?
| def setLoggerClass(klass):
if (klass != Logger):
if (not issubclass(klass, Logger)):
raise TypeError(('logger not derived from logging.Logger: ' + klass.__name__))
global _loggerClass
_loggerClass = klass
| null | null | null | to be used
| codeqa | def set Logger Class klass if klass Logger if not issubclass klass Logger raise Type Error 'loggernotderivedfromlogging Logger ' + klass name global logger Class logger Class klass
| null | null | null | null | Question:
For what purpose did the code set the class when instantiating a logger ?
Code:
def setLoggerClass(klass):
if (klass != Logger):
if (not issubclass(klass, Logger)):
raise TypeError(('logger not derived from logging.Logger: ' + klass.__name__))
global _loggerClass
_loggerClass = klass
|
null | null | null | When did the code set the class to be used ?
| def setLoggerClass(klass):
if (klass != Logger):
if (not issubclass(klass, Logger)):
raise TypeError(('logger not derived from logging.Logger: ' + klass.__name__))
global _loggerClass
_loggerClass = klass
| null | null | null | when instantiating a logger
| codeqa | def set Logger Class klass if klass Logger if not issubclass klass Logger raise Type Error 'loggernotderivedfromlogging Logger ' + klass name global logger Class logger Class klass
| null | null | null | null | Question:
When did the code set the class to be used ?
Code:
def setLoggerClass(klass):
if (klass != Logger):
if (not issubclass(klass, Logger)):
raise TypeError(('logger not derived from logging.Logger: ' + klass.__name__))
global _loggerClass
_loggerClass = klass
|
null | null | null | How is float formatted ?
| def set_eng_float_format(accuracy=3, use_eng_prefix=False):
set_option('display.float_format', EngFormatter(accuracy, use_eng_prefix))
set_option('display.column_space', max(12, (accuracy + 9)))
| null | null | null | how
| codeqa | def set eng float format accuracy 3 use eng prefix False set option 'display float format' Eng Formatter accuracy use eng prefix set option 'display column space' max 12 accuracy + 9
| null | null | null | null | Question:
How is float formatted ?
Code:
def set_eng_float_format(accuracy=3, use_eng_prefix=False):
set_option('display.float_format', EngFormatter(accuracy, use_eng_prefix))
set_option('display.column_space', max(12, (accuracy + 9)))
|
null | null | null | What does the code get ?
| def get_env_init_command(package):
result = ('gcloud', 'beta', 'emulators', package, 'env-init')
extra = EXTRA.get(package, ())
return (result + extra)
| null | null | null | command line arguments for getting emulator env
| codeqa | def get env init command package result 'gcloud' 'beta' 'emulators' package 'env-init' extra EXTRA get package return result + extra
| null | null | null | null | Question:
What does the code get ?
Code:
def get_env_init_command(package):
result = ('gcloud', 'beta', 'emulators', package, 'env-init')
extra = EXTRA.get(package, ())
return (result + extra)
|
null | null | null | What does custom exception handler return ?
| def json_api_exception_handler(exc, context):
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
errors = []
if response:
message = response.data
if isinstance(exc, TwoFactorRequiredError):
response['X-OSF-OTP'] = 'required; app'
if isinstance(exc, JSONAPIException):
errors.extend([{'source': (exc.source or {}), 'detail': exc.detail, 'meta': (exc.meta or {})}])
elif isinstance(message, dict):
errors.extend(dict_error_formatting(message, None))
else:
if isinstance(message, basestring):
message = [message]
for (index, error) in enumerate(message):
if isinstance(error, dict):
errors.extend(dict_error_formatting(error, index))
else:
errors.append({'detail': error})
response.data = {'errors': errors}
return response
| null | null | null | errors object
| codeqa | def json api exception handler exc context from rest framework views import exception handlerresponse exception handler exc context errors []if response message response dataif isinstance exc Two Factor Required Error response['X-OSF-OTP'] 'required app'if isinstance exc JSONAPI Exception errors extend [{'source' exc source or {} 'detail' exc detail 'meta' exc meta or {} }] elif isinstance message dict errors extend dict error formatting message None else if isinstance message basestring message [message]for index error in enumerate message if isinstance error dict errors extend dict error formatting error index else errors append {'detail' error} response data {'errors' errors}return response
| null | null | null | null | Question:
What does custom exception handler return ?
Code:
def json_api_exception_handler(exc, context):
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
errors = []
if response:
message = response.data
if isinstance(exc, TwoFactorRequiredError):
response['X-OSF-OTP'] = 'required; app'
if isinstance(exc, JSONAPIException):
errors.extend([{'source': (exc.source or {}), 'detail': exc.detail, 'meta': (exc.meta or {})}])
elif isinstance(message, dict):
errors.extend(dict_error_formatting(message, None))
else:
if isinstance(message, basestring):
message = [message]
for (index, error) in enumerate(message):
if isinstance(error, dict):
errors.extend(dict_error_formatting(error, index))
else:
errors.append({'detail': error})
response.data = {'errors': errors}
return response
|
null | null | null | What returns errors object ?
| def json_api_exception_handler(exc, context):
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
errors = []
if response:
message = response.data
if isinstance(exc, TwoFactorRequiredError):
response['X-OSF-OTP'] = 'required; app'
if isinstance(exc, JSONAPIException):
errors.extend([{'source': (exc.source or {}), 'detail': exc.detail, 'meta': (exc.meta or {})}])
elif isinstance(message, dict):
errors.extend(dict_error_formatting(message, None))
else:
if isinstance(message, basestring):
message = [message]
for (index, error) in enumerate(message):
if isinstance(error, dict):
errors.extend(dict_error_formatting(error, index))
else:
errors.append({'detail': error})
response.data = {'errors': errors}
return response
| null | null | null | custom exception handler
| codeqa | def json api exception handler exc context from rest framework views import exception handlerresponse exception handler exc context errors []if response message response dataif isinstance exc Two Factor Required Error response['X-OSF-OTP'] 'required app'if isinstance exc JSONAPI Exception errors extend [{'source' exc source or {} 'detail' exc detail 'meta' exc meta or {} }] elif isinstance message dict errors extend dict error formatting message None else if isinstance message basestring message [message]for index error in enumerate message if isinstance error dict errors extend dict error formatting error index else errors append {'detail' error} response data {'errors' errors}return response
| null | null | null | null | Question:
What returns errors object ?
Code:
def json_api_exception_handler(exc, context):
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
errors = []
if response:
message = response.data
if isinstance(exc, TwoFactorRequiredError):
response['X-OSF-OTP'] = 'required; app'
if isinstance(exc, JSONAPIException):
errors.extend([{'source': (exc.source or {}), 'detail': exc.detail, 'meta': (exc.meta or {})}])
elif isinstance(message, dict):
errors.extend(dict_error_formatting(message, None))
else:
if isinstance(message, basestring):
message = [message]
for (index, error) in enumerate(message):
if isinstance(error, dict):
errors.extend(dict_error_formatting(error, index))
else:
errors.append({'detail': error})
response.data = {'errors': errors}
return response
|
null | null | null | What does the code get ?
| @register.tag(name='get_inline_types')
def do_get_inline_types(parser, token):
try:
(tag_name, arg) = token.contents.split(None, 1)
except ValueError:
raise template.TemplateSyntaxError, ('%s tag requires arguments' % token.contents.split()[0])
m = re.search('as (\\w+)', arg)
if (not m):
raise template.TemplateSyntaxError, ('%s tag had invalid arguments' % tag_name)
var_name = m.groups()[0]
return InlineTypes(var_name)
| null | null | null | all inline types
| codeqa | @register tag name 'get inline types' def do get inline types parser token try tag name arg token contents split None 1 except Value Error raise template Template Syntax Error '%stagrequiresarguments' % token contents split [0 ] m re search 'as \\w+ ' arg if not m raise template Template Syntax Error '%staghadinvalidarguments' % tag name var name m groups [0 ]return Inline Types var name
| null | null | null | null | Question:
What does the code get ?
Code:
@register.tag(name='get_inline_types')
def do_get_inline_types(parser, token):
try:
(tag_name, arg) = token.contents.split(None, 1)
except ValueError:
raise template.TemplateSyntaxError, ('%s tag requires arguments' % token.contents.split()[0])
m = re.search('as (\\w+)', arg)
if (not m):
raise template.TemplateSyntaxError, ('%s tag had invalid arguments' % tag_name)
var_name = m.groups()[0]
return InlineTypes(var_name)
|
null | null | null | What does the code compute ?
| def compute_min_alignment_length(seqs_f, fraction=0.75):
med_length = median([len(s) for (_, s) in parse_fasta(seqs_f)])
return int((med_length * fraction))
| null | null | null | the min alignment length
| codeqa | def compute min alignment length seqs f fraction 0 75 med length median [len s for s in parse fasta seqs f ] return int med length * fraction
| null | null | null | null | Question:
What does the code compute ?
Code:
def compute_min_alignment_length(seqs_f, fraction=0.75):
med_length = median([len(s) for (_, s) in parse_fasta(seqs_f)])
return int((med_length * fraction))
|
null | null | null | Where is a key element ?
| def dictfind(dictionary, element):
for (key, value) in iteritems(dictionary):
if (element is value):
return key
| null | null | null | in dictionary
| codeqa | def dictfind dictionary element for key value in iteritems dictionary if element is value return key
| null | null | null | null | Question:
Where is a key element ?
Code:
def dictfind(dictionary, element):
for (key, value) in iteritems(dictionary):
if (element is value):
return key
|
null | null | null | How did job be disabled ?
| def disable_job(name=None):
if (not name):
raise SaltInvocationError('Required parameter `name` is missing.')
server = _connect()
if (not job_exists(name)):
raise SaltInvocationError('Job `{0}` does not exists.'.format(name))
try:
server.disable_job(name)
except jenkins.JenkinsException as err:
raise SaltInvocationError('Something went wrong {0}.'.format(err))
return True
| null | null | null | successfully
| codeqa | def disable job name None if not name raise Salt Invocation Error ' Requiredparameter`name`ismissing ' server connect if not job exists name raise Salt Invocation Error ' Job`{ 0 }`doesnotexists ' format name try server disable job name except jenkins Jenkins Exception as err raise Salt Invocation Error ' Somethingwentwrong{ 0 } ' format err return True
| null | null | null | null | Question:
How did job be disabled ?
Code:
def disable_job(name=None):
if (not name):
raise SaltInvocationError('Required parameter `name` is missing.')
server = _connect()
if (not job_exists(name)):
raise SaltInvocationError('Job `{0}` does not exists.'.format(name))
try:
server.disable_job(name)
except jenkins.JenkinsException as err:
raise SaltInvocationError('Something went wrong {0}.'.format(err))
return True
|
null | null | null | What does return true be ?
| def disable_job(name=None):
if (not name):
raise SaltInvocationError('Required parameter `name` is missing.')
server = _connect()
if (not job_exists(name)):
raise SaltInvocationError('Job `{0}` does not exists.'.format(name))
try:
server.disable_job(name)
except jenkins.JenkinsException as err:
raise SaltInvocationError('Something went wrong {0}.'.format(err))
return True
| null | null | null | job is disabled successfully
| codeqa | def disable job name None if not name raise Salt Invocation Error ' Requiredparameter`name`ismissing ' server connect if not job exists name raise Salt Invocation Error ' Job`{ 0 }`doesnotexists ' format name try server disable job name except jenkins Jenkins Exception as err raise Salt Invocation Error ' Somethingwentwrong{ 0 } ' format err return True
| null | null | null | null | Question:
What does return true be ?
Code:
def disable_job(name=None):
if (not name):
raise SaltInvocationError('Required parameter `name` is missing.')
server = _connect()
if (not job_exists(name)):
raise SaltInvocationError('Job `{0}` does not exists.'.format(name))
try:
server.disable_job(name)
except jenkins.JenkinsException as err:
raise SaltInvocationError('Something went wrong {0}.'.format(err))
return True
|
null | null | null | What is job is disabled successfully ?
| def disable_job(name=None):
if (not name):
raise SaltInvocationError('Required parameter `name` is missing.')
server = _connect()
if (not job_exists(name)):
raise SaltInvocationError('Job `{0}` does not exists.'.format(name))
try:
server.disable_job(name)
except jenkins.JenkinsException as err:
raise SaltInvocationError('Something went wrong {0}.'.format(err))
return True
| null | null | null | return true
| codeqa | def disable job name None if not name raise Salt Invocation Error ' Requiredparameter`name`ismissing ' server connect if not job exists name raise Salt Invocation Error ' Job`{ 0 }`doesnotexists ' format name try server disable job name except jenkins Jenkins Exception as err raise Salt Invocation Error ' Somethingwentwrong{ 0 } ' format err return True
| null | null | null | null | Question:
What is job is disabled successfully ?
Code:
def disable_job(name=None):
if (not name):
raise SaltInvocationError('Required parameter `name` is missing.')
server = _connect()
if (not job_exists(name)):
raise SaltInvocationError('Job `{0}` does not exists.'.format(name))
try:
server.disable_job(name)
except jenkins.JenkinsException as err:
raise SaltInvocationError('Something went wrong {0}.'.format(err))
return True
|
null | null | null | How is job disabled ?
| def disable_job(name=None):
if (not name):
raise SaltInvocationError('Required parameter `name` is missing.')
server = _connect()
if (not job_exists(name)):
raise SaltInvocationError('Job `{0}` does not exists.'.format(name))
try:
server.disable_job(name)
except jenkins.JenkinsException as err:
raise SaltInvocationError('Something went wrong {0}.'.format(err))
return True
| null | null | null | successfully
| codeqa | def disable job name None if not name raise Salt Invocation Error ' Requiredparameter`name`ismissing ' server connect if not job exists name raise Salt Invocation Error ' Job`{ 0 }`doesnotexists ' format name try server disable job name except jenkins Jenkins Exception as err raise Salt Invocation Error ' Somethingwentwrong{ 0 } ' format err return True
| null | null | null | null | Question:
How is job disabled ?
Code:
def disable_job(name=None):
if (not name):
raise SaltInvocationError('Required parameter `name` is missing.')
server = _connect()
if (not job_exists(name)):
raise SaltInvocationError('Job `{0}` does not exists.'.format(name))
try:
server.disable_job(name)
except jenkins.JenkinsException as err:
raise SaltInvocationError('Something went wrong {0}.'.format(err))
return True
|
null | null | null | What converts to an abstract object tree ?
| def jellyToAOT(obj):
return AOTJellier().jelly(obj)
| null | null | null | an object
| codeqa | def jelly To AOT obj return AOT Jellier jelly obj
| null | null | null | null | Question:
What converts to an abstract object tree ?
Code:
def jellyToAOT(obj):
return AOTJellier().jelly(obj)
|
null | null | null | How does a text in the console write ?
| def sys_write_flush(s):
sys.stdout.write(s)
sys.stdout.flush()
| null | null | null | without delay
| codeqa | def sys write flush s sys stdout write s sys stdout flush
| null | null | null | null | Question:
How does a text in the console write ?
Code:
def sys_write_flush(s):
sys.stdout.write(s)
sys.stdout.flush()
|
null | null | null | What does the code get ?
| def get_all_node_subscriptions(user, node, user_subscriptions=None):
if (not user_subscriptions):
user_subscriptions = get_all_user_subscriptions(user)
for subscription in user_subscriptions:
if (subscription and (subscription.owner == node)):
(yield subscription)
| null | null | null | all subscription objects for a node that the user is subscribed to
| codeqa | def get all node subscriptions user node user subscriptions None if not user subscriptions user subscriptions get all user subscriptions user for subscription in user subscriptions if subscription and subscription owner node yield subscription
| null | null | null | null | Question:
What does the code get ?
Code:
def get_all_node_subscriptions(user, node, user_subscriptions=None):
if (not user_subscriptions):
user_subscriptions = get_all_user_subscriptions(user)
for subscription in user_subscriptions:
if (subscription and (subscription.owner == node)):
(yield subscription)
|
null | null | null | What does the code get from the mine based on the target ?
| def get(tgt, fun, tgt_type='glob', roster='flat'):
opts = copy.deepcopy(__context__['master_opts'])
minopts = copy.deepcopy(__opts__)
opts.update(minopts)
if roster:
opts['roster'] = roster
opts['argv'] = [fun]
opts['selected_target_option'] = tgt_type
opts['tgt'] = tgt
opts['arg'] = []
ssh = salt.client.ssh.SSH(opts)
rets = {}
for ret in ssh.run_iter(mine=True):
rets.update(ret)
cret = {}
for host in rets:
if ('return' in rets[host]):
cret[host] = rets[host]['return']
else:
cret[host] = rets[host]
return cret
| null | null | null | data
| codeqa | def get tgt fun tgt type 'glob' roster 'flat' opts copy deepcopy context ['master opts'] minopts copy deepcopy opts opts update minopts if roster opts['roster'] rosteropts['argv'] [fun]opts['selected target option'] tgt typeopts['tgt'] tgtopts['arg'] []ssh salt client ssh SSH opts rets {}for ret in ssh run iter mine True rets update ret cret {}for host in rets if 'return' in rets[host] cret[host] rets[host]['return']else cret[host] rets[host]return cret
| null | null | null | null | Question:
What does the code get from the mine based on the target ?
Code:
def get(tgt, fun, tgt_type='glob', roster='flat'):
opts = copy.deepcopy(__context__['master_opts'])
minopts = copy.deepcopy(__opts__)
opts.update(minopts)
if roster:
opts['roster'] = roster
opts['argv'] = [fun]
opts['selected_target_option'] = tgt_type
opts['tgt'] = tgt
opts['arg'] = []
ssh = salt.client.ssh.SSH(opts)
rets = {}
for ret in ssh.run_iter(mine=True):
rets.update(ret)
cret = {}
for host in rets:
if ('return' in rets[host]):
cret[host] = rets[host]['return']
else:
cret[host] = rets[host]
return cret
|
null | null | null | What does the code compute ?
| def _dipole_forwards(fwd_data, whitener, rr, n_jobs=1):
B = _compute_forwards_meeg(rr, fwd_data, n_jobs, verbose=False)
B = np.concatenate(B, axis=1)
B_orig = B.copy()
B = np.dot(B, whitener.T)
scales = np.ones(3)
return (B, B_orig, scales)
| null | null | null | the forward solution
| codeqa | def dipole forwards fwd data whitener rr n jobs 1 B compute forwards meeg rr fwd data n jobs verbose False B np concatenate B axis 1 B orig B copy B np dot B whitener T scales np ones 3 return B B orig scales
| null | null | null | null | Question:
What does the code compute ?
Code:
def _dipole_forwards(fwd_data, whitener, rr, n_jobs=1):
B = _compute_forwards_meeg(rr, fwd_data, n_jobs, verbose=False)
B = np.concatenate(B, axis=1)
B_orig = B.copy()
B = np.dot(B, whitener.T)
scales = np.ones(3)
return (B, B_orig, scales)
|
null | null | null | What does the code do ?
| def _dipole_forwards(fwd_data, whitener, rr, n_jobs=1):
B = _compute_forwards_meeg(rr, fwd_data, n_jobs, verbose=False)
B = np.concatenate(B, axis=1)
B_orig = B.copy()
B = np.dot(B, whitener.T)
scales = np.ones(3)
return (B, B_orig, scales)
| null | null | null | other nice stuff
| codeqa | def dipole forwards fwd data whitener rr n jobs 1 B compute forwards meeg rr fwd data n jobs verbose False B np concatenate B axis 1 B orig B copy B np dot B whitener T scales np ones 3 return B B orig scales
| null | null | null | null | Question:
What does the code do ?
Code:
def _dipole_forwards(fwd_data, whitener, rr, n_jobs=1):
B = _compute_forwards_meeg(rr, fwd_data, n_jobs, verbose=False)
B = np.concatenate(B, axis=1)
B_orig = B.copy()
B = np.dot(B, whitener.T)
scales = np.ones(3)
return (B, B_orig, scales)
|
null | null | null | What does the code decode ?
| def decode(st):
l = []
_i.expressionReceived = l.append
try:
_i.dataReceived(st)
finally:
_i.buffer = ''
del _i.expressionReceived
return l[0]
| null | null | null | a banana - encoded string
| codeqa | def decode st l [] i expression Received l appendtry i data Received st finally i buffer ''del i expression Receivedreturn l[ 0 ]
| null | null | null | null | Question:
What does the code decode ?
Code:
def decode(st):
l = []
_i.expressionReceived = l.append
try:
_i.dataReceived(st)
finally:
_i.buffer = ''
del _i.expressionReceived
return l[0]
|
null | null | null | How does the code run on all hosts in net ?
| def ifconfigTest(net):
hosts = net.hosts
for host in hosts:
info(host.cmd('ifconfig'))
| null | null | null | ifconfig
| codeqa | def ifconfig Test net hosts net hostsfor host in hosts info host cmd 'ifconfig'
| null | null | null | null | Question:
How does the code run on all hosts in net ?
Code:
def ifconfigTest(net):
hosts = net.hosts
for host in hosts:
info(host.cmd('ifconfig'))
|
null | null | null | What do decorator skip if package is not available ?
| def requires_module(function, name, call=None):
call = (('import %s' % name) if (call is None) else call)
try:
from nose.plugins.skip import SkipTest
except ImportError:
SkipTest = AssertionError
@wraps(function)
def dec(*args, **kwargs):
try:
exec call in globals(), locals()
except Exception as exc:
raise SkipTest(('Test %s skipped, requires %s. Got exception (%s)' % (function.__name__, name, exc)))
return function(*args, **kwargs)
return dec
| null | null | null | test
| codeqa | def requires module function name call None call 'import%s' % name if call is None else call try from nose plugins skip import Skip Testexcept Import Error Skip Test Assertion Error@wraps function def dec *args **kwargs try exec call in globals locals except Exception as exc raise Skip Test ' Test%sskipped requires%s Gotexception %s ' % function name name exc return function *args **kwargs return dec
| null | null | null | null | Question:
What do decorator skip if package is not available ?
Code:
def requires_module(function, name, call=None):
call = (('import %s' % name) if (call is None) else call)
try:
from nose.plugins.skip import SkipTest
except ImportError:
SkipTest = AssertionError
@wraps(function)
def dec(*args, **kwargs):
try:
exec call in globals(), locals()
except Exception as exc:
raise SkipTest(('Test %s skipped, requires %s. Got exception (%s)' % (function.__name__, name, exc)))
return function(*args, **kwargs)
return dec
|
null | null | null | What skips test if package is not available ?
| def requires_module(function, name, call=None):
call = (('import %s' % name) if (call is None) else call)
try:
from nose.plugins.skip import SkipTest
except ImportError:
SkipTest = AssertionError
@wraps(function)
def dec(*args, **kwargs):
try:
exec call in globals(), locals()
except Exception as exc:
raise SkipTest(('Test %s skipped, requires %s. Got exception (%s)' % (function.__name__, name, exc)))
return function(*args, **kwargs)
return dec
| null | null | null | decorator
| codeqa | def requires module function name call None call 'import%s' % name if call is None else call try from nose plugins skip import Skip Testexcept Import Error Skip Test Assertion Error@wraps function def dec *args **kwargs try exec call in globals locals except Exception as exc raise Skip Test ' Test%sskipped requires%s Gotexception %s ' % function name name exc return function *args **kwargs return dec
| null | null | null | null | Question:
What skips test if package is not available ?
Code:
def requires_module(function, name, call=None):
call = (('import %s' % name) if (call is None) else call)
try:
from nose.plugins.skip import SkipTest
except ImportError:
SkipTest = AssertionError
@wraps(function)
def dec(*args, **kwargs):
try:
exec call in globals(), locals()
except Exception as exc:
raise SkipTest(('Test %s skipped, requires %s. Got exception (%s)' % (function.__name__, name, exc)))
return function(*args, **kwargs)
return dec
|
null | null | null | What does the code write ?
| def load_yaml(fname, string):
FILES[fname] = string
with patch_yaml_files(FILES):
return load_yaml_config_file(fname)
| null | null | null | a string to file
| codeqa | def load yaml fname string FILES[fname] stringwith patch yaml files FILES return load yaml config file fname
| null | null | null | null | Question:
What does the code write ?
Code:
def load_yaml(fname, string):
FILES[fname] = string
with patch_yaml_files(FILES):
return load_yaml_config_file(fname)
|
null | null | null | What does the code add ?
| def add_cli_options():
CONF.unregister_opt(sql_connection_opt)
CONF.register_cli_opt(sql_connection_opt)
| null | null | null | any configuration options that the db layer might have
| codeqa | def add cli options CONF unregister opt sql connection opt CONF register cli opt sql connection opt
| null | null | null | null | Question:
What does the code add ?
Code:
def add_cli_options():
CONF.unregister_opt(sql_connection_opt)
CONF.register_cli_opt(sql_connection_opt)
|
null | null | null | What finds in the directories listed in path ?
| def _find_executable(executable, path=None):
if (path is None):
path = os.environ['PATH']
paths = path.split(os.pathsep)
(base, ext) = os.path.splitext(executable)
if (((sys.platform == 'win32') or (os.name == 'os2')) and (ext != '.exe')):
executable = (executable + '.exe')
if (not os.path.isfile(executable)):
for p in paths:
f = os.path.join(p, executable)
if os.path.isfile(f):
return f
return None
else:
return executable
| null | null | null | executable
| codeqa | def find executable executable path None if path is None path os environ['PATH']paths path split os pathsep base ext os path splitext executable if sys platform 'win 32 ' or os name 'os 2 ' and ext ' exe' executable executable + ' exe' if not os path isfile executable for p in paths f os path join p executable if os path isfile f return freturn Noneelse return executable
| null | null | null | null | Question:
What finds in the directories listed in path ?
Code:
def _find_executable(executable, path=None):
if (path is None):
path = os.environ['PATH']
paths = path.split(os.pathsep)
(base, ext) = os.path.splitext(executable)
if (((sys.platform == 'win32') or (os.name == 'os2')) and (ext != '.exe')):
executable = (executable + '.exe')
if (not os.path.isfile(executable)):
for p in paths:
f = os.path.join(p, executable)
if os.path.isfile(f):
return f
return None
else:
return executable
|
null | null | null | Where does executable find ?
| def _find_executable(executable, path=None):
if (path is None):
path = os.environ['PATH']
paths = path.split(os.pathsep)
(base, ext) = os.path.splitext(executable)
if (((sys.platform == 'win32') or (os.name == 'os2')) and (ext != '.exe')):
executable = (executable + '.exe')
if (not os.path.isfile(executable)):
for p in paths:
f = os.path.join(p, executable)
if os.path.isfile(f):
return f
return None
else:
return executable
| null | null | null | in the directories listed in path
| codeqa | def find executable executable path None if path is None path os environ['PATH']paths path split os pathsep base ext os path splitext executable if sys platform 'win 32 ' or os name 'os 2 ' and ext ' exe' executable executable + ' exe' if not os path isfile executable for p in paths f os path join p executable if os path isfile f return freturn Noneelse return executable
| null | null | null | null | Question:
Where does executable find ?
Code:
def _find_executable(executable, path=None):
if (path is None):
path = os.environ['PATH']
paths = path.split(os.pathsep)
(base, ext) = os.path.splitext(executable)
if (((sys.platform == 'win32') or (os.name == 'os2')) and (ext != '.exe')):
executable = (executable + '.exe')
if (not os.path.isfile(executable)):
for p in paths:
f = os.path.join(p, executable)
if os.path.isfile(f):
return f
return None
else:
return executable
|
null | null | null | By how much do tool shed tool ?
| def remove_port_from_tool_shed_url(tool_shed_url):
try:
if (tool_shed_url.find(':') > 0):
new_tool_shed_url = tool_shed_url.split(':')[0]
else:
new_tool_shed_url = tool_shed_url
return new_tool_shed_url.rstrip('/')
except Exception as e:
if (tool_shed_url is not None):
log.exception('Handled exception removing the port from Tool Shed URL %s:\n%s', str(tool_shed_url), e)
return tool_shed_url
| null | null | null | partial
| codeqa | def remove port from tool shed url tool shed url try if tool shed url find ' ' > 0 new tool shed url tool shed url split ' ' [0 ]else new tool shed url tool shed urlreturn new tool shed url rstrip '/' except Exception as e if tool shed url is not None log exception ' Handledexceptionremovingtheportfrom Tool Shed URL%s \n%s' str tool shed url e return tool shed url
| null | null | null | null | Question:
By how much do tool shed tool ?
Code:
def remove_port_from_tool_shed_url(tool_shed_url):
try:
if (tool_shed_url.find(':') > 0):
new_tool_shed_url = tool_shed_url.split(':')[0]
else:
new_tool_shed_url = tool_shed_url
return new_tool_shed_url.rstrip('/')
except Exception as e:
if (tool_shed_url is not None):
log.exception('Handled exception removing the port from Tool Shed URL %s:\n%s', str(tool_shed_url), e)
return tool_shed_url
|
null | null | null | What list on the system ?
| def list_startup_disks():
ret = salt.utils.mac_utils.execute_return_result('systemsetup -liststartupdisks')
return ret.splitlines()
| null | null | null | all valid startup disks
| codeqa | def list startup disks ret salt utils mac utils execute return result 'systemsetup-liststartupdisks' return ret splitlines
| null | null | null | null | Question:
What list on the system ?
Code:
def list_startup_disks():
ret = salt.utils.mac_utils.execute_return_result('systemsetup -liststartupdisks')
return ret.splitlines()
|
null | null | null | Where do all valid startup disks list ?
| def list_startup_disks():
ret = salt.utils.mac_utils.execute_return_result('systemsetup -liststartupdisks')
return ret.splitlines()
| null | null | null | on the system
| codeqa | def list startup disks ret salt utils mac utils execute return result 'systemsetup-liststartupdisks' return ret splitlines
| null | null | null | null | Question:
Where do all valid startup disks list ?
Code:
def list_startup_disks():
ret = salt.utils.mac_utils.execute_return_result('systemsetup -liststartupdisks')
return ret.splitlines()
|
null | null | null | What does the code execute ?
| def execute_rule(rule, matches, context):
if rule.enabled(context):
log(rule.log_level, 'Checking rule condition: %s', rule)
when_response = rule.when(matches, context)
if when_response:
log(rule.log_level, 'Rule was triggered: %s', when_response)
log(rule.log_level, 'Running rule consequence: %s %s', rule, when_response)
rule.then(matches, when_response, context)
return when_response
else:
log(rule.log_level, 'Rule is disabled: %s', rule)
| null | null | null | the given rule
| codeqa | def execute rule rule matches context if rule enabled context log rule log level ' Checkingrulecondition %s' rule when response rule when matches context if when response log rule log level ' Rulewastriggered %s' when response log rule log level ' Runningruleconsequence %s%s' rule when response rule then matches when response context return when responseelse log rule log level ' Ruleisdisabled %s' rule
| null | null | null | null | Question:
What does the code execute ?
Code:
def execute_rule(rule, matches, context):
if rule.enabled(context):
log(rule.log_level, 'Checking rule condition: %s', rule)
when_response = rule.when(matches, context)
if when_response:
log(rule.log_level, 'Rule was triggered: %s', when_response)
log(rule.log_level, 'Running rule consequence: %s %s', rule, when_response)
rule.then(matches, when_response, context)
return when_response
else:
log(rule.log_level, 'Rule is disabled: %s', rule)
|
null | null | null | What does the code perform for each 3-tuple from the input queue ?
| def worker_e_step(input_queue, result_queue):
logger.debug('worker process entering E-step loop')
while True:
logger.debug('getting a new job')
(chunk_no, chunk, worker_lda) = input_queue.get()
logger.debug('processing chunk #%i of %i documents', chunk_no, len(chunk))
worker_lda.state.reset()
worker_lda.do_estep(chunk)
del chunk
logger.debug('processed chunk, queuing the result')
result_queue.put(worker_lda.state)
del worker_lda
logger.debug('result put')
| null | null | null | e - step
| codeqa | def worker e step input queue result queue logger debug 'workerprocessentering E-steploop' while True logger debug 'gettinganewjob' chunk no chunk worker lda input queue get logger debug 'processingchunk#%iof%idocuments' chunk no len chunk worker lda state reset worker lda do estep chunk del chunklogger debug 'processedchunk queuingtheresult' result queue put worker lda state del worker ldalogger debug 'resultput'
| null | null | null | null | Question:
What does the code perform for each 3-tuple from the input queue ?
Code:
def worker_e_step(input_queue, result_queue):
logger.debug('worker process entering E-step loop')
while True:
logger.debug('getting a new job')
(chunk_no, chunk, worker_lda) = input_queue.get()
logger.debug('processing chunk #%i of %i documents', chunk_no, len(chunk))
worker_lda.state.reset()
worker_lda.do_estep(chunk)
del chunk
logger.debug('processed chunk, queuing the result')
result_queue.put(worker_lda.state)
del worker_lda
logger.debug('result put')
|
null | null | null | In which direction does the code perform e - step for each 3-tuple ?
| def worker_e_step(input_queue, result_queue):
logger.debug('worker process entering E-step loop')
while True:
logger.debug('getting a new job')
(chunk_no, chunk, worker_lda) = input_queue.get()
logger.debug('processing chunk #%i of %i documents', chunk_no, len(chunk))
worker_lda.state.reset()
worker_lda.do_estep(chunk)
del chunk
logger.debug('processed chunk, queuing the result')
result_queue.put(worker_lda.state)
del worker_lda
logger.debug('result put')
| null | null | null | from the input queue
| codeqa | def worker e step input queue result queue logger debug 'workerprocessentering E-steploop' while True logger debug 'gettinganewjob' chunk no chunk worker lda input queue get logger debug 'processingchunk#%iof%idocuments' chunk no len chunk worker lda state reset worker lda do estep chunk del chunklogger debug 'processedchunk queuingtheresult' result queue put worker lda state del worker ldalogger debug 'resultput'
| null | null | null | null | Question:
In which direction does the code perform e - step for each 3-tuple ?
Code:
def worker_e_step(input_queue, result_queue):
logger.debug('worker process entering E-step loop')
while True:
logger.debug('getting a new job')
(chunk_no, chunk, worker_lda) = input_queue.get()
logger.debug('processing chunk #%i of %i documents', chunk_no, len(chunk))
worker_lda.state.reset()
worker_lda.do_estep(chunk)
del chunk
logger.debug('processed chunk, queuing the result')
result_queue.put(worker_lda.state)
del worker_lda
logger.debug('result put')
|
null | null | null | What does the code find ?
| def find_file_mismatch_nodes():
return [node for node in Node.find() if (set(node.files_versions.keys()) != set(node.files_current.keys()))]
| null | null | null | nodes with inconsistent files_current and files_versions field keys
| codeqa | def find file mismatch nodes return [node for node in Node find if set node files versions keys set node files current keys ]
| null | null | null | null | Question:
What does the code find ?
Code:
def find_file_mismatch_nodes():
return [node for node in Node.find() if (set(node.files_versions.keys()) != set(node.files_current.keys()))]
|
null | null | null | What did the code set ?
| def setup_platform(hass, config, add_devices, discovery_info=None):
if ((discovery_info is None) or (zwave.NETWORK is None)):
_LOGGER.debug('No discovery_info=%s or no NETWORK=%s', discovery_info, zwave.NETWORK)
return
temp_unit = hass.config.units.temperature_unit
node = zwave.NETWORK.nodes[discovery_info[zwave.const.ATTR_NODE_ID]]
value = node.values[discovery_info[zwave.const.ATTR_VALUE_ID]]
value.set_change_verified(False)
add_devices([ZWaveClimate(value, temp_unit)])
_LOGGER.debug('discovery_info=%s and zwave.NETWORK=%s', discovery_info, zwave.NETWORK)
| null | null | null | the z - wave climate devices
| codeqa | def setup platform hass config add devices discovery info None if discovery info is None or zwave NETWORK is None LOGGER debug ' Nodiscovery info %sorno NETWORK %s' discovery info zwave NETWORK returntemp unit hass config units temperature unitnode zwave NETWORK nodes[discovery info[zwave const ATTR NODE ID]]value node values[discovery info[zwave const ATTR VALUE ID]]value set change verified False add devices [Z Wave Climate value temp unit ] LOGGER debug 'discovery info %sandzwave NETWORK %s' discovery info zwave NETWORK
| null | null | null | null | Question:
What did the code set ?
Code:
def setup_platform(hass, config, add_devices, discovery_info=None):
if ((discovery_info is None) or (zwave.NETWORK is None)):
_LOGGER.debug('No discovery_info=%s or no NETWORK=%s', discovery_info, zwave.NETWORK)
return
temp_unit = hass.config.units.temperature_unit
node = zwave.NETWORK.nodes[discovery_info[zwave.const.ATTR_NODE_ID]]
value = node.values[discovery_info[zwave.const.ATTR_VALUE_ID]]
value.set_change_verified(False)
add_devices([ZWaveClimate(value, temp_unit)])
_LOGGER.debug('discovery_info=%s and zwave.NETWORK=%s', discovery_info, zwave.NETWORK)
|
null | null | null | What does the code create ?
| def new_figure_manager(num, *args, **kwargs):
FigureClass = kwargs.pop('FigureClass', Figure)
thisFig = FigureClass(*args, **kwargs)
return new_figure_manager_given_figure(num, thisFig)
| null | null | null | a new figure manager instance
| codeqa | def new figure manager num *args **kwargs Figure Class kwargs pop ' Figure Class' Figure this Fig Figure Class *args **kwargs return new figure manager given figure num this Fig
| null | null | null | null | Question:
What does the code create ?
Code:
def new_figure_manager(num, *args, **kwargs):
FigureClass = kwargs.pop('FigureClass', Figure)
thisFig = FigureClass(*args, **kwargs)
return new_figure_manager_given_figure(num, thisFig)
|
null | null | null | What does the code perform ?
| def _covar_mstep_diag(gmm, X, responsibilities, weighted_X_sum, norm, min_covar):
avg_X2 = (np.dot(responsibilities.T, (X * X)) * norm)
avg_means2 = (gmm.means_ ** 2)
avg_X_means = ((gmm.means_ * weighted_X_sum) * norm)
return (((avg_X2 - (2 * avg_X_means)) + avg_means2) + min_covar)
| null | null | null | the covariance m step for diagonal cases
| codeqa | def covar mstep diag gmm X responsibilities weighted X sum norm min covar avg X2 np dot responsibilities T X * X * norm avg means 2 gmm means ** 2 avg X means gmm means * weighted X sum * norm return avg X2 - 2 * avg X means + avg means 2 + min covar
| null | null | null | null | Question:
What does the code perform ?
Code:
def _covar_mstep_diag(gmm, X, responsibilities, weighted_X_sum, norm, min_covar):
avg_X2 = (np.dot(responsibilities.T, (X * X)) * norm)
avg_means2 = (gmm.means_ ** 2)
avg_X_means = ((gmm.means_ * weighted_X_sum) * norm)
return (((avg_X2 - (2 * avg_X_means)) + avg_means2) + min_covar)
|
null | null | null | What validates an action function against a given schema ?
| def validate(schema_func, can_skip_validator=False):
def action_decorator(action):
@functools.wraps(action)
def wrapper(context, data_dict):
if can_skip_validator:
if context.get('skip_validation'):
return action(context, data_dict)
schema = context.get('schema', schema_func())
(data_dict, errors) = _validate(data_dict, schema, context)
if errors:
raise ValidationError(errors)
return action(context, data_dict)
return wrapper
return action_decorator
| null | null | null | a decorator
| codeqa | def validate schema func can skip validator False def action decorator action @functools wraps action def wrapper context data dict if can skip validator if context get 'skip validation' return action context data dict schema context get 'schema' schema func data dict errors validate data dict schema context if errors raise Validation Error errors return action context data dict return wrapperreturn action decorator
| null | null | null | null | Question:
What validates an action function against a given schema ?
Code:
def validate(schema_func, can_skip_validator=False):
def action_decorator(action):
@functools.wraps(action)
def wrapper(context, data_dict):
if can_skip_validator:
if context.get('skip_validation'):
return action(context, data_dict)
schema = context.get('schema', schema_func())
(data_dict, errors) = _validate(data_dict, schema, context)
if errors:
raise ValidationError(errors)
return action(context, data_dict)
return wrapper
return action_decorator
|
null | null | null | What does a decorator validate against a given schema ?
| def validate(schema_func, can_skip_validator=False):
def action_decorator(action):
@functools.wraps(action)
def wrapper(context, data_dict):
if can_skip_validator:
if context.get('skip_validation'):
return action(context, data_dict)
schema = context.get('schema', schema_func())
(data_dict, errors) = _validate(data_dict, schema, context)
if errors:
raise ValidationError(errors)
return action(context, data_dict)
return wrapper
return action_decorator
| null | null | null | an action function
| codeqa | def validate schema func can skip validator False def action decorator action @functools wraps action def wrapper context data dict if can skip validator if context get 'skip validation' return action context data dict schema context get 'schema' schema func data dict errors validate data dict schema context if errors raise Validation Error errors return action context data dict return wrapperreturn action decorator
| null | null | null | null | Question:
What does a decorator validate against a given schema ?
Code:
def validate(schema_func, can_skip_validator=False):
def action_decorator(action):
@functools.wraps(action)
def wrapper(context, data_dict):
if can_skip_validator:
if context.get('skip_validation'):
return action(context, data_dict)
schema = context.get('schema', schema_func())
(data_dict, errors) = _validate(data_dict, schema, context)
if errors:
raise ValidationError(errors)
return action(context, data_dict)
return wrapper
return action_decorator
|
null | null | null | What is joining the accepted matches input ?
| def plot_matches(im1, im2, locs1, locs2, matchscores, show_below=True):
im3 = appendimages(im1, im2)
if show_below:
im3 = vstack((im3, im3))
imshow(im3)
cols1 = im1.shape[1]
for (i, m) in enumerate(matchscores):
if (m > 0):
plot([locs1[i][0], (locs2[m][0] + cols1)], [locs1[i][1], locs2[m][1]], 'c')
axis('off')
| null | null | null | lines
| codeqa | def plot matches im 1 im 2 locs 1 locs 2 matchscores show below True im 3 appendimages im 1 im 2 if show below im 3 vstack im 3 im 3 imshow im 3 cols 1 im 1 shape[ 1 ]for i m in enumerate matchscores if m > 0 plot [locs 1 [i][ 0 ] locs 2 [m][ 0 ] + cols 1 ] [locs 1 [i][ 1 ] locs 2 [m][ 1 ]] 'c' axis 'off'
| null | null | null | null | Question:
What is joining the accepted matches input ?
Code:
def plot_matches(im1, im2, locs1, locs2, matchscores, show_below=True):
im3 = appendimages(im1, im2)
if show_below:
im3 = vstack((im3, im3))
imshow(im3)
cols1 = im1.shape[1]
for (i, m) in enumerate(matchscores):
if (m > 0):
plot([locs1[i][0], (locs2[m][0] + cols1)], [locs1[i][1], locs2[m][1]], 'c')
axis('off')
|
null | null | null | What does the code show ?
| def plot_matches(im1, im2, locs1, locs2, matchscores, show_below=True):
im3 = appendimages(im1, im2)
if show_below:
im3 = vstack((im3, im3))
imshow(im3)
cols1 = im1.shape[1]
for (i, m) in enumerate(matchscores):
if (m > 0):
plot([locs1[i][0], (locs2[m][0] + cols1)], [locs1[i][1], locs2[m][1]], 'c')
axis('off')
| null | null | null | a figure with lines joining the accepted matches input
| codeqa | def plot matches im 1 im 2 locs 1 locs 2 matchscores show below True im 3 appendimages im 1 im 2 if show below im 3 vstack im 3 im 3 imshow im 3 cols 1 im 1 shape[ 1 ]for i m in enumerate matchscores if m > 0 plot [locs 1 [i][ 0 ] locs 2 [m][ 0 ] + cols 1 ] [locs 1 [i][ 1 ] locs 2 [m][ 1 ]] 'c' axis 'off'
| null | null | null | null | Question:
What does the code show ?
Code:
def plot_matches(im1, im2, locs1, locs2, matchscores, show_below=True):
im3 = appendimages(im1, im2)
if show_below:
im3 = vstack((im3, im3))
imshow(im3)
cols1 = im1.shape[1]
for (i, m) in enumerate(matchscores):
if (m > 0):
plot([locs1[i][0], (locs2[m][0] + cols1)], [locs1[i][1], locs2[m][1]], 'c')
axis('off')
|
null | null | null | What do lines join ?
| def plot_matches(im1, im2, locs1, locs2, matchscores, show_below=True):
im3 = appendimages(im1, im2)
if show_below:
im3 = vstack((im3, im3))
imshow(im3)
cols1 = im1.shape[1]
for (i, m) in enumerate(matchscores):
if (m > 0):
plot([locs1[i][0], (locs2[m][0] + cols1)], [locs1[i][1], locs2[m][1]], 'c')
axis('off')
| null | null | null | the accepted matches input
| codeqa | def plot matches im 1 im 2 locs 1 locs 2 matchscores show below True im 3 appendimages im 1 im 2 if show below im 3 vstack im 3 im 3 imshow im 3 cols 1 im 1 shape[ 1 ]for i m in enumerate matchscores if m > 0 plot [locs 1 [i][ 0 ] locs 2 [m][ 0 ] + cols 1 ] [locs 1 [i][ 1 ] locs 2 [m][ 1 ]] 'c' axis 'off'
| null | null | null | null | Question:
What do lines join ?
Code:
def plot_matches(im1, im2, locs1, locs2, matchscores, show_below=True):
im3 = appendimages(im1, im2)
if show_below:
im3 = vstack((im3, im3))
imshow(im3)
cols1 = im1.shape[1]
for (i, m) in enumerate(matchscores):
if (m > 0):
plot([locs1[i][0], (locs2[m][0] + cols1)], [locs1[i][1], locs2[m][1]], 'c')
axis('off')
|
null | null | null | What does the code retrieve according to the given parameters ?
| def usergroup_get(name=None, usrgrpids=None, userids=None, **connection_args):
conn_args = _login(**connection_args)
try:
if conn_args:
method = 'usergroup.get'
params = {'output': 'extend', 'filter': {}}
if ((not name) and (not usrgrpids) and (not userids)):
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **connection_args)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return (False if (len(ret['result']) < 1) else ret['result'])
else:
raise KeyError
except KeyError:
return False
| null | null | null | user groups
| codeqa | def usergroup get name None usrgrpids None userids None **connection args conn args login **connection args try if conn args method 'usergroup get'params {'output' 'extend' 'filter' {}}if not name and not usrgrpids and not userids return Falseif name params['filter'] setdefault 'name' name if usrgrpids params setdefault 'usrgrpids' usrgrpids if userids params setdefault 'userids' userids params params extend params **connection args ret query method params conn args['url'] conn args['auth'] return False if len ret['result'] < 1 else ret['result'] else raise Key Errorexcept Key Error return False
| null | null | null | null | Question:
What does the code retrieve according to the given parameters ?
Code:
def usergroup_get(name=None, usrgrpids=None, userids=None, **connection_args):
conn_args = _login(**connection_args)
try:
if conn_args:
method = 'usergroup.get'
params = {'output': 'extend', 'filter': {}}
if ((not name) and (not usrgrpids) and (not userids)):
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **connection_args)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return (False if (len(ret['result']) < 1) else ret['result'])
else:
raise KeyError
except KeyError:
return False
|
null | null | null | How does the code retrieve user groups ?
| def usergroup_get(name=None, usrgrpids=None, userids=None, **connection_args):
conn_args = _login(**connection_args)
try:
if conn_args:
method = 'usergroup.get'
params = {'output': 'extend', 'filter': {}}
if ((not name) and (not usrgrpids) and (not userids)):
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **connection_args)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return (False if (len(ret['result']) < 1) else ret['result'])
else:
raise KeyError
except KeyError:
return False
| null | null | null | according to the given parameters
| codeqa | def usergroup get name None usrgrpids None userids None **connection args conn args login **connection args try if conn args method 'usergroup get'params {'output' 'extend' 'filter' {}}if not name and not usrgrpids and not userids return Falseif name params['filter'] setdefault 'name' name if usrgrpids params setdefault 'usrgrpids' usrgrpids if userids params setdefault 'userids' userids params params extend params **connection args ret query method params conn args['url'] conn args['auth'] return False if len ret['result'] < 1 else ret['result'] else raise Key Errorexcept Key Error return False
| null | null | null | null | Question:
How does the code retrieve user groups ?
Code:
def usergroup_get(name=None, usrgrpids=None, userids=None, **connection_args):
conn_args = _login(**connection_args)
try:
if conn_args:
method = 'usergroup.get'
params = {'output': 'extend', 'filter': {}}
if ((not name) and (not usrgrpids) and (not userids)):
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **connection_args)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return (False if (len(ret['result']) < 1) else ret['result'])
else:
raise KeyError
except KeyError:
return False
|
null | null | null | How do files copy from a remote host ?
| def copy_files_from(address, client, username, password, port, remote_path, local_path, limit='', log_filename=None, verbose=False, timeout=600, interface=None):
if (client == 'scp'):
scp_from_remote(address, port, username, password, remote_path, local_path, limit, log_filename, timeout, interface=interface)
elif (client == 'rss'):
log_func = None
if verbose:
log_func = logging.debug
c = rss_client.FileDownloadClient(address, port, log_func)
c.download(remote_path, local_path, timeout)
c.close()
| null | null | null | using the selected client
| codeqa | def copy files from address client username password port remote path local path limit '' log filename None verbose False timeout 600 interface None if client 'scp' scp from remote address port username password remote path local path limit log filename timeout interface interface elif client 'rss' log func Noneif verbose log func logging debugc rss client File Download Client address port log func c download remote path local path timeout c close
| null | null | null | null | Question:
How do files copy from a remote host ?
Code:
def copy_files_from(address, client, username, password, port, remote_path, local_path, limit='', log_filename=None, verbose=False, timeout=600, interface=None):
if (client == 'scp'):
scp_from_remote(address, port, username, password, remote_path, local_path, limit, log_filename, timeout, interface=interface)
elif (client == 'rss'):
log_func = None
if verbose:
log_func = logging.debug
c = rss_client.FileDownloadClient(address, port, log_func)
c.download(remote_path, local_path, timeout)
c.close()
|
null | null | null | What does the code create ?
| def console_create(context, values):
return IMPL.console_create(context, values)
| null | null | null | a console
| codeqa | def console create context values return IMPL console create context values
| null | null | null | null | Question:
What does the code create ?
Code:
def console_create(context, values):
return IMPL.console_create(context, values)
|
null | null | null | What does the code specify ?
| def test_commandline_explicit_interp(tmpdir):
subprocess.check_call([sys.executable, VIRTUALENV_SCRIPT, '-p', sys.executable, str(tmpdir.join('venv'))])
| null | null | null | the python interpreter
| codeqa | def test commandline explicit interp tmpdir subprocess check call [sys executable VIRTUALENV SCRIPT '-p' sys executable str tmpdir join 'venv' ]
| null | null | null | null | Question:
What does the code specify ?
Code:
def test_commandline_explicit_interp(tmpdir):
subprocess.check_call([sys.executable, VIRTUALENV_SCRIPT, '-p', sys.executable, str(tmpdir.join('venv'))])
|
null | null | null | What does a logger log with level debug and above to stderr ?
| def get_logger_for_python_runner_action(action_name):
logger_name = ('actions.python.%s' % action_name)
logger = logging.getLogger(logger_name)
console = stdlib_logging.StreamHandler()
console.setLevel(stdlib_logging.DEBUG)
formatter = stdlib_logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logger.addHandler(console)
logger.setLevel(stdlib_logging.DEBUG)
return logger
| null | null | null | all the messages
| codeqa | def get logger for python runner action action name logger name 'actions python %s' % action name logger logging get Logger logger name console stdlib logging Stream Handler console set Level stdlib logging DEBUG formatter stdlib logging Formatter '% name -12 s % levelname -8 s% message s' console set Formatter formatter logger add Handler console logger set Level stdlib logging DEBUG return logger
| null | null | null | null | Question:
What does a logger log with level debug and above to stderr ?
Code:
def get_logger_for_python_runner_action(action_name):
logger_name = ('actions.python.%s' % action_name)
logger = logging.getLogger(logger_name)
console = stdlib_logging.StreamHandler()
console.setLevel(stdlib_logging.DEBUG)
formatter = stdlib_logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logger.addHandler(console)
logger.setLevel(stdlib_logging.DEBUG)
return logger
|
null | null | null | What did the code set ?
| def get_logger_for_python_runner_action(action_name):
logger_name = ('actions.python.%s' % action_name)
logger = logging.getLogger(logger_name)
console = stdlib_logging.StreamHandler()
console.setLevel(stdlib_logging.DEBUG)
formatter = stdlib_logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logger.addHandler(console)
logger.setLevel(stdlib_logging.DEBUG)
return logger
| null | null | null | a logger which logs all the messages with level debug and above to stderr
| codeqa | def get logger for python runner action action name logger name 'actions python %s' % action name logger logging get Logger logger name console stdlib logging Stream Handler console set Level stdlib logging DEBUG formatter stdlib logging Formatter '% name -12 s % levelname -8 s% message s' console set Formatter formatter logger add Handler console logger set Level stdlib logging DEBUG return logger
| null | null | null | null | Question:
What did the code set ?
Code:
def get_logger_for_python_runner_action(action_name):
logger_name = ('actions.python.%s' % action_name)
logger = logging.getLogger(logger_name)
console = stdlib_logging.StreamHandler()
console.setLevel(stdlib_logging.DEBUG)
formatter = stdlib_logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logger.addHandler(console)
logger.setLevel(stdlib_logging.DEBUG)
return logger
|
null | null | null | For what purpose does a logger log all the messages with level debug and above ?
| def get_logger_for_python_runner_action(action_name):
logger_name = ('actions.python.%s' % action_name)
logger = logging.getLogger(logger_name)
console = stdlib_logging.StreamHandler()
console.setLevel(stdlib_logging.DEBUG)
formatter = stdlib_logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logger.addHandler(console)
logger.setLevel(stdlib_logging.DEBUG)
return logger
| null | null | null | to stderr
| codeqa | def get logger for python runner action action name logger name 'actions python %s' % action name logger logging get Logger logger name console stdlib logging Stream Handler console set Level stdlib logging DEBUG formatter stdlib logging Formatter '% name -12 s % levelname -8 s% message s' console set Formatter formatter logger add Handler console logger set Level stdlib logging DEBUG return logger
| null | null | null | null | Question:
For what purpose does a logger log all the messages with level debug and above ?
Code:
def get_logger_for_python_runner_action(action_name):
logger_name = ('actions.python.%s' % action_name)
logger = logging.getLogger(logger_name)
console = stdlib_logging.StreamHandler()
console.setLevel(stdlib_logging.DEBUG)
formatter = stdlib_logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logger.addHandler(console)
logger.setLevel(stdlib_logging.DEBUG)
return logger
|
null | null | null | How does a logger log all the messages to stderr ?
| def get_logger_for_python_runner_action(action_name):
logger_name = ('actions.python.%s' % action_name)
logger = logging.getLogger(logger_name)
console = stdlib_logging.StreamHandler()
console.setLevel(stdlib_logging.DEBUG)
formatter = stdlib_logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logger.addHandler(console)
logger.setLevel(stdlib_logging.DEBUG)
return logger
| null | null | null | with level debug and above
| codeqa | def get logger for python runner action action name logger name 'actions python %s' % action name logger logging get Logger logger name console stdlib logging Stream Handler console set Level stdlib logging DEBUG formatter stdlib logging Formatter '% name -12 s % levelname -8 s% message s' console set Formatter formatter logger add Handler console logger set Level stdlib logging DEBUG return logger
| null | null | null | null | Question:
How does a logger log all the messages to stderr ?
Code:
def get_logger_for_python_runner_action(action_name):
logger_name = ('actions.python.%s' % action_name)
logger = logging.getLogger(logger_name)
console = stdlib_logging.StreamHandler()
console.setLevel(stdlib_logging.DEBUG)
formatter = stdlib_logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logger.addHandler(console)
logger.setLevel(stdlib_logging.DEBUG)
return logger
|
null | null | null | What logs all the messages with level debug and above to stderr ?
| def get_logger_for_python_runner_action(action_name):
logger_name = ('actions.python.%s' % action_name)
logger = logging.getLogger(logger_name)
console = stdlib_logging.StreamHandler()
console.setLevel(stdlib_logging.DEBUG)
formatter = stdlib_logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logger.addHandler(console)
logger.setLevel(stdlib_logging.DEBUG)
return logger
| null | null | null | a logger
| codeqa | def get logger for python runner action action name logger name 'actions python %s' % action name logger logging get Logger logger name console stdlib logging Stream Handler console set Level stdlib logging DEBUG formatter stdlib logging Formatter '% name -12 s % levelname -8 s% message s' console set Formatter formatter logger add Handler console logger set Level stdlib logging DEBUG return logger
| null | null | null | null | Question:
What logs all the messages with level debug and above to stderr ?
Code:
def get_logger_for_python_runner_action(action_name):
logger_name = ('actions.python.%s' % action_name)
logger = logging.getLogger(logger_name)
console = stdlib_logging.StreamHandler()
console.setLevel(stdlib_logging.DEBUG)
formatter = stdlib_logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logger.addHandler(console)
logger.setLevel(stdlib_logging.DEBUG)
return logger
|
null | null | null | What does the code take ?
| def expandServices(service_elements):
expanded = []
for service_element in service_elements:
expanded.extend(expandService(service_element))
return expanded
| null | null | null | a sorted iterator of service elements
| codeqa | def expand Services service elements expanded []for service element in service elements expanded extend expand Service service element return expanded
| null | null | null | null | Question:
What does the code take ?
Code:
def expandServices(service_elements):
expanded = []
for service_element in service_elements:
expanded.extend(expandService(service_element))
return expanded
|
null | null | null | What is the label_flags indicate ?
| def has_level_label(label_flags, vmin):
if ((label_flags.size == 0) or ((label_flags.size == 1) and (label_flags[0] == 0) and ((vmin % 1) > 0.0))):
return False
else:
return True
| null | null | null | there is at least one label for this level
| codeqa | def has level label label flags vmin if label flags size 0 or label flags size 1 and label flags[ 0 ] 0 and vmin % 1 > 0 0 return Falseelse return True
| null | null | null | null | Question:
What is the label_flags indicate ?
Code:
def has_level_label(label_flags, vmin):
if ((label_flags.size == 0) or ((label_flags.size == 1) and (label_flags[0] == 0) and ((vmin % 1) > 0.0))):
return False
else:
return True
|
null | null | null | What does the code get ?
| def get_valuation_rate():
item_val_rate_map = {}
for d in frappe.db.sql(u'select item_code,\n DCTB DCTB sum(actual_qty*valuation_rate)/sum(actual_qty) as val_rate\n DCTB DCTB from tabBin where actual_qty > 0 group by item_code', as_dict=1):
item_val_rate_map.setdefault(d.item_code, d.val_rate)
return item_val_rate_map
| null | null | null | an average valuation rate of an item from all warehouses
| codeqa | def get valuation rate item val rate map {}for d in frappe db sql u'selectitem code \n DCTB DCTB sum actual qty*valuation rate /sum actual qty asval rate\n DCTB DCTB fromtab Binwhereactual qty> 0 groupbyitem code' as dict 1 item val rate map setdefault d item code d val rate return item val rate map
| null | null | null | null | Question:
What does the code get ?
Code:
def get_valuation_rate():
item_val_rate_map = {}
for d in frappe.db.sql(u'select item_code,\n DCTB DCTB sum(actual_qty*valuation_rate)/sum(actual_qty) as val_rate\n DCTB DCTB from tabBin where actual_qty > 0 group by item_code', as_dict=1):
item_val_rate_map.setdefault(d.item_code, d.val_rate)
return item_val_rate_map
|
null | null | null | When did beets load ?
| def find_plugins():
load_plugins()
plugins = []
for cls in _classes:
if (cls not in _instances):
_instances[cls] = cls()
plugins.append(_instances[cls])
return plugins
| null | null | null | currently
| codeqa | def find plugins load plugins plugins []for cls in classes if cls not in instances instances[cls] cls plugins append instances[cls] return plugins
| null | null | null | null | Question:
When did beets load ?
Code:
def find_plugins():
load_plugins()
plugins = []
for cls in _classes:
if (cls not in _instances):
_instances[cls] = cls()
plugins.append(_instances[cls])
return plugins
|
null | null | null | When is tool shed current tool shed ?
| def generate_repository_dependencies_key_for_repository(toolshed_base_url, repository_name, repository_owner, changeset_revision, prior_installation_required, only_if_compiling_contained_td):
tool_shed = common_util.remove_protocol_from_tool_shed_url(toolshed_base_url)
return ('%s%s%s%s%s%s%s%s%s%s%s' % (tool_shed, STRSEP, str(repository_name), STRSEP, str(repository_owner), STRSEP, str(changeset_revision), STRSEP, str(prior_installation_required), STRSEP, str(only_if_compiling_contained_td)))
| null | null | null | since repository dependencies across tool sheds
| codeqa | def generate repository dependencies key for repository toolshed base url repository name repository owner changeset revision prior installation required only if compiling contained td tool shed common util remove protocol from tool shed url toolshed base url return '%s%s%s%s%s%s%s%s%s%s%s' % tool shed STRSEP str repository name STRSEP str repository owner STRSEP str changeset revision STRSEP str prior installation required STRSEP str only if compiling contained td
| null | null | null | null | Question:
When is tool shed current tool shed ?
Code:
def generate_repository_dependencies_key_for_repository(toolshed_base_url, repository_name, repository_owner, changeset_revision, prior_installation_required, only_if_compiling_contained_td):
tool_shed = common_util.remove_protocol_from_tool_shed_url(toolshed_base_url)
return ('%s%s%s%s%s%s%s%s%s%s%s' % (tool_shed, STRSEP, str(repository_name), STRSEP, str(repository_owner), STRSEP, str(changeset_revision), STRSEP, str(prior_installation_required), STRSEP, str(only_if_compiling_contained_td)))
|
null | null | null | When did tool shed ?
| def generate_repository_dependencies_key_for_repository(toolshed_base_url, repository_name, repository_owner, changeset_revision, prior_installation_required, only_if_compiling_contained_td):
tool_shed = common_util.remove_protocol_from_tool_shed_url(toolshed_base_url)
return ('%s%s%s%s%s%s%s%s%s%s%s' % (tool_shed, STRSEP, str(repository_name), STRSEP, str(repository_owner), STRSEP, str(changeset_revision), STRSEP, str(prior_installation_required), STRSEP, str(only_if_compiling_contained_td)))
| null | null | null | current
| codeqa | def generate repository dependencies key for repository toolshed base url repository name repository owner changeset revision prior installation required only if compiling contained td tool shed common util remove protocol from tool shed url toolshed base url return '%s%s%s%s%s%s%s%s%s%s%s' % tool shed STRSEP str repository name STRSEP str repository owner STRSEP str changeset revision STRSEP str prior installation required STRSEP str only if compiling contained td
| null | null | null | null | Question:
When did tool shed ?
Code:
def generate_repository_dependencies_key_for_repository(toolshed_base_url, repository_name, repository_owner, changeset_revision, prior_installation_required, only_if_compiling_contained_td):
tool_shed = common_util.remove_protocol_from_tool_shed_url(toolshed_base_url)
return ('%s%s%s%s%s%s%s%s%s%s%s' % (tool_shed, STRSEP, str(repository_name), STRSEP, str(repository_owner), STRSEP, str(changeset_revision), STRSEP, str(prior_installation_required), STRSEP, str(only_if_compiling_contained_td)))
|
null | null | null | What does your plot draw on box select ?
| def add_visual_box_select(plot):
source = ColumnDataSource(data=dict(x=[], y=[], width=[], height=[]))
rect = Rect(x='x', y='y', width='width', height='height', fill_alpha=0.3, fill_color='#009933')
callback = CustomJS(args=dict(source=source), code="\n // get data source from Callback args\n var data = source.data;\n\n /// get BoxSelectTool dimensions from cb_data parameter of Callback\n var geometry = cb_data['geometry'];\n\n /// calculate Rect attributes\n var width = geometry['x1'] - geometry['x0'];\n var height = geometry['y1'] - geometry['y0'];\n var x = geometry['x0'] + width/2;\n var y = geometry['y0'] + height/2;\n\n /// update data source with new Rect attributes\n data['x'].push(x);\n data['y'].push(y);\n data['width'].push(width);\n data['height'].push(height);\n\n // trigger update of data source\n source.trigger('change');\n ")
box_select = BoxSelectTool(callback=callback)
plot.add_glyph(source, rect, selection_glyph=rect, nonselection_glyph=rect)
plot.add_tools(box_select)
return plot
| null | null | null | a rect
| codeqa | def add visual box select plot source Column Data Source data dict x [] y [] width [] height [] rect Rect x 'x' y 'y' width 'width' height 'height' fill alpha 0 3 fill color '# 009933 ' callback Custom JS args dict source source code "\n//getdatasourcefrom Callbackargs\nvardata source data \n\n///get Box Select Tooldimensionsfromcb dataparameterof Callback\nvargeometry cb data['geometry'] \n\n///calculate Rectattributes\nvarwidth geometry['x 1 ']-geometry['x 0 '] \nvarheight geometry['y 1 ']-geometry['y 0 '] \nvarx geometry['x 0 ']+width/ 2 \nvary geometry['y 0 ']+height/ 2 \n\n///updatedatasourcewithnew Rectattributes\ndata['x'] push x \ndata['y'] push y \ndata['width'] push width \ndata['height'] push height \n\n//triggerupdateofdatasource\nsource trigger 'change' \n" box select Box Select Tool callback callback plot add glyph source rect selection glyph rect nonselection glyph rect plot add tools box select return plot
| null | null | null | null | Question:
What does your plot draw on box select ?
Code:
def add_visual_box_select(plot):
source = ColumnDataSource(data=dict(x=[], y=[], width=[], height=[]))
rect = Rect(x='x', y='y', width='width', height='height', fill_alpha=0.3, fill_color='#009933')
callback = CustomJS(args=dict(source=source), code="\n // get data source from Callback args\n var data = source.data;\n\n /// get BoxSelectTool dimensions from cb_data parameter of Callback\n var geometry = cb_data['geometry'];\n\n /// calculate Rect attributes\n var width = geometry['x1'] - geometry['x0'];\n var height = geometry['y1'] - geometry['y0'];\n var x = geometry['x0'] + width/2;\n var y = geometry['y0'] + height/2;\n\n /// update data source with new Rect attributes\n data['x'].push(x);\n data['y'].push(y);\n data['width'].push(width);\n data['height'].push(height);\n\n // trigger update of data source\n source.trigger('change');\n ")
box_select = BoxSelectTool(callback=callback)
plot.add_glyph(source, rect, selection_glyph=rect, nonselection_glyph=rect)
plot.add_tools(box_select)
return plot
|
null | null | null | What draws a rect on box select ?
| def add_visual_box_select(plot):
source = ColumnDataSource(data=dict(x=[], y=[], width=[], height=[]))
rect = Rect(x='x', y='y', width='width', height='height', fill_alpha=0.3, fill_color='#009933')
callback = CustomJS(args=dict(source=source), code="\n // get data source from Callback args\n var data = source.data;\n\n /// get BoxSelectTool dimensions from cb_data parameter of Callback\n var geometry = cb_data['geometry'];\n\n /// calculate Rect attributes\n var width = geometry['x1'] - geometry['x0'];\n var height = geometry['y1'] - geometry['y0'];\n var x = geometry['x0'] + width/2;\n var y = geometry['y0'] + height/2;\n\n /// update data source with new Rect attributes\n data['x'].push(x);\n data['y'].push(y);\n data['width'].push(width);\n data['height'].push(height);\n\n // trigger update of data source\n source.trigger('change');\n ")
box_select = BoxSelectTool(callback=callback)
plot.add_glyph(source, rect, selection_glyph=rect, nonselection_glyph=rect)
plot.add_tools(box_select)
return plot
| null | null | null | your plot
| codeqa | def add visual box select plot source Column Data Source data dict x [] y [] width [] height [] rect Rect x 'x' y 'y' width 'width' height 'height' fill alpha 0 3 fill color '# 009933 ' callback Custom JS args dict source source code "\n//getdatasourcefrom Callbackargs\nvardata source data \n\n///get Box Select Tooldimensionsfromcb dataparameterof Callback\nvargeometry cb data['geometry'] \n\n///calculate Rectattributes\nvarwidth geometry['x 1 ']-geometry['x 0 '] \nvarheight geometry['y 1 ']-geometry['y 0 '] \nvarx geometry['x 0 ']+width/ 2 \nvary geometry['y 0 ']+height/ 2 \n\n///updatedatasourcewithnew Rectattributes\ndata['x'] push x \ndata['y'] push y \ndata['width'] push width \ndata['height'] push height \n\n//triggerupdateofdatasource\nsource trigger 'change' \n" box select Box Select Tool callback callback plot add glyph source rect selection glyph rect nonselection glyph rect plot add tools box select return plot
| null | null | null | null | Question:
What draws a rect on box select ?
Code:
def add_visual_box_select(plot):
source = ColumnDataSource(data=dict(x=[], y=[], width=[], height=[]))
rect = Rect(x='x', y='y', width='width', height='height', fill_alpha=0.3, fill_color='#009933')
callback = CustomJS(args=dict(source=source), code="\n // get data source from Callback args\n var data = source.data;\n\n /// get BoxSelectTool dimensions from cb_data parameter of Callback\n var geometry = cb_data['geometry'];\n\n /// calculate Rect attributes\n var width = geometry['x1'] - geometry['x0'];\n var height = geometry['y1'] - geometry['y0'];\n var x = geometry['x0'] + width/2;\n var y = geometry['y0'] + height/2;\n\n /// update data source with new Rect attributes\n data['x'].push(x);\n data['y'].push(y);\n data['width'].push(width);\n data['height'].push(height);\n\n // trigger update of data source\n source.trigger('change');\n ")
box_select = BoxSelectTool(callback=callback)
plot.add_glyph(source, rect, selection_glyph=rect, nonselection_glyph=rect)
plot.add_tools(box_select)
return plot
|
null | null | null | Where does your plot draw a rect ?
| def add_visual_box_select(plot):
source = ColumnDataSource(data=dict(x=[], y=[], width=[], height=[]))
rect = Rect(x='x', y='y', width='width', height='height', fill_alpha=0.3, fill_color='#009933')
callback = CustomJS(args=dict(source=source), code="\n // get data source from Callback args\n var data = source.data;\n\n /// get BoxSelectTool dimensions from cb_data parameter of Callback\n var geometry = cb_data['geometry'];\n\n /// calculate Rect attributes\n var width = geometry['x1'] - geometry['x0'];\n var height = geometry['y1'] - geometry['y0'];\n var x = geometry['x0'] + width/2;\n var y = geometry['y0'] + height/2;\n\n /// update data source with new Rect attributes\n data['x'].push(x);\n data['y'].push(y);\n data['width'].push(width);\n data['height'].push(height);\n\n // trigger update of data source\n source.trigger('change');\n ")
box_select = BoxSelectTool(callback=callback)
plot.add_glyph(source, rect, selection_glyph=rect, nonselection_glyph=rect)
plot.add_tools(box_select)
return plot
| null | null | null | on box select
| codeqa | def add visual box select plot source Column Data Source data dict x [] y [] width [] height [] rect Rect x 'x' y 'y' width 'width' height 'height' fill alpha 0 3 fill color '# 009933 ' callback Custom JS args dict source source code "\n//getdatasourcefrom Callbackargs\nvardata source data \n\n///get Box Select Tooldimensionsfromcb dataparameterof Callback\nvargeometry cb data['geometry'] \n\n///calculate Rectattributes\nvarwidth geometry['x 1 ']-geometry['x 0 '] \nvarheight geometry['y 1 ']-geometry['y 0 '] \nvarx geometry['x 0 ']+width/ 2 \nvary geometry['y 0 ']+height/ 2 \n\n///updatedatasourcewithnew Rectattributes\ndata['x'] push x \ndata['y'] push y \ndata['width'] push width \ndata['height'] push height \n\n//triggerupdateofdatasource\nsource trigger 'change' \n" box select Box Select Tool callback callback plot add glyph source rect selection glyph rect nonselection glyph rect plot add tools box select return plot
| null | null | null | null | Question:
Where does your plot draw a rect ?
Code:
def add_visual_box_select(plot):
source = ColumnDataSource(data=dict(x=[], y=[], width=[], height=[]))
rect = Rect(x='x', y='y', width='width', height='height', fill_alpha=0.3, fill_color='#009933')
callback = CustomJS(args=dict(source=source), code="\n // get data source from Callback args\n var data = source.data;\n\n /// get BoxSelectTool dimensions from cb_data parameter of Callback\n var geometry = cb_data['geometry'];\n\n /// calculate Rect attributes\n var width = geometry['x1'] - geometry['x0'];\n var height = geometry['y1'] - geometry['y0'];\n var x = geometry['x0'] + width/2;\n var y = geometry['y0'] + height/2;\n\n /// update data source with new Rect attributes\n data['x'].push(x);\n data['y'].push(y);\n data['width'].push(width);\n data['height'].push(height);\n\n // trigger update of data source\n source.trigger('change');\n ")
box_select = BoxSelectTool(callback=callback)
plot.add_glyph(source, rect, selection_glyph=rect, nonselection_glyph=rect)
plot.add_tools(box_select)
return plot
|
null | null | null | What does the code return for the specified user ?
| def _SecretName(user):
return '{0}_otp'.format(user)
| null | null | null | the name of the secret file
| codeqa | def Secret Name user return '{ 0 } otp' format user
| null | null | null | null | Question:
What does the code return for the specified user ?
Code:
def _SecretName(user):
return '{0}_otp'.format(user)
|
null | null | null | When did users connect ?
| def users():
retlist = []
rawlist = cext.users()
for item in rawlist:
(user, hostname, tstamp) = item
user = py2_strencode(user)
nt = _common.suser(user, None, hostname, tstamp)
retlist.append(nt)
return retlist
| null | null | null | currently
| codeqa | def users retlist []rawlist cext users for item in rawlist user hostname tstamp itemuser py 2 strencode user nt common suser user None hostname tstamp retlist append nt return retlist
| null | null | null | null | Question:
When did users connect ?
Code:
def users():
retlist = []
rawlist = cext.users()
for item in rawlist:
(user, hostname, tstamp) = item
user = py2_strencode(user)
nt = _common.suser(user, None, hostname, tstamp)
retlist.append(nt)
return retlist
|
null | null | null | When does a sibling be right ?
| def select_direct_adjacent(cache, left, right):
right = (always_in if (right is None) else frozenset(right))
for parent in left:
for sibling in cache.itersiblings(parent):
if (sibling in right):
(yield sibling)
break
| null | null | null | immediately after left
| codeqa | def select direct adjacent cache left right right always in if right is None else frozenset right for parent in left for sibling in cache itersiblings parent if sibling in right yield sibling break
| null | null | null | null | Question:
When does a sibling be right ?
Code:
def select_direct_adjacent(cache, left, right):
right = (always_in if (right is None) else frozenset(right))
for parent in left:
for sibling in cache.itersiblings(parent):
if (sibling in right):
(yield sibling)
break
|
null | null | null | What does the code escape ?
| def _EscapeCommandLineArgumentForMSVS(s):
def _Replace(match):
return ((2 * match.group(1)) + '\\"')
s = quote_replacer_regex.sub(_Replace, s)
s = (('"' + s) + '"')
return s
| null | null | null | a windows command - line argument
| codeqa | def Escape Command Line Argument For MSVS s def Replace match return 2 * match group 1 + '\\"' s quote replacer regex sub Replace s s '"' + s + '"' return s
| null | null | null | null | Question:
What does the code escape ?
Code:
def _EscapeCommandLineArgumentForMSVS(s):
def _Replace(match):
return ((2 * match.group(1)) + '\\"')
s = quote_replacer_regex.sub(_Replace, s)
s = (('"' + s) + '"')
return s
|
null | null | null | What do a string represent ?
| def version(*names, **kwargs):
return __salt__['pkg_resource.version'](*names, **kwargs)
| null | null | null | the package version
| codeqa | def version *names **kwargs return salt ['pkg resource version'] *names **kwargs
| null | null | null | null | Question:
What do a string represent ?
Code:
def version(*names, **kwargs):
return __salt__['pkg_resource.version'](*names, **kwargs)
|
null | null | null | What is representing the package version ?
| def version(*names, **kwargs):
return __salt__['pkg_resource.version'](*names, **kwargs)
| null | null | null | a string
| codeqa | def version *names **kwargs return salt ['pkg resource version'] *names **kwargs
| null | null | null | null | Question:
What is representing the package version ?
Code:
def version(*names, **kwargs):
return __salt__['pkg_resource.version'](*names, **kwargs)
|
null | null | null | How does an index instance return ?
| def load(kind=None):
cfg = config.load()
if (not kind):
kind = cfg.search_backend.lower()
if (kind == 'sqlalchemy'):
from . import db
return db.SQLAlchemyIndex()
try:
module = importlib.import_module(kind)
except ImportError:
pass
else:
return module.Index()
raise NotImplementedError('Unknown index type {0!r}'.format(kind))
| null | null | null | according to the configuration
| codeqa | def load kind None cfg config load if not kind kind cfg search backend lower if kind 'sqlalchemy' from import dbreturn db SQL Alchemy Index try module importlib import module kind except Import Error passelse return module Index raise Not Implemented Error ' Unknownindextype{ 0 r}' format kind
| null | null | null | null | Question:
How does an index instance return ?
Code:
def load(kind=None):
cfg = config.load()
if (not kind):
kind = cfg.search_backend.lower()
if (kind == 'sqlalchemy'):
from . import db
return db.SQLAlchemyIndex()
try:
module = importlib.import_module(kind)
except ImportError:
pass
else:
return module.Index()
raise NotImplementedError('Unknown index type {0!r}'.format(kind))
|
null | null | null | What does the code build ?
| def describe_file(module):
from . import remote
descriptor = FileDescriptor()
descriptor.package = util.get_package_for_module(module)
if (not descriptor.package):
descriptor.package = None
message_descriptors = []
enum_descriptors = []
service_descriptors = []
for name in sorted(dir(module)):
value = getattr(module, name)
if isinstance(value, type):
if issubclass(value, messages.Message):
message_descriptors.append(describe_message(value))
elif issubclass(value, messages.Enum):
enum_descriptors.append(describe_enum(value))
elif issubclass(value, remote.Service):
service_descriptors.append(describe_service(value))
if message_descriptors:
descriptor.message_types = message_descriptors
if enum_descriptors:
descriptor.enum_types = enum_descriptors
if service_descriptors:
descriptor.service_types = service_descriptors
return descriptor
| null | null | null | a file from a specified python module
| codeqa | def describe file module from import remotedescriptor File Descriptor descriptor package util get package for module module if not descriptor package descriptor package Nonemessage descriptors []enum descriptors []service descriptors []for name in sorted dir module value getattr module name if isinstance value type if issubclass value messages Message message descriptors append describe message value elif issubclass value messages Enum enum descriptors append describe enum value elif issubclass value remote Service service descriptors append describe service value if message descriptors descriptor message types message descriptorsif enum descriptors descriptor enum types enum descriptorsif service descriptors descriptor service types service descriptorsreturn descriptor
| null | null | null | null | Question:
What does the code build ?
Code:
def describe_file(module):
from . import remote
descriptor = FileDescriptor()
descriptor.package = util.get_package_for_module(module)
if (not descriptor.package):
descriptor.package = None
message_descriptors = []
enum_descriptors = []
service_descriptors = []
for name in sorted(dir(module)):
value = getattr(module, name)
if isinstance(value, type):
if issubclass(value, messages.Message):
message_descriptors.append(describe_message(value))
elif issubclass(value, messages.Enum):
enum_descriptors.append(describe_enum(value))
elif issubclass(value, remote.Service):
service_descriptors.append(describe_service(value))
if message_descriptors:
descriptor.message_types = message_descriptors
if enum_descriptors:
descriptor.enum_types = enum_descriptors
if service_descriptors:
descriptor.service_types = service_descriptors
return descriptor
|
null | null | null | What returns an open port ?
| def test_choose_port_returns_an_open_port():
app = OnionShare()
app.choose_port()
socket.socket().bind(('127.0.0.1', app.port))
| null | null | null | choose_port
| codeqa | def test choose port returns an open port app Onion Share app choose port socket socket bind '127 0 0 1' app port
| null | null | null | null | Question:
What returns an open port ?
Code:
def test_choose_port_returns_an_open_port():
app = OnionShare()
app.choose_port()
socket.socket().bind(('127.0.0.1', app.port))
|
null | null | null | What does choose_port return ?
| def test_choose_port_returns_an_open_port():
app = OnionShare()
app.choose_port()
socket.socket().bind(('127.0.0.1', app.port))
| null | null | null | an open port
| codeqa | def test choose port returns an open port app Onion Share app choose port socket socket bind '127 0 0 1' app port
| null | null | null | null | Question:
What does choose_port return ?
Code:
def test_choose_port_returns_an_open_port():
app = OnionShare()
app.choose_port()
socket.socket().bind(('127.0.0.1', app.port))
|
null | null | null | What does the code get ?
| def getNewDerivation(elementNode, prefix, sideLength):
return SegmentDerivation(elementNode, prefix)
| null | null | null | new derivation
| codeqa | def get New Derivation element Node prefix side Length return Segment Derivation element Node prefix
| null | null | null | null | Question:
What does the code get ?
Code:
def getNewDerivation(elementNode, prefix, sideLength):
return SegmentDerivation(elementNode, prefix)
|
null | null | null | What is returning lines ?
| def backward(f, blocksize=4096):
f.seek(0, os.SEEK_END)
if (f.tell() == 0):
return
last_row = ''
while (f.tell() != 0):
try:
f.seek((- blocksize), os.SEEK_CUR)
except IOError:
blocksize = f.tell()
f.seek((- blocksize), os.SEEK_CUR)
block = f.read(blocksize)
f.seek((- blocksize), os.SEEK_CUR)
rows = block.split('\n')
rows[(-1)] = (rows[(-1)] + last_row)
while rows:
last_row = rows.pop((-1))
if (rows and last_row):
(yield last_row)
(yield last_row)
| null | null | null | a generator
| codeqa | def backward f blocksize 4096 f seek 0 os SEEK END if f tell 0 returnlast row ''while f tell 0 try f seek - blocksize os SEEK CUR except IO Error blocksize f tell f seek - blocksize os SEEK CUR block f read blocksize f seek - blocksize os SEEK CUR rows block split '\n' rows[ -1 ] rows[ -1 ] + last row while rows last row rows pop -1 if rows and last row yield last row yield last row
| null | null | null | null | Question:
What is returning lines ?
Code:
def backward(f, blocksize=4096):
f.seek(0, os.SEEK_END)
if (f.tell() == 0):
return
last_row = ''
while (f.tell() != 0):
try:
f.seek((- blocksize), os.SEEK_CUR)
except IOError:
blocksize = f.tell()
f.seek((- blocksize), os.SEEK_CUR)
block = f.read(blocksize)
f.seek((- blocksize), os.SEEK_CUR)
rows = block.split('\n')
rows[(-1)] = (rows[(-1)] + last_row)
while rows:
last_row = rows.pop((-1))
if (rows and last_row):
(yield last_row)
(yield last_row)
|
null | null | null | What does the code add ?
| @shared_task
def add(x, y):
return (x + y)
| null | null | null | two numbers
| codeqa | @shared taskdef add x y return x + y
| null | null | null | null | Question:
What does the code add ?
Code:
@shared_task
def add(x, y):
return (x + y)
|
null | null | null | What does the code add to the given element ?
| def _add_element_attrs(elem, attrs):
for (attr, value) in attrs.items():
elem.attrib[attr] = value
return elem
| null | null | null | attributes
| codeqa | def add element attrs elem attrs for attr value in attrs items elem attrib[attr] valuereturn elem
| null | null | null | null | Question:
What does the code add to the given element ?
Code:
def _add_element_attrs(elem, attrs):
for (attr, value) in attrs.items():
elem.attrib[attr] = value
return elem
|
null | null | null | What does the code turn back into its character representation ?
| def characters(probabilities):
return [id2char(c) for c in np.argmax(probabilities, 1)]
| null | null | null | a 1-hot encoding or a probability distribution over the possible characters
| codeqa | def characters probabilities return [id 2 char c for c in np argmax probabilities 1 ]
| null | null | null | null | Question:
What does the code turn back into its character representation ?
Code:
def characters(probabilities):
return [id2char(c) for c in np.argmax(probabilities, 1)]
|
null | null | null | What should exist in the design document ?
| def ensure_views():
options = _get_options(ret=None)
_response = _request('GET', ((options['url'] + options['db']) + '/_design/salt'))
if ('error' in _response):
return set_salt_view()
for view in get_valid_salt_views():
if (view not in _response['views']):
return set_salt_view()
return True
| null | null | null | all the views
| codeqa | def ensure views options get options ret None response request 'GET' options['url'] + options['db'] + '/ design/salt' if 'error' in response return set salt view for view in get valid salt views if view not in response['views'] return set salt view return True
| null | null | null | null | Question:
What should exist in the design document ?
Code:
def ensure_views():
options = _get_options(ret=None)
_response = _request('GET', ((options['url'] + options['db']) + '/_design/salt'))
if ('error' in _response):
return set_salt_view()
for view in get_valid_salt_views():
if (view not in _response['views']):
return set_salt_view()
return True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.