labNo float64 1 10 ⌀ | taskNo float64 0 4 ⌀ | questioner stringclasses 2 values | question stringlengths 9 201 | code stringlengths 18 30.3k | startLine float64 0 192 ⌀ | endLine float64 0 196 ⌀ | questionType stringclasses 4 values | answer stringlengths 2 905 | src stringclasses 3 values | code_processed stringlengths 12 28.3k ⌀ | id stringlengths 2 5 ⌀ | raw_code stringlengths 20 30.3k ⌀ | raw_comment stringlengths 10 242 ⌀ | comment stringlengths 9 207 ⌀ | q_code stringlengths 66 30.3k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
null | null | null | What does the code show ?
| def showwarning(title=None, message=None, **options):
return _show(title, message, WARNING, OK, **options)
| null | null | null | a warning message
| codeqa | def showwarning title None message None **options return show title message WARNING OK **options
| null | null | null | null | Question:
What does the code show ?
Code:
def showwarning(title=None, message=None, **options):
return _show(title, message, WARNING, OK, **options)
|
null | null | null | What does the code create ?
| def create_network(context, net_id, vlan):
session = context.session
with session.begin(subtransactions=True):
net = BrocadeNetwork(id=net_id, vlan=vlan)
session.add(net)
return net
| null | null | null | a brocade specific network / port - profiles
| codeqa | def create network context net id vlan session context sessionwith session begin subtransactions True net Brocade Network id net id vlan vlan session add net return net
| null | null | null | null | Question:
What does the code create ?
Code:
def create_network(context, net_id, vlan):
session = context.session
with session.begin(subtransactions=True):
net = BrocadeNetwork(id=net_id, vlan=vlan)
session.add(net)
return net
|
null | null | null | What does the code run ?
| def execusercustomize():
try:
import usercustomize
except ImportError:
pass
except Exception:
if sys.flags.verbose:
sys.excepthook(*sys.exc_info())
else:
print >>sys.stderr, "'import usercustomize' failed; use -v for traceback"
| null | null | null | custom user specific code
| codeqa | def execusercustomize try import usercustomizeexcept Import Error passexcept Exception if sys flags verbose sys excepthook *sys exc info else print >>sys stderr "'importusercustomize'failed use-vfortraceback"
| null | null | null | null | Question:
What does the code run ?
Code:
def execusercustomize():
try:
import usercustomize
except ImportError:
pass
except Exception:
if sys.flags.verbose:
sys.excepthook(*sys.exc_info())
else:
print >>sys.stderr, "'import usercustomize' failed; use -v for traceback"
|
null | null | null | What does the code install ?
| def install(poll_interval=1):
mon = Monitor(poll_interval=poll_interval)
t = threading.Thread(target=mon.periodic_reload)
t.setDaemon(True)
t.start()
| null | null | null | the reloading monitor
| codeqa | def install poll interval 1 mon Monitor poll interval poll interval t threading Thread target mon periodic reload t set Daemon True t start
| null | null | null | null | Question:
What does the code install ?
Code:
def install(poll_interval=1):
mon = Monitor(poll_interval=poll_interval)
t = threading.Thread(target=mon.periodic_reload)
t.setDaemon(True)
t.start()
|
null | null | null | What does the code remove if i d does not actually change the broadcasting pattern ?
| @register_useless
@register_canonicalize
@register_specialize
@gof.local_optimizer([T.Rebroadcast])
def local_useless_rebroadcast(node):
if isinstance(node.op, T.Rebroadcast):
x = node.inputs[0]
if numpy.all((x.broadcastable == node.outputs[0].broadcastable)):
return [x]
else:
new_axis = {}
for (dim, bc) in list(node.op.axis.items()):
if (x.broadcastable[dim] != bc):
new_axis[dim] = bc
if (new_axis == node.op.axis):
return
else:
r = T.Rebroadcast(*list(new_axis.items()))(x)
copy_stack_trace(node.outputs, r)
return [r]
| null | null | null | rebroadcast
| codeqa | @register useless@register canonicalize@register specialize@gof local optimizer [T Rebroadcast] def local useless rebroadcast node if isinstance node op T Rebroadcast x node inputs[ 0 ]if numpy all x broadcastable node outputs[ 0 ] broadcastable return [x]else new axis {}for dim bc in list node op axis items if x broadcastable[dim] bc new axis[dim] bcif new axis node op axis returnelse r T Rebroadcast *list new axis items x copy stack trace node outputs r return [r]
| null | null | null | null | Question:
What does the code remove if i d does not actually change the broadcasting pattern ?
Code:
@register_useless
@register_canonicalize
@register_specialize
@gof.local_optimizer([T.Rebroadcast])
def local_useless_rebroadcast(node):
if isinstance(node.op, T.Rebroadcast):
x = node.inputs[0]
if numpy.all((x.broadcastable == node.outputs[0].broadcastable)):
return [x]
else:
new_axis = {}
for (dim, bc) in list(node.op.axis.items()):
if (x.broadcastable[dim] != bc):
new_axis[dim] = bc
if (new_axis == node.op.axis):
return
else:
r = T.Rebroadcast(*list(new_axis.items()))(x)
copy_stack_trace(node.outputs, r)
return [r]
|
null | null | null | Who d does not change the broadcasting pattern actually ?
| @register_useless
@register_canonicalize
@register_specialize
@gof.local_optimizer([T.Rebroadcast])
def local_useless_rebroadcast(node):
if isinstance(node.op, T.Rebroadcast):
x = node.inputs[0]
if numpy.all((x.broadcastable == node.outputs[0].broadcastable)):
return [x]
else:
new_axis = {}
for (dim, bc) in list(node.op.axis.items()):
if (x.broadcastable[dim] != bc):
new_axis[dim] = bc
if (new_axis == node.op.axis):
return
else:
r = T.Rebroadcast(*list(new_axis.items()))(x)
copy_stack_trace(node.outputs, r)
return [r]
| null | null | null | i d
| codeqa | @register useless@register canonicalize@register specialize@gof local optimizer [T Rebroadcast] def local useless rebroadcast node if isinstance node op T Rebroadcast x node inputs[ 0 ]if numpy all x broadcastable node outputs[ 0 ] broadcastable return [x]else new axis {}for dim bc in list node op axis items if x broadcastable[dim] bc new axis[dim] bcif new axis node op axis returnelse r T Rebroadcast *list new axis items x copy stack trace node outputs r return [r]
| null | null | null | null | Question:
Who d does not change the broadcasting pattern actually ?
Code:
@register_useless
@register_canonicalize
@register_specialize
@gof.local_optimizer([T.Rebroadcast])
def local_useless_rebroadcast(node):
if isinstance(node.op, T.Rebroadcast):
x = node.inputs[0]
if numpy.all((x.broadcastable == node.outputs[0].broadcastable)):
return [x]
else:
new_axis = {}
for (dim, bc) in list(node.op.axis.items()):
if (x.broadcastable[dim] != bc):
new_axis[dim] = bc
if (new_axis == node.op.axis):
return
else:
r = T.Rebroadcast(*list(new_axis.items()))(x)
copy_stack_trace(node.outputs, r)
return [r]
|
null | null | null | D i d does change the broadcasting pattern actually ?
| @register_useless
@register_canonicalize
@register_specialize
@gof.local_optimizer([T.Rebroadcast])
def local_useless_rebroadcast(node):
if isinstance(node.op, T.Rebroadcast):
x = node.inputs[0]
if numpy.all((x.broadcastable == node.outputs[0].broadcastable)):
return [x]
else:
new_axis = {}
for (dim, bc) in list(node.op.axis.items()):
if (x.broadcastable[dim] != bc):
new_axis[dim] = bc
if (new_axis == node.op.axis):
return
else:
r = T.Rebroadcast(*list(new_axis.items()))(x)
copy_stack_trace(node.outputs, r)
return [r]
| null | null | null | No
| codeqa | @register useless@register canonicalize@register specialize@gof local optimizer [T Rebroadcast] def local useless rebroadcast node if isinstance node op T Rebroadcast x node inputs[ 0 ]if numpy all x broadcastable node outputs[ 0 ] broadcastable return [x]else new axis {}for dim bc in list node op axis items if x broadcastable[dim] bc new axis[dim] bcif new axis node op axis returnelse r T Rebroadcast *list new axis items x copy stack trace node outputs r return [r]
| null | null | null | null | Question:
D i d does change the broadcasting pattern actually ?
Code:
@register_useless
@register_canonicalize
@register_specialize
@gof.local_optimizer([T.Rebroadcast])
def local_useless_rebroadcast(node):
if isinstance(node.op, T.Rebroadcast):
x = node.inputs[0]
if numpy.all((x.broadcastable == node.outputs[0].broadcastable)):
return [x]
else:
new_axis = {}
for (dim, bc) in list(node.op.axis.items()):
if (x.broadcastable[dim] != bc):
new_axis[dim] = bc
if (new_axis == node.op.axis):
return
else:
r = T.Rebroadcast(*list(new_axis.items()))(x)
copy_stack_trace(node.outputs, r)
return [r]
|
null | null | null | What does the code retrieve ?
| def get_relative_path_to_pack(pack_ref, file_path):
pack_base_path = get_pack_base_path(pack_name=pack_ref)
if (not os.path.isabs(file_path)):
return file_path
common_prefix = os.path.commonprefix([pack_base_path, file_path])
if (common_prefix != pack_base_path):
raise ValueError('file_path is not located inside the pack directory')
relative_path = os.path.relpath(file_path, common_prefix)
return relative_path
| null | null | null | a file path which is relative to the provided pack directory
| codeqa | def get relative path to pack pack ref file path pack base path get pack base path pack name pack ref if not os path isabs file path return file pathcommon prefix os path commonprefix [pack base path file path] if common prefix pack base path raise Value Error 'file pathisnotlocatedinsidethepackdirectory' relative path os path relpath file path common prefix return relative path
| null | null | null | null | Question:
What does the code retrieve ?
Code:
def get_relative_path_to_pack(pack_ref, file_path):
pack_base_path = get_pack_base_path(pack_name=pack_ref)
if (not os.path.isabs(file_path)):
return file_path
common_prefix = os.path.commonprefix([pack_base_path, file_path])
if (common_prefix != pack_base_path):
raise ValueError('file_path is not located inside the pack directory')
relative_path = os.path.relpath(file_path, common_prefix)
return relative_path
|
null | null | null | What does the code get ?
| def backup_get_all(context):
return IMPL.backup_get_all(context)
| null | null | null | all backups
| codeqa | def backup get all context return IMPL backup get all context
| null | null | null | null | Question:
What does the code get ?
Code:
def backup_get_all(context):
return IMPL.backup_get_all(context)
|
null | null | null | What do they have ?
| def _scrub_empty_str_values(dct, keys_to_scrub):
for key in keys_to_scrub:
if ((key in dct) and (dct[key] == '')):
del dct[key]
| null | null | null | the value
| codeqa | def scrub empty str values dct keys to scrub for key in keys to scrub if key in dct and dct[key] '' del dct[key]
| null | null | null | null | Question:
What do they have ?
Code:
def _scrub_empty_str_values(dct, keys_to_scrub):
for key in keys_to_scrub:
if ((key in dct) and (dct[key] == '')):
del dct[key]
|
null | null | null | What found in sequence ?
| def _scrub_empty_str_values(dct, keys_to_scrub):
for key in keys_to_scrub:
if ((key in dct) and (dct[key] == '')):
del dct[key]
| null | null | null | any keys
| codeqa | def scrub empty str values dct keys to scrub for key in keys to scrub if key in dct and dct[key] '' del dct[key]
| null | null | null | null | Question:
What found in sequence ?
Code:
def _scrub_empty_str_values(dct, keys_to_scrub):
for key in keys_to_scrub:
if ((key in dct) and (dct[key] == '')):
del dct[key]
|
null | null | null | Where did any keys find ?
| def _scrub_empty_str_values(dct, keys_to_scrub):
for key in keys_to_scrub:
if ((key in dct) and (dct[key] == '')):
del dct[key]
| null | null | null | in sequence
| codeqa | def scrub empty str values dct keys to scrub for key in keys to scrub if key in dct and dct[key] '' del dct[key]
| null | null | null | null | Question:
Where did any keys find ?
Code:
def _scrub_empty_str_values(dct, keys_to_scrub):
for key in keys_to_scrub:
if ((key in dct) and (dct[key] == '')):
del dct[key]
|
null | null | null | Who have the value ?
| def _scrub_empty_str_values(dct, keys_to_scrub):
for key in keys_to_scrub:
if ((key in dct) and (dct[key] == '')):
del dct[key]
| null | null | null | they
| codeqa | def scrub empty str values dct keys to scrub for key in keys to scrub if key in dct and dct[key] '' del dct[key]
| null | null | null | null | Question:
Who have the value ?
Code:
def _scrub_empty_str_values(dct, keys_to_scrub):
for key in keys_to_scrub:
if ((key in dct) and (dct[key] == '')):
del dct[key]
|
null | null | null | What have the code remove if they have the value ?
| def _scrub_empty_str_values(dct, keys_to_scrub):
for key in keys_to_scrub:
if ((key in dct) and (dct[key] == '')):
del dct[key]
| null | null | null | any keys found in sequence keys_to_scrub from the dict
| codeqa | def scrub empty str values dct keys to scrub for key in keys to scrub if key in dct and dct[key] '' del dct[key]
| null | null | null | null | Question:
What have the code remove if they have the value ?
Code:
def _scrub_empty_str_values(dct, keys_to_scrub):
for key in keys_to_scrub:
if ((key in dct) and (dct[key] == '')):
del dct[key]
|
null | null | null | What did the code set ?
| def set_warndays(name, days):
return False
| null | null | null | the number of days before the password expires that the user will start to see a warning
| codeqa | def set warndays name days return False
| null | null | null | null | Question:
What did the code set ?
Code:
def set_warndays(name, days):
return False
|
null | null | null | What sidesteps the issue of bogus /etc / hosts entries and other local misconfigurations ?
| def get_my_ip():
import socket
try:
import Pyro4
ns = Pyro4.naming.locateNS()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((ns._pyroUri.host, ns._pyroUri.port))
(result, port) = s.getsockname()
except:
try:
import commands
result = commands.getoutput('ifconfig').split('\n')[1].split()[1][5:]
if (len(result.split('.')) != 4):
raise Exception()
except:
result = socket.gethostbyname(socket.gethostname())
return result
| null | null | null | this
| codeqa | def get my ip import sockettry import Pyro 4 ns Pyro 4 naming locate NS s socket socket socket AF INET socket SOCK DGRAM s connect ns pyro Uri host ns pyro Uri port result port s getsockname except try import commandsresult commands getoutput 'ifconfig' split '\n' [1 ] split [1 ][ 5 ]if len result split ' ' 4 raise Exception except result socket gethostbyname socket gethostname return result
| null | null | null | null | Question:
What sidesteps the issue of bogus /etc / hosts entries and other local misconfigurations ?
Code:
def get_my_ip():
import socket
try:
import Pyro4
ns = Pyro4.naming.locateNS()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((ns._pyroUri.host, ns._pyroUri.port))
(result, port) = s.getsockname()
except:
try:
import commands
result = commands.getoutput('ifconfig').split('\n')[1].split()[1][5:]
if (len(result.split('.')) != 4):
raise Exception()
except:
result = socket.gethostbyname(socket.gethostname())
return result
|
null | null | null | What does this try ?
| def get_my_ip():
import socket
try:
import Pyro4
ns = Pyro4.naming.locateNS()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((ns._pyroUri.host, ns._pyroUri.port))
(result, port) = s.getsockname()
except:
try:
import commands
result = commands.getoutput('ifconfig').split('\n')[1].split()[1][5:]
if (len(result.split('.')) != 4):
raise Exception()
except:
result = socket.gethostbyname(socket.gethostname())
return result
| null | null | null | to sidestep the issue of bogus /etc / hosts entries and other local misconfigurations
| codeqa | def get my ip import sockettry import Pyro 4 ns Pyro 4 naming locate NS s socket socket socket AF INET socket SOCK DGRAM s connect ns pyro Uri host ns pyro Uri port result port s getsockname except try import commandsresult commands getoutput 'ifconfig' split '\n' [1 ] split [1 ][ 5 ]if len result split ' ' 4 raise Exception except result socket gethostbyname socket gethostname return result
| null | null | null | null | Question:
What does this try ?
Code:
def get_my_ip():
import socket
try:
import Pyro4
ns = Pyro4.naming.locateNS()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((ns._pyroUri.host, ns._pyroUri.port))
(result, port) = s.getsockname()
except:
try:
import commands
result = commands.getoutput('ifconfig').split('\n')[1].split()[1][5:]
if (len(result.split('.')) != 4):
raise Exception()
except:
result = socket.gethostbyname(socket.gethostname())
return result
|
null | null | null | What tries to sidestep the issue of bogus /etc / hosts entries and other local misconfigurations ?
| def get_my_ip():
import socket
try:
import Pyro4
ns = Pyro4.naming.locateNS()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((ns._pyroUri.host, ns._pyroUri.port))
(result, port) = s.getsockname()
except:
try:
import commands
result = commands.getoutput('ifconfig').split('\n')[1].split()[1][5:]
if (len(result.split('.')) != 4):
raise Exception()
except:
result = socket.gethostbyname(socket.gethostname())
return result
| null | null | null | this
| codeqa | def get my ip import sockettry import Pyro 4 ns Pyro 4 naming locate NS s socket socket socket AF INET socket SOCK DGRAM s connect ns pyro Uri host ns pyro Uri port result port s getsockname except try import commandsresult commands getoutput 'ifconfig' split '\n' [1 ] split [1 ][ 5 ]if len result split ' ' 4 raise Exception except result socket gethostbyname socket gethostname return result
| null | null | null | null | Question:
What tries to sidestep the issue of bogus /etc / hosts entries and other local misconfigurations ?
Code:
def get_my_ip():
import socket
try:
import Pyro4
ns = Pyro4.naming.locateNS()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((ns._pyroUri.host, ns._pyroUri.port))
(result, port) = s.getsockname()
except:
try:
import commands
result = commands.getoutput('ifconfig').split('\n')[1].split()[1][5:]
if (len(result.split('.')) != 4):
raise Exception()
except:
result = socket.gethostbyname(socket.gethostname())
return result
|
null | null | null | What does this sidestep ?
| def get_my_ip():
import socket
try:
import Pyro4
ns = Pyro4.naming.locateNS()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((ns._pyroUri.host, ns._pyroUri.port))
(result, port) = s.getsockname()
except:
try:
import commands
result = commands.getoutput('ifconfig').split('\n')[1].split()[1][5:]
if (len(result.split('.')) != 4):
raise Exception()
except:
result = socket.gethostbyname(socket.gethostname())
return result
| null | null | null | the issue of bogus /etc / hosts entries and other local misconfigurations
| codeqa | def get my ip import sockettry import Pyro 4 ns Pyro 4 naming locate NS s socket socket socket AF INET socket SOCK DGRAM s connect ns pyro Uri host ns pyro Uri port result port s getsockname except try import commandsresult commands getoutput 'ifconfig' split '\n' [1 ] split [1 ][ 5 ]if len result split ' ' 4 raise Exception except result socket gethostbyname socket gethostname return result
| null | null | null | null | Question:
What does this sidestep ?
Code:
def get_my_ip():
import socket
try:
import Pyro4
ns = Pyro4.naming.locateNS()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((ns._pyroUri.host, ns._pyroUri.port))
(result, port) = s.getsockname()
except:
try:
import commands
result = commands.getoutput('ifconfig').split('\n')[1].split()[1][5:]
if (len(result.split('.')) != 4):
raise Exception()
except:
result = socket.gethostbyname(socket.gethostname())
return result
|
null | null | null | What do all rules need ?
| def unicode_urlencode(obj, charset='utf-8', for_qs=False):
if (not isinstance(obj, string_types)):
obj = text_type(obj)
if isinstance(obj, text_type):
obj = obj.encode(charset)
safe = (((not for_qs) and '/') or '')
rv = text_type(url_quote(obj, safe))
if for_qs:
rv = rv.replace('%20', '+')
return rv
| null | null | null | to be considered under all supported python versions
| codeqa | def unicode urlencode obj charset 'utf- 8 ' for qs False if not isinstance obj string types obj text type obj if isinstance obj text type obj obj encode charset safe not for qs and '/' or '' rv text type url quote obj safe if for qs rv rv replace '% 20 ' '+' return rv
| null | null | null | null | Question:
What do all rules need ?
Code:
def unicode_urlencode(obj, charset='utf-8', for_qs=False):
if (not isinstance(obj, string_types)):
obj = text_type(obj)
if isinstance(obj, text_type):
obj = obj.encode(charset)
safe = (((not for_qs) and '/') or '')
rv = text_type(url_quote(obj, safe))
if for_qs:
rv = rv.replace('%20', '+')
return rv
|
null | null | null | What does the code turn into one of inverse argument ?
| def _flip_g(g):
def tr(l):
return [(1 - a) for a in l]
return meijerg(tr(g.bm), tr(g.bother), tr(g.an), tr(g.aother), (1 / g.argument))
| null | null | null | the g function
| codeqa | def flip g g def tr l return [ 1 - a for a in l]return meijerg tr g bm tr g bother tr g an tr g aother 1 / g argument
| null | null | null | null | Question:
What does the code turn into one of inverse argument ?
Code:
def _flip_g(g):
def tr(l):
return [(1 - a) for a in l]
return meijerg(tr(g.bm), tr(g.bother), tr(g.an), tr(g.aother), (1 / g.argument))
|
null | null | null | What appears at the top of the file ?
| def CheckForCopyright(filename, lines, error):
for line in range(1, min(len(lines), 11)):
if re.search('Copyright', lines[line], re.I):
break
else:
error(filename, 0, 'legal/copyright', 5, 'No copyright message found. You should have a line: "Copyright [year] <Copyright Owner>"')
| null | null | null | no copyright message
| codeqa | def Check For Copyright filename lines error for line in range 1 min len lines 11 if re search ' Copyright' lines[line] re I breakelse error filename 0 'legal/copyright' 5 ' Nocopyrightmessagefound Youshouldhavealine " Copyright[year]< Copyright Owner>"'
| null | null | null | null | Question:
What appears at the top of the file ?
Code:
def CheckForCopyright(filename, lines, error):
for line in range(1, min(len(lines), 11)):
if re.search('Copyright', lines[line], re.I):
break
else:
error(filename, 0, 'legal/copyright', 5, 'No copyright message found. You should have a line: "Copyright [year] <Copyright Owner>"')
|
null | null | null | Where does no copyright message appear ?
| def CheckForCopyright(filename, lines, error):
for line in range(1, min(len(lines), 11)):
if re.search('Copyright', lines[line], re.I):
break
else:
error(filename, 0, 'legal/copyright', 5, 'No copyright message found. You should have a line: "Copyright [year] <Copyright Owner>"')
| null | null | null | at the top of the file
| codeqa | def Check For Copyright filename lines error for line in range 1 min len lines 11 if re search ' Copyright' lines[line] re I breakelse error filename 0 'legal/copyright' 5 ' Nocopyrightmessagefound Youshouldhavealine " Copyright[year]< Copyright Owner>"'
| null | null | null | null | Question:
Where does no copyright message appear ?
Code:
def CheckForCopyright(filename, lines, error):
for line in range(1, min(len(lines), 11)):
if re.search('Copyright', lines[line], re.I):
break
else:
error(filename, 0, 'legal/copyright', 5, 'No copyright message found. You should have a line: "Copyright [year] <Copyright Owner>"')
|
null | null | null | What does the code tune ?
| def stop_tuning(step):
if hasattr(step, 'tune'):
step.tune = False
elif hasattr(step, 'methods'):
step.methods = [stop_tuning(s) for s in step.methods]
return step
| null | null | null | the current step method
| codeqa | def stop tuning step if hasattr step 'tune' step tune Falseelif hasattr step 'methods' step methods [stop tuning s for s in step methods]return step
| null | null | null | null | Question:
What does the code tune ?
Code:
def stop_tuning(step):
if hasattr(step, 'tune'):
step.tune = False
elif hasattr(step, 'methods'):
step.methods = [stop_tuning(s) for s in step.methods]
return step
|
null | null | null | What does the code send to your system ?
| def sendStayAwake():
return False
| null | null | null | a signal
| codeqa | def send Stay Awake return False
| null | null | null | null | Question:
What does the code send to your system ?
Code:
def sendStayAwake():
return False
|
null | null | null | What logs all internal exceptions when running in debug mode ?
| def squelch_exceptions(fn):
@functools.wraps(fn)
def squelched_fn(*a, **kw):
try:
return fn(*a, **kw)
except BaseException:
if g.debug:
raise
else:
g.log.exception('squelching exception')
return squelched_fn
| null | null | null | a function
| codeqa | def squelch exceptions fn @functools wraps fn def squelched fn *a **kw try return fn *a **kw except Base Exception if g debug raiseelse g log exception 'squelchingexception' return squelched fn
| null | null | null | null | Question:
What logs all internal exceptions when running in debug mode ?
Code:
def squelch_exceptions(fn):
@functools.wraps(fn)
def squelched_fn(*a, **kw):
try:
return fn(*a, **kw)
except BaseException:
if g.debug:
raise
else:
g.log.exception('squelching exception')
return squelched_fn
|
null | null | null | When do all internal exceptions suppress ?
| def squelch_exceptions(fn):
@functools.wraps(fn)
def squelched_fn(*a, **kw):
try:
return fn(*a, **kw)
except BaseException:
if g.debug:
raise
else:
g.log.exception('squelching exception')
return squelched_fn
| null | null | null | when running in debug mode
| codeqa | def squelch exceptions fn @functools wraps fn def squelched fn *a **kw try return fn *a **kw except Base Exception if g debug raiseelse g log exception 'squelchingexception' return squelched fn
| null | null | null | null | Question:
When do all internal exceptions suppress ?
Code:
def squelch_exceptions(fn):
@functools.wraps(fn)
def squelched_fn(*a, **kw):
try:
return fn(*a, **kw)
except BaseException:
if g.debug:
raise
else:
g.log.exception('squelching exception')
return squelched_fn
|
null | null | null | For what purpose do a function wrap ?
| def squelch_exceptions(fn):
@functools.wraps(fn)
def squelched_fn(*a, **kw):
try:
return fn(*a, **kw)
except BaseException:
if g.debug:
raise
else:
g.log.exception('squelching exception')
return squelched_fn
| null | null | null | to log and suppress all internal exceptions when running in debug mode
| codeqa | def squelch exceptions fn @functools wraps fn def squelched fn *a **kw try return fn *a **kw except Base Exception if g debug raiseelse g log exception 'squelchingexception' return squelched fn
| null | null | null | null | Question:
For what purpose do a function wrap ?
Code:
def squelch_exceptions(fn):
@functools.wraps(fn)
def squelched_fn(*a, **kw):
try:
return fn(*a, **kw)
except BaseException:
if g.debug:
raise
else:
g.log.exception('squelching exception')
return squelched_fn
|
null | null | null | How be the user logged ?
| def reviewer_required(region=None, moderator=False):
def decorator(f):
@login_required
@functools.wraps(f)
def wrapper(request, *args, **kw):
reviewer_perm = acl.check_reviewer(request)
moderator_perm = (moderator and acl.action_allowed(request, 'Apps', 'ModerateReview'))
view_only = ((request.method == 'GET') and acl.action_allowed(request, 'ReviewerTools', 'View'))
if (reviewer_perm or moderator_perm or view_only):
return f(request, *args, **kw)
else:
raise PermissionDenied
return wrapper
if callable(region):
return decorator(region)
else:
return decorator
| null | null | null | as a reviewer or admin
| codeqa | def reviewer required region None moderator False def decorator f @login required@functools wraps f def wrapper request *args **kw reviewer perm acl check reviewer request moderator perm moderator and acl action allowed request ' Apps' ' Moderate Review' view only request method 'GET' and acl action allowed request ' Reviewer Tools' ' View' if reviewer perm or moderator perm or view only return f request *args **kw else raise Permission Deniedreturn wrapperif callable region return decorator region else return decorator
| null | null | null | null | Question:
How be the user logged ?
Code:
def reviewer_required(region=None, moderator=False):
def decorator(f):
@login_required
@functools.wraps(f)
def wrapper(request, *args, **kw):
reviewer_perm = acl.check_reviewer(request)
moderator_perm = (moderator and acl.action_allowed(request, 'Apps', 'ModerateReview'))
view_only = ((request.method == 'GET') and acl.action_allowed(request, 'ReviewerTools', 'View'))
if (reviewer_perm or moderator_perm or view_only):
return f(request, *args, **kw)
else:
raise PermissionDenied
return wrapper
if callable(region):
return decorator(region)
else:
return decorator
|
null | null | null | What does the code invoke ?
| def cast(context, topic, msg):
return _get_impl().cast(CONF, context, topic, msg)
| null | null | null | a remote method that does not return anything
| codeqa | def cast context topic msg return get impl cast CONF context topic msg
| null | null | null | null | Question:
What does the code invoke ?
Code:
def cast(context, topic, msg):
return _get_impl().cast(CONF, context, topic, msg)
|
null | null | null | Does a remote method return anything ?
| def cast(context, topic, msg):
return _get_impl().cast(CONF, context, topic, msg)
| null | null | null | No
| codeqa | def cast context topic msg return get impl cast CONF context topic msg
| null | null | null | null | Question:
Does a remote method return anything ?
Code:
def cast(context, topic, msg):
return _get_impl().cast(CONF, context, topic, msg)
|
null | null | null | What does a remote method not return ?
| def cast(context, topic, msg):
return _get_impl().cast(CONF, context, topic, msg)
| null | null | null | anything
| codeqa | def cast context topic msg return get impl cast CONF context topic msg
| null | null | null | null | Question:
What does a remote method not return ?
Code:
def cast(context, topic, msg):
return _get_impl().cast(CONF, context, topic, msg)
|
null | null | null | What does not return anything ?
| def cast(context, topic, msg):
return _get_impl().cast(CONF, context, topic, msg)
| null | null | null | a remote method
| codeqa | def cast context topic msg return get impl cast CONF context topic msg
| null | null | null | null | Question:
What does not return anything ?
Code:
def cast(context, topic, msg):
return _get_impl().cast(CONF, context, topic, msg)
|
null | null | null | What given in key / val pairs ?
| def validate_positive_scalars(**kwargs):
for (key, val) in kwargs.items():
try:
if (val <= 0):
raise ValueError('{} must be > 0, got {}'.format(key, val))
except TypeError:
raise exceptions.PlotlyError('{} must be a number, got {}'.format(key, val))
| null | null | null | all values
| codeqa | def validate positive scalars **kwargs for key val in kwargs items try if val < 0 raise Value Error '{}mustbe> 0 got{}' format key val except Type Error raise exceptions Plotly Error '{}mustbeanumber got{}' format key val
| null | null | null | null | Question:
What given in key / val pairs ?
Code:
def validate_positive_scalars(**kwargs):
for (key, val) in kwargs.items():
try:
if (val <= 0):
raise ValueError('{} must be > 0, got {}'.format(key, val))
except TypeError:
raise exceptions.PlotlyError('{} must be a number, got {}'.format(key, val))
|
null | null | null | Where did all values give ?
| def validate_positive_scalars(**kwargs):
for (key, val) in kwargs.items():
try:
if (val <= 0):
raise ValueError('{} must be > 0, got {}'.format(key, val))
except TypeError:
raise exceptions.PlotlyError('{} must be a number, got {}'.format(key, val))
| null | null | null | in key / val pairs
| codeqa | def validate positive scalars **kwargs for key val in kwargs items try if val < 0 raise Value Error '{}mustbe> 0 got{}' format key val except Type Error raise exceptions Plotly Error '{}mustbeanumber got{}' format key val
| null | null | null | null | Question:
Where did all values give ?
Code:
def validate_positive_scalars(**kwargs):
for (key, val) in kwargs.items():
try:
if (val <= 0):
raise ValueError('{} must be > 0, got {}'.format(key, val))
except TypeError:
raise exceptions.PlotlyError('{} must be a number, got {}'.format(key, val))
|
null | null | null | What has required tools ?
| def __virtual__():
supported_os_tool = {'FreeBSD': 'ifconfig', 'Linux': 'brctl', 'NetBSD': 'brconfig', 'OpenBSD': 'ifconfig'}
cur_os = __grains__['kernel']
for _os in supported_os_tool:
if ((cur_os == _os) and salt.utils.which(supported_os_tool[cur_os])):
return True
return (False, 'The bridge execution module failed to load: requires one of the following tool/os combinations: ifconfig on FreeBSD/OpenBSD, brctl on Linux or brconfig on NetBSD.')
| null | null | null | the system
| codeqa | def virtual supported os tool {' Free BSD' 'ifconfig' ' Linux' 'brctl' ' Net BSD' 'brconfig' ' Open BSD' 'ifconfig'}cur os grains ['kernel']for os in supported os tool if cur os os and salt utils which supported os tool[cur os] return Truereturn False ' Thebridgeexecutionmodulefailedtoload requiresoneofthefollowingtool/oscombinations ifconfigon Free BSD/ Open BSD brctlon Linuxorbrconfigon Net BSD '
| null | null | null | null | Question:
What has required tools ?
Code:
def __virtual__():
supported_os_tool = {'FreeBSD': 'ifconfig', 'Linux': 'brctl', 'NetBSD': 'brconfig', 'OpenBSD': 'ifconfig'}
cur_os = __grains__['kernel']
for _os in supported_os_tool:
if ((cur_os == _os) and salt.utils.which(supported_os_tool[cur_os])):
return True
return (False, 'The bridge execution module failed to load: requires one of the following tool/os combinations: ifconfig on FreeBSD/OpenBSD, brctl on Linux or brconfig on NetBSD.')
|
null | null | null | What has the system required ?
| def __virtual__():
supported_os_tool = {'FreeBSD': 'ifconfig', 'Linux': 'brctl', 'NetBSD': 'brconfig', 'OpenBSD': 'ifconfig'}
cur_os = __grains__['kernel']
for _os in supported_os_tool:
if ((cur_os == _os) and salt.utils.which(supported_os_tool[cur_os])):
return True
return (False, 'The bridge execution module failed to load: requires one of the following tool/os combinations: ifconfig on FreeBSD/OpenBSD, brctl on Linux or brconfig on NetBSD.')
| null | null | null | tools
| codeqa | def virtual supported os tool {' Free BSD' 'ifconfig' ' Linux' 'brctl' ' Net BSD' 'brconfig' ' Open BSD' 'ifconfig'}cur os grains ['kernel']for os in supported os tool if cur os os and salt utils which supported os tool[cur os] return Truereturn False ' Thebridgeexecutionmodulefailedtoload requiresoneofthefollowingtool/oscombinations ifconfigon Free BSD/ Open BSD brctlon Linuxorbrconfigon Net BSD '
| null | null | null | null | Question:
What has the system required ?
Code:
def __virtual__():
supported_os_tool = {'FreeBSD': 'ifconfig', 'Linux': 'brctl', 'NetBSD': 'brconfig', 'OpenBSD': 'ifconfig'}
cur_os = __grains__['kernel']
for _os in supported_os_tool:
if ((cur_os == _os) and salt.utils.which(supported_os_tool[cur_os])):
return True
return (False, 'The bridge execution module failed to load: requires one of the following tool/os combinations: ifconfig on FreeBSD/OpenBSD, brctl on Linux or brconfig on NetBSD.')
|
null | null | null | What does the code make from a hist object ?
| def MakeSuiteFromHist(hist, label=None):
if (label is None):
label = hist.label
d = dict(hist.GetDict())
return MakeSuiteFromDict(d, label)
| null | null | null | a normalized suite
| codeqa | def Make Suite From Hist hist label None if label is None label hist labeld dict hist Get Dict return Make Suite From Dict d label
| null | null | null | null | Question:
What does the code make from a hist object ?
Code:
def MakeSuiteFromHist(hist, label=None):
if (label is None):
label = hist.label
d = dict(hist.GetDict())
return MakeSuiteFromDict(d, label)
|
null | null | null | When is it not set ?
| def set_mysql_collation_for_column(apps, cursor, model, column, collation, schema):
if (not hasattr(cursor.db, 'mysql_version')):
return
db_name = cursor.db.get_connection_params()['db']
table_name = apps.get_model(model)._meta.db_table
cursor.execute(("SELECT COLLATION_NAME FROM `information_schema`.`columns` WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = '%s' AND COLUMN_NAME = '%s';" % (db_name, table_name, column)))
current_collation = cursor.fetchone()[0]
if (current_collation != collation):
cursor.execute(('ALTER TABLE `%s`.`%s` MODIFY `%s` %s CHARACTER SET utf8 COLLATE %s NOT NULL;' % (db_name, table_name, column, schema, collation)))
| null | null | null | already
| codeqa | def set mysql collation for column apps cursor model column collation schema if not hasattr cursor db 'mysql version' returndb name cursor db get connection params ['db']table name apps get model model meta db tablecursor execute "SELECTCOLLATION NAMEFROM`information schema` `columns`WHERETABLE SCHEMA '%s'ANDTABLE NAME '%s'ANDCOLUMN NAME '%s' " % db name table name column current collation cursor fetchone [0 ]if current collation collation cursor execute 'ALTERTABLE`%s` `%s`MODIFY`%s`%s CHARACTERSE Tutf 8 COLLATE%s NOTNULL ' % db name table name column schema collation
| null | null | null | null | Question:
When is it not set ?
Code:
def set_mysql_collation_for_column(apps, cursor, model, column, collation, schema):
if (not hasattr(cursor.db, 'mysql_version')):
return
db_name = cursor.db.get_connection_params()['db']
table_name = apps.get_model(model)._meta.db_table
cursor.execute(("SELECT COLLATION_NAME FROM `information_schema`.`columns` WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = '%s' AND COLUMN_NAME = '%s';" % (db_name, table_name, column)))
current_collation = cursor.fetchone()[0]
if (current_collation != collation):
cursor.execute(('ALTER TABLE `%s`.`%s` MODIFY `%s` %s CHARACTER SET utf8 COLLATE %s NOT NULL;' % (db_name, table_name, column, schema, collation)))
|
null | null | null | When do positive cylinder add ?
| def addPositivePeg(derivation, positives, x, y):
positivePegRadius = (derivation.pegRadiusArealized - derivation.halfPegClearance)
radiusArealized = complex(positivePegRadius, positivePegRadius)
copyShallow = derivation.elementNode.getCopyShallow()
start = Vector3(x, y, derivation.demiheight)
endZ = derivation.height
peg.addPegOutput(derivation.pegBevel, endZ, positives, radiusArealized, derivation.sides, start, derivation.topOverBottom)
| null | null | null | at x and y
| codeqa | def add Positive Peg derivation positives x y positive Peg Radius derivation peg Radius Arealized - derivation half Peg Clearance radius Arealized complex positive Peg Radius positive Peg Radius copy Shallow derivation element Node get Copy Shallow start Vector 3 x y derivation demiheight end Z derivation heightpeg add Peg Output derivation peg Bevel end Z positives radius Arealized derivation sides start derivation top Over Bottom
| null | null | null | null | Question:
When do positive cylinder add ?
Code:
def addPositivePeg(derivation, positives, x, y):
positivePegRadius = (derivation.pegRadiusArealized - derivation.halfPegClearance)
radiusArealized = complex(positivePegRadius, positivePegRadius)
copyShallow = derivation.elementNode.getCopyShallow()
start = Vector3(x, y, derivation.demiheight)
endZ = derivation.height
peg.addPegOutput(derivation.pegBevel, endZ, positives, radiusArealized, derivation.sides, start, derivation.topOverBottom)
|
null | null | null | What made on the network device ?
| def commit():
return __proxy__['napalm.call']('commit_config', **{})
| null | null | null | the configuration changes
| codeqa | def commit return proxy ['napalm call'] 'commit config' **{}
| null | null | null | null | Question:
What made on the network device ?
Code:
def commit():
return __proxy__['napalm.call']('commit_config', **{})
|
null | null | null | Where did the configuration changes make ?
| def commit():
return __proxy__['napalm.call']('commit_config', **{})
| null | null | null | on the network device
| codeqa | def commit return proxy ['napalm call'] 'commit config' **{}
| null | null | null | null | Question:
Where did the configuration changes make ?
Code:
def commit():
return __proxy__['napalm.call']('commit_config', **{})
|
null | null | null | Where does the code add a user ?
| def add_bucket_owner(bucket_name, user_email):
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
bucket.acl.reload()
bucket.acl.user(user_email).grant_owner()
bucket.acl.save()
print 'Added user {} as an owner on bucket {}.'.format(user_email, bucket_name)
| null | null | null | on the given bucket
| codeqa | def add bucket owner bucket name user email storage client storage Client bucket storage client bucket bucket name bucket acl reload bucket acl user user email grant owner bucket acl save print ' Addeduser{}asanowneronbucket{} ' format user email bucket name
| null | null | null | null | Question:
Where does the code add a user ?
Code:
def add_bucket_owner(bucket_name, user_email):
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
bucket.acl.reload()
bucket.acl.user(user_email).grant_owner()
bucket.acl.save()
print 'Added user {} as an owner on bucket {}.'.format(user_email, bucket_name)
|
null | null | null | What does the code get ?
| def _sig_key(key, date_stamp, regionName, serviceName):
kDate = _sign(('AWS4' + key).encode('utf-8'), date_stamp)
if regionName:
kRegion = _sign(kDate, regionName)
kService = _sign(kRegion, serviceName)
else:
kService = _sign(kDate, serviceName)
kSigning = _sign(kService, 'aws4_request')
return kSigning
| null | null | null | a signature key
| codeqa | def sig key key date stamp region Name service Name k Date sign 'AWS 4 ' + key encode 'utf- 8 ' date stamp if region Name k Region sign k Date region Name k Service sign k Region service Name else k Service sign k Date service Name k Signing sign k Service 'aws 4 request' return k Signing
| null | null | null | null | Question:
What does the code get ?
Code:
def _sig_key(key, date_stamp, regionName, serviceName):
kDate = _sign(('AWS4' + key).encode('utf-8'), date_stamp)
if regionName:
kRegion = _sign(kDate, regionName)
kService = _sign(kRegion, serviceName)
else:
kService = _sign(kDate, serviceName)
kSigning = _sign(kService, 'aws4_request')
return kSigning
|
null | null | null | Does the code take no for an answer ?
| def get_god_player():
try:
god_player = PlayerDB.objects.get(id=1)
except PlayerDB.DoesNotExist:
raise PlayerDB.DoesNotExist(ERROR_NO_SUPERUSER)
return god_player
| null | null | null | No
| codeqa | def get god player try god player Player DB objects get id 1 except Player DB Does Not Exist raise Player DB Does Not Exist ERROR NO SUPERUSER return god player
| null | null | null | null | Question:
Does the code take no for an answer ?
Code:
def get_god_player():
try:
god_player = PlayerDB.objects.get(id=1)
except PlayerDB.DoesNotExist:
raise PlayerDB.DoesNotExist(ERROR_NO_SUPERUSER)
return god_player
|
null | null | null | What does the code create ?
| def get_god_player():
try:
god_player = PlayerDB.objects.get(id=1)
except PlayerDB.DoesNotExist:
raise PlayerDB.DoesNotExist(ERROR_NO_SUPERUSER)
return god_player
| null | null | null | the god user
| codeqa | def get god player try god player Player DB objects get id 1 except Player DB Does Not Exist raise Player DB Does Not Exist ERROR NO SUPERUSER return god player
| null | null | null | null | Question:
What does the code create ?
Code:
def get_god_player():
try:
god_player = PlayerDB.objects.get(id=1)
except PlayerDB.DoesNotExist:
raise PlayerDB.DoesNotExist(ERROR_NO_SUPERUSER)
return god_player
|
null | null | null | What does the code produce ?
| def _make_complex_eigvecs(w, vin, dtype):
v = numpy.array(vin, dtype=dtype)
m = (w.imag > 0)
m[:(-1)] |= (w.imag[1:] < 0)
for i in flatnonzero(m):
v.imag[:, i] = vin[:, (i + 1)]
conj(v[:, i], v[:, (i + 1)])
return v
| null | null | null | complex - valued eigenvectors
| codeqa | def make complex eigvecs w vin dtype v numpy array vin dtype dtype m w imag > 0 m[ -1 ] w imag[ 1 ] < 0 for i in flatnonzero m v imag[ i] vin[ i + 1 ]conj v[ i] v[ i + 1 ] return v
| null | null | null | null | Question:
What does the code produce ?
Code:
def _make_complex_eigvecs(w, vin, dtype):
v = numpy.array(vin, dtype=dtype)
m = (w.imag > 0)
m[:(-1)] |= (w.imag[1:] < 0)
for i in flatnonzero(m):
v.imag[:, i] = vin[:, (i + 1)]
conj(v[:, i], v[:, (i + 1)])
return v
|
null | null | null | How did eigenvectors value ?
| def _make_complex_eigvecs(w, vin, dtype):
v = numpy.array(vin, dtype=dtype)
m = (w.imag > 0)
m[:(-1)] |= (w.imag[1:] < 0)
for i in flatnonzero(m):
v.imag[:, i] = vin[:, (i + 1)]
conj(v[:, i], v[:, (i + 1)])
return v
| null | null | null | complex
| codeqa | def make complex eigvecs w vin dtype v numpy array vin dtype dtype m w imag > 0 m[ -1 ] w imag[ 1 ] < 0 for i in flatnonzero m v imag[ i] vin[ i + 1 ]conj v[ i] v[ i + 1 ] return v
| null | null | null | null | Question:
How did eigenvectors value ?
Code:
def _make_complex_eigvecs(w, vin, dtype):
v = numpy.array(vin, dtype=dtype)
m = (w.imag > 0)
m[:(-1)] |= (w.imag[1:] < 0)
for i in flatnonzero(m):
v.imag[:, i] = vin[:, (i + 1)]
conj(v[:, i], v[:, (i + 1)])
return v
|
null | null | null | What does the code create ?
| def new_figure_manager(num, *args, **kwargs):
DEBUG_MSG(u'new_figure_manager()', 3, None)
backend_wx._create_wx_app()
FigureClass = kwargs.pop(u'FigureClass', Figure)
fig = FigureClass(*args, **kwargs)
return new_figure_manager_given_figure(num, fig)
| null | null | null | a new figure manager instance
| codeqa | def new figure manager num *args **kwargs DEBUG MSG u'new figure manager ' 3 None backend wx create wx app Figure Class kwargs pop u' Figure Class' Figure fig Figure Class *args **kwargs return new figure manager given figure num fig
| null | null | null | null | Question:
What does the code create ?
Code:
def new_figure_manager(num, *args, **kwargs):
DEBUG_MSG(u'new_figure_manager()', 3, None)
backend_wx._create_wx_app()
FigureClass = kwargs.pop(u'FigureClass', Figure)
fig = FigureClass(*args, **kwargs)
return new_figure_manager_given_figure(num, fig)
|
null | null | null | What does the code generate ?
| def _calculate_photo_filename(instance, filename):
return os.path.join(settings.USER_AVATAR_DIR, (str(uuid.uuid4()) + '.jpg'))
| null | null | null | a unique filename for uploaded photo
| codeqa | def calculate photo filename instance filename return os path join settings USER AVATAR DIR str uuid uuid 4 + ' jpg'
| null | null | null | null | Question:
What does the code generate ?
Code:
def _calculate_photo_filename(instance, filename):
return os.path.join(settings.USER_AVATAR_DIR, (str(uuid.uuid4()) + '.jpg'))
|
null | null | null | What does the code capitalize ?
| @register(u'capitalize-word')
def capitalize_word(event):
buff = event.current_buffer
for i in range(event.arg):
pos = buff.document.find_next_word_ending()
words = buff.document.text_after_cursor[:pos]
buff.insert_text(words.title(), overwrite=True)
| null | null | null | the current word
| codeqa | @register u'capitalize-word' def capitalize word event buff event current bufferfor i in range event arg pos buff document find next word ending words buff document text after cursor[ pos]buff insert text words title overwrite True
| null | null | null | null | Question:
What does the code capitalize ?
Code:
@register(u'capitalize-word')
def capitalize_word(event):
buff = event.current_buffer
for i in range(event.arg):
pos = buff.document.find_next_word_ending()
words = buff.document.text_after_cursor[:pos]
buff.insert_text(words.title(), overwrite=True)
|
null | null | null | How do number vary ?
| def VaryRate(start, end, saturate_epochs, epoch):
if (saturate_epochs <= 0):
return start
step = ((start - end) / (saturate_epochs - 1))
if (epoch < saturate_epochs):
return (start - (step * epoch))
else:
return end
| null | null | null | linearly
| codeqa | def Vary Rate start end saturate epochs epoch if saturate epochs < 0 return startstep start - end / saturate epochs - 1 if epoch < saturate epochs return start - step * epoch else return end
| null | null | null | null | Question:
How do number vary ?
Code:
def VaryRate(start, end, saturate_epochs, epoch):
if (saturate_epochs <= 0):
return start
step = ((start - end) / (saturate_epochs - 1))
if (epoch < saturate_epochs):
return (start - (step * epoch))
else:
return end
|
null | null | null | What does the code get ?
| def _random_getnode():
import random
return (random.randrange(0, (1 << 48)) | 1099511627776)
| null | null | null | a random node i d
| codeqa | def random getnode import randomreturn random randrange 0 1 << 48 1099511627776
| null | null | null | null | Question:
What does the code get ?
Code:
def _random_getnode():
import random
return (random.randrange(0, (1 << 48)) | 1099511627776)
|
null | null | null | What does the code do ?
| def get(url, api_key=None):
url = make_url(url, api_key=api_key, args=None)
try:
return json.loads(urllib2.urlopen(url).read())
except ValueError:
sys.exit('URL did not return JSON data')
| null | null | null | the get
| codeqa | def get url api key None url make url url api key api key args None try return json loads urllib 2 urlopen url read except Value Error sys exit 'UR Ldidnotreturn JSO Ndata'
| null | null | null | null | Question:
What does the code do ?
Code:
def get(url, api_key=None):
url = make_url(url, api_key=api_key, args=None)
try:
return json.loads(urllib2.urlopen(url).read())
except ValueError:
sys.exit('URL did not return JSON data')
|
null | null | null | What will change the state of the unit ?
| @pytest.mark.django_db
def test_accept_suggestion_changes_state(issue_2401_po, system):
suggestions = review.get(Suggestion)()
unit = issue_2401_po.units[0]
assert (unit.state == UNTRANSLATED)
(suggestion, created_) = suggestions.add(unit, 'foo')
assert (unit.state == UNTRANSLATED)
review.get(Suggestion)([suggestion], system).accept()
assert (unit.state == TRANSLATED)
unit = issue_2401_po.units[1]
assert (unit.state == TRANSLATED)
(suggestion, created_) = suggestions.add(unit, 'bar')
assert (unit.state == TRANSLATED)
review.get(Suggestion)([suggestion], system).accept()
assert (unit.state == TRANSLATED)
unit = issue_2401_po.units[2]
assert (unit.state == FUZZY)
(suggestion, created_) = suggestions.add(unit, 'baz')
assert (unit.state == FUZZY)
review.get(Suggestion)([suggestion], system).accept()
assert (unit.state == TRANSLATED)
| null | null | null | accepting a suggestion
| codeqa | @pytest mark django dbdef test accept suggestion changes state issue 2401 po system suggestions review get Suggestion unit issue 2401 po units[ 0 ]assert unit state UNTRANSLATED suggestion created suggestions add unit 'foo' assert unit state UNTRANSLATED review get Suggestion [suggestion] system accept assert unit state TRANSLATED unit issue 2401 po units[ 1 ]assert unit state TRANSLATED suggestion created suggestions add unit 'bar' assert unit state TRANSLATED review get Suggestion [suggestion] system accept assert unit state TRANSLATED unit issue 2401 po units[ 2 ]assert unit state FUZZY suggestion created suggestions add unit 'baz' assert unit state FUZZY review get Suggestion [suggestion] system accept assert unit state TRANSLATED
| null | null | null | null | Question:
What will change the state of the unit ?
Code:
@pytest.mark.django_db
def test_accept_suggestion_changes_state(issue_2401_po, system):
suggestions = review.get(Suggestion)()
unit = issue_2401_po.units[0]
assert (unit.state == UNTRANSLATED)
(suggestion, created_) = suggestions.add(unit, 'foo')
assert (unit.state == UNTRANSLATED)
review.get(Suggestion)([suggestion], system).accept()
assert (unit.state == TRANSLATED)
unit = issue_2401_po.units[1]
assert (unit.state == TRANSLATED)
(suggestion, created_) = suggestions.add(unit, 'bar')
assert (unit.state == TRANSLATED)
review.get(Suggestion)([suggestion], system).accept()
assert (unit.state == TRANSLATED)
unit = issue_2401_po.units[2]
assert (unit.state == FUZZY)
(suggestion, created_) = suggestions.add(unit, 'baz')
assert (unit.state == FUZZY)
review.get(Suggestion)([suggestion], system).accept()
assert (unit.state == TRANSLATED)
|
null | null | null | What does the code climb ?
| def grab_tree(api_handle, item):
settings = api_handle.settings()
results = [item]
parent = item.get_parent()
while (parent is not None):
results.append(parent)
parent = parent.get_parent()
results.append(settings)
return results
| null | null | null | the tree
| codeqa | def grab tree api handle item settings api handle settings results [item]parent item get parent while parent is not None results append parent parent parent get parent results append settings return results
| null | null | null | null | Question:
What does the code climb ?
Code:
def grab_tree(api_handle, item):
settings = api_handle.settings()
results = [item]
parent = item.get_parent()
while (parent is not None):
results.append(parent)
parent = parent.get_parent()
results.append(settings)
return results
|
null | null | null | What does the code get ?
| def grab_tree(api_handle, item):
settings = api_handle.settings()
results = [item]
parent = item.get_parent()
while (parent is not None):
results.append(parent)
parent = parent.get_parent()
results.append(settings)
return results
| null | null | null | every node
| codeqa | def grab tree api handle item settings api handle settings results [item]parent item get parent while parent is not None results append parent parent parent get parent results append settings return results
| null | null | null | null | Question:
What does the code get ?
Code:
def grab_tree(api_handle, item):
settings = api_handle.settings()
results = [item]
parent = item.get_parent()
while (parent is not None):
results.append(parent)
parent = parent.get_parent()
results.append(settings)
return results
|
null | null | null | What does the code get ?
| @blueprint.route('/jobs/<job_id>/table_data.json', methods=['GET'])
def job_table_data(job_id):
job = scheduler.get_job(job_id)
if (job is None):
raise werkzeug.exceptions.NotFound('Job not found')
model_output_fields = set()
return flask.jsonify({'job': json_dict(job, model_output_fields)})
| null | null | null | the job data for the front page tables
| codeqa | @blueprint route '/jobs/<job id>/table data json' methods ['GET'] def job table data job id job scheduler get job job id if job is None raise werkzeug exceptions Not Found ' Jobnotfound' model output fields set return flask jsonify {'job' json dict job model output fields }
| null | null | null | null | Question:
What does the code get ?
Code:
@blueprint.route('/jobs/<job_id>/table_data.json', methods=['GET'])
def job_table_data(job_id):
job = scheduler.get_job(job_id)
if (job is None):
raise werkzeug.exceptions.NotFound('Job not found')
model_output_fields = set()
return flask.jsonify({'job': json_dict(job, model_output_fields)})
|
null | null | null | What does the code setup ?
| def setup_platform(hass, config, add_devices, discovery_info=None):
add_devices([DemoCamera('Demo camera')])
| null | null | null | the demo camera platform
| codeqa | def setup platform hass config add devices discovery info None add devices [ Demo Camera ' Democamera' ]
| null | null | null | null | Question:
What does the code setup ?
Code:
def setup_platform(hass, config, add_devices, discovery_info=None):
add_devices([DemoCamera('Demo camera')])
|
null | null | null | What does the code update ?
| def update_featured_activity_references(featured_activity_references):
for activity_reference in featured_activity_references:
activity_reference.validate()
activity_hashes = [reference.get_hash() for reference in featured_activity_references]
if (len(activity_hashes) != len(set(activity_hashes))):
raise Exception('The activity reference list should not have duplicates.')
featured_model_instance = activity_models.ActivityReferencesModel.get_or_create(activity_models.ACTIVITY_REFERENCE_LIST_FEATURED)
featured_model_instance.activity_references = [reference.to_dict() for reference in featured_activity_references]
featured_model_instance.put()
| null | null | null | the current list of featured activity references
| codeqa | def update featured activity references featured activity references for activity reference in featured activity references activity reference validate activity hashes [reference get hash for reference in featured activity references]if len activity hashes len set activity hashes raise Exception ' Theactivityreferencelistshouldnothaveduplicates ' featured model instance activity models Activity References Model get or create activity models ACTIVITY REFERENCE LIST FEATURED featured model instance activity references [reference to dict for reference in featured activity references]featured model instance put
| null | null | null | null | Question:
What does the code update ?
Code:
def update_featured_activity_references(featured_activity_references):
for activity_reference in featured_activity_references:
activity_reference.validate()
activity_hashes = [reference.get_hash() for reference in featured_activity_references]
if (len(activity_hashes) != len(set(activity_hashes))):
raise Exception('The activity reference list should not have duplicates.')
featured_model_instance = activity_models.ActivityReferencesModel.get_or_create(activity_models.ACTIVITY_REFERENCE_LIST_FEATURED)
featured_model_instance.activity_references = [reference.to_dict() for reference in featured_activity_references]
featured_model_instance.put()
|
null | null | null | What does the code generate ?
| def make_low_rank_matrix(n_samples=100, n_features=100, effective_rank=10, tail_strength=0.5, random_state=None):
generator = check_random_state(random_state)
n = min(n_samples, n_features)
(u, _) = linalg.qr(generator.randn(n_samples, n), mode='economic')
(v, _) = linalg.qr(generator.randn(n_features, n), mode='economic')
singular_ind = np.arange(n, dtype=np.float64)
low_rank = ((1 - tail_strength) * np.exp(((-1.0) * ((singular_ind / effective_rank) ** 2))))
tail = (tail_strength * np.exp((((-0.1) * singular_ind) / effective_rank)))
s = (np.identity(n) * (low_rank + tail))
return np.dot(np.dot(u, s), v.T)
| null | null | null | a mostly low rank matrix with bell - shaped singular values
| codeqa | def make low rank matrix n samples 100 n features 100 effective rank 10 tail strength 0 5 random state None generator check random state random state n min n samples n features u linalg qr generator randn n samples n mode 'economic' v linalg qr generator randn n features n mode 'economic' singular ind np arange n dtype np float 64 low rank 1 - tail strength * np exp -1 0 * singular ind / effective rank ** 2 tail tail strength * np exp -0 1 * singular ind / effective rank s np identity n * low rank + tail return np dot np dot u s v T
| null | null | null | null | Question:
What does the code generate ?
Code:
def make_low_rank_matrix(n_samples=100, n_features=100, effective_rank=10, tail_strength=0.5, random_state=None):
generator = check_random_state(random_state)
n = min(n_samples, n_features)
(u, _) = linalg.qr(generator.randn(n_samples, n), mode='economic')
(v, _) = linalg.qr(generator.randn(n_features, n), mode='economic')
singular_ind = np.arange(n, dtype=np.float64)
low_rank = ((1 - tail_strength) * np.exp(((-1.0) * ((singular_ind / effective_rank) ** 2))))
tail = (tail_strength * np.exp((((-0.1) * singular_ind) / effective_rank)))
s = (np.identity(n) * (low_rank + tail))
return np.dot(np.dot(u, s), v.T)
|
null | null | null | What does the low rank part of the singular values profile be ?
| def make_low_rank_matrix(n_samples=100, n_features=100, effective_rank=10, tail_strength=0.5, random_state=None):
generator = check_random_state(random_state)
n = min(n_samples, n_features)
(u, _) = linalg.qr(generator.randn(n_samples, n), mode='economic')
(v, _) = linalg.qr(generator.randn(n_features, n), mode='economic')
singular_ind = np.arange(n, dtype=np.float64)
low_rank = ((1 - tail_strength) * np.exp(((-1.0) * ((singular_ind / effective_rank) ** 2))))
tail = (tail_strength * np.exp((((-0.1) * singular_ind) / effective_rank)))
s = (np.identity(n) * (low_rank + tail))
return np.dot(np.dot(u, s), v.T)
| null | null | null | * exp(-1
| codeqa | def make low rank matrix n samples 100 n features 100 effective rank 10 tail strength 0 5 random state None generator check random state random state n min n samples n features u linalg qr generator randn n samples n mode 'economic' v linalg qr generator randn n features n mode 'economic' singular ind np arange n dtype np float 64 low rank 1 - tail strength * np exp -1 0 * singular ind / effective rank ** 2 tail tail strength * np exp -0 1 * singular ind / effective rank s np identity n * low rank + tail return np dot np dot u s v T
| null | null | null | null | Question:
What does the low rank part of the singular values profile be ?
Code:
def make_low_rank_matrix(n_samples=100, n_features=100, effective_rank=10, tail_strength=0.5, random_state=None):
generator = check_random_state(random_state)
n = min(n_samples, n_features)
(u, _) = linalg.qr(generator.randn(n_samples, n), mode='economic')
(v, _) = linalg.qr(generator.randn(n_features, n), mode='economic')
singular_ind = np.arange(n, dtype=np.float64)
low_rank = ((1 - tail_strength) * np.exp(((-1.0) * ((singular_ind / effective_rank) ** 2))))
tail = (tail_strength * np.exp((((-0.1) * singular_ind) / effective_rank)))
s = (np.identity(n) * (low_rank + tail))
return np.dot(np.dot(u, s), v.T)
|
null | null | null | What extracts from all paragraphs that have been classified as containing options ?
| def extract(manpage):
for (i, p) in enumerate(manpage.paragraphs):
if p.is_option:
(s, l) = extract_option(p.cleantext())
if (s or l):
expectsarg = any((x.expectsarg for x in (s + l)))
s = [x.flag for x in s]
l = [x.flag for x in l]
manpage.paragraphs[i] = store.option(p, s, l, expectsarg)
else:
logger.error('no options could be extracted from paragraph %r', p)
| null | null | null | options
| codeqa | def extract manpage for i p in enumerate manpage paragraphs if p is option s l extract option p cleantext if s or l expectsarg any x expectsarg for x in s + l s [x flag for x in s]l [x flag for x in l]manpage paragraphs[i] store option p s l expectsarg else logger error 'nooptionscouldbeextractedfromparagraph%r' p
| null | null | null | null | Question:
What extracts from all paragraphs that have been classified as containing options ?
Code:
def extract(manpage):
for (i, p) in enumerate(manpage.paragraphs):
if p.is_option:
(s, l) = extract_option(p.cleantext())
if (s or l):
expectsarg = any((x.expectsarg for x in (s + l)))
s = [x.flag for x in s]
l = [x.flag for x in l]
manpage.paragraphs[i] = store.option(p, s, l, expectsarg)
else:
logger.error('no options could be extracted from paragraph %r', p)
|
null | null | null | What do options extract ?
| def extract(manpage):
for (i, p) in enumerate(manpage.paragraphs):
if p.is_option:
(s, l) = extract_option(p.cleantext())
if (s or l):
expectsarg = any((x.expectsarg for x in (s + l)))
s = [x.flag for x in s]
l = [x.flag for x in l]
manpage.paragraphs[i] = store.option(p, s, l, expectsarg)
else:
logger.error('no options could be extracted from paragraph %r', p)
| null | null | null | from all paragraphs that have been classified as containing options
| codeqa | def extract manpage for i p in enumerate manpage paragraphs if p is option s l extract option p cleantext if s or l expectsarg any x expectsarg for x in s + l s [x flag for x in s]l [x flag for x in l]manpage paragraphs[i] store option p s l expectsarg else logger error 'nooptionscouldbeextractedfromparagraph%r' p
| null | null | null | null | Question:
What do options extract ?
Code:
def extract(manpage):
for (i, p) in enumerate(manpage.paragraphs):
if p.is_option:
(s, l) = extract_option(p.cleantext())
if (s or l):
expectsarg = any((x.expectsarg for x in (s + l)))
s = [x.flag for x in s]
l = [x.flag for x in l]
manpage.paragraphs[i] = store.option(p, s, l, expectsarg)
else:
logger.error('no options could be extracted from paragraph %r', p)
|
null | null | null | When will process execute only ?
| def lowest(logging=logging):
return _set_priority('Lowest', logging=logging)
| null | null | null | when system is idle
| codeqa | def lowest logging logging return set priority ' Lowest' logging logging
| null | null | null | null | Question:
When will process execute only ?
Code:
def lowest(logging=logging):
return _set_priority('Lowest', logging=logging)
|
null | null | null | When do those of appear ?
| def padded_key(key, symbols, filter=True):
syms = list(uniq(symbols))
if (len(syms) != len(symbols)):
extra = ''.join(sorted(set([i for i in symbols if (symbols.count(i) > 1)])))
raise ValueError(('duplicate characters in symbols: %s' % extra))
extra = (set(key) - set(syms))
if extra:
raise ValueError(('characters in key but not symbols: %s' % ''.join(sorted(extra))))
key0 = ''.join(list(uniq(key)))
return (key0 + ''.join([i for i in syms if (i not in key0)]))
| null | null | null | first
| codeqa | def padded key key symbols filter True syms list uniq symbols if len syms len symbols extra '' join sorted set [i for i in symbols if symbols count i > 1 ] raise Value Error 'duplicatecharactersinsymbols %s' % extra extra set key - set syms if extra raise Value Error 'charactersinkeybutnotsymbols %s' % '' join sorted extra key 0 '' join list uniq key return key 0 + '' join [i for i in syms if i not in key 0 ]
| null | null | null | null | Question:
When do those of appear ?
Code:
def padded_key(key, symbols, filter=True):
syms = list(uniq(symbols))
if (len(syms) != len(symbols)):
extra = ''.join(sorted(set([i for i in symbols if (symbols.count(i) > 1)])))
raise ValueError(('duplicate characters in symbols: %s' % extra))
extra = (set(key) - set(syms))
if extra:
raise ValueError(('characters in key but not symbols: %s' % ''.join(sorted(extra))))
key0 = ''.join(list(uniq(key)))
return (key0 + ''.join([i for i in syms if (i not in key0)]))
|
null | null | null | What does the code prompt for the given variable ?
| def read_user_variable(var_name, default_value):
return click.prompt(var_name, default=default_value)
| null | null | null | the user
| codeqa | def read user variable var name default value return click prompt var name default default value
| null | null | null | null | Question:
What does the code prompt for the given variable ?
Code:
def read_user_variable(var_name, default_value):
return click.prompt(var_name, default=default_value)
|
null | null | null | What does the code return ?
| def read_user_variable(var_name, default_value):
return click.prompt(var_name, default=default_value)
| null | null | null | the entered value or the given default
| codeqa | def read user variable var name default value return click prompt var name default default value
| null | null | null | null | Question:
What does the code return ?
Code:
def read_user_variable(var_name, default_value):
return click.prompt(var_name, default=default_value)
|
null | null | null | What does the code ensure ?
| def test_unique_prefix_completion():
superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')
testRegex = ''
superConsole.SendKeys('print z{TAB}{ENTER}')
testRegex += 'zoltar'
superConsole.SendKeys('print yo{TAB}{ENTER}')
testRegex += 'yorick'
superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')
verifyResults(getTestOutput()[0], testRegex)
AreEqual(removePrompts(getTestOutput()[1]), [])
| null | null | null | that an attribute with a prefix unique to the dictionary is properly completed
| codeqa | def test unique prefix completion super Console Send Keys 'output Redirect Start{ }{ }{ENTER}' test Regex ''super Console Send Keys 'printz{TAB}{ENTER}' test Regex + 'zoltar'super Console Send Keys 'printyo{TAB}{ENTER}' test Regex + 'yorick'super Console Send Keys 'output Redirect Stop{ }{ }{ENTER}' verify Results get Test Output [0 ] test Regex Are Equal remove Prompts get Test Output [1 ] []
| null | null | null | null | Question:
What does the code ensure ?
Code:
def test_unique_prefix_completion():
superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')
testRegex = ''
superConsole.SendKeys('print z{TAB}{ENTER}')
testRegex += 'zoltar'
superConsole.SendKeys('print yo{TAB}{ENTER}')
testRegex += 'yorick'
superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')
verifyResults(getTestOutput()[0], testRegex)
AreEqual(removePrompts(getTestOutput()[1]), [])
|
null | null | null | How is an attribute with a prefix unique to the dictionary completed ?
| def test_unique_prefix_completion():
superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')
testRegex = ''
superConsole.SendKeys('print z{TAB}{ENTER}')
testRegex += 'zoltar'
superConsole.SendKeys('print yo{TAB}{ENTER}')
testRegex += 'yorick'
superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')
verifyResults(getTestOutput()[0], testRegex)
AreEqual(removePrompts(getTestOutput()[1]), [])
| null | null | null | properly
| codeqa | def test unique prefix completion super Console Send Keys 'output Redirect Start{ }{ }{ENTER}' test Regex ''super Console Send Keys 'printz{TAB}{ENTER}' test Regex + 'zoltar'super Console Send Keys 'printyo{TAB}{ENTER}' test Regex + 'yorick'super Console Send Keys 'output Redirect Stop{ }{ }{ENTER}' verify Results get Test Output [0 ] test Regex Are Equal remove Prompts get Test Output [1 ] []
| null | null | null | null | Question:
How is an attribute with a prefix unique to the dictionary completed ?
Code:
def test_unique_prefix_completion():
superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')
testRegex = ''
superConsole.SendKeys('print z{TAB}{ENTER}')
testRegex += 'zoltar'
superConsole.SendKeys('print yo{TAB}{ENTER}')
testRegex += 'yorick'
superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')
verifyResults(getTestOutput()[0], testRegex)
AreEqual(removePrompts(getTestOutput()[1]), [])
|
null | null | null | Where did all folders locate ?
| def list_folders(location='\\'):
pythoncom.CoInitialize()
task_service = win32com.client.Dispatch('Schedule.Service')
task_service.Connect()
task_folder = task_service.GetFolder(location)
folders = task_folder.GetFolders(0)
ret = []
for folder in folders:
ret.append(folder.Name)
return ret
| null | null | null | in a specific location in the task scheduler
| codeqa | def list folders location '\\' pythoncom Co Initialize task service win 32 com client Dispatch ' Schedule Service' task service Connect task folder task service Get Folder location folders task folder Get Folders 0 ret []for folder in folders ret append folder Name return ret
| null | null | null | null | Question:
Where did all folders locate ?
Code:
def list_folders(location='\\'):
pythoncom.CoInitialize()
task_service = win32com.client.Dispatch('Schedule.Service')
task_service.Connect()
task_folder = task_service.GetFolder(location)
folders = task_folder.GetFolders(0)
ret = []
for folder in folders:
ret.append(folder.Name)
return ret
|
null | null | null | What located in a specific location in the task scheduler ?
| def list_folders(location='\\'):
pythoncom.CoInitialize()
task_service = win32com.client.Dispatch('Schedule.Service')
task_service.Connect()
task_folder = task_service.GetFolder(location)
folders = task_folder.GetFolders(0)
ret = []
for folder in folders:
ret.append(folder.Name)
return ret
| null | null | null | all folders
| codeqa | def list folders location '\\' pythoncom Co Initialize task service win 32 com client Dispatch ' Schedule Service' task service Connect task folder task service Get Folder location folders task folder Get Folders 0 ret []for folder in folders ret append folder Name return ret
| null | null | null | null | Question:
What located in a specific location in the task scheduler ?
Code:
def list_folders(location='\\'):
pythoncom.CoInitialize()
task_service = win32com.client.Dispatch('Schedule.Service')
task_service.Connect()
task_folder = task_service.GetFolder(location)
folders = task_folder.GetFolders(0)
ret = []
for folder in folders:
ret.append(folder.Name)
return ret
|
null | null | null | What is returning only the value of interest ?
| def sysctl(cmdline):
result = sh(('sysctl ' + cmdline))
if FREEBSD:
result = result[(result.find(': ') + 2):]
elif (OPENBSD or NETBSD):
result = result[(result.find('=') + 1):]
try:
return int(result)
except ValueError:
return result
| null | null | null | the result
| codeqa | def sysctl cmdline result sh 'sysctl' + cmdline if FREEBSD result result[ result find ' ' + 2 ]elif OPENBSD or NETBSD result result[ result find ' ' + 1 ]try return int result except Value Error return result
| null | null | null | null | Question:
What is returning only the value of interest ?
Code:
def sysctl(cmdline):
result = sh(('sysctl ' + cmdline))
if FREEBSD:
result = result[(result.find(': ') + 2):]
elif (OPENBSD or NETBSD):
result = result[(result.find('=') + 1):]
try:
return int(result)
except ValueError:
return result
|
null | null | null | What have you installed ?
| def build_ssl_validation_error(hostname, port, paths, exc=None):
msg = ['Failed to validate the SSL certificate for %s:%s. Make sure your managed systems have a valid CA certificate installed.']
if (not HAS_SSLCONTEXT):
msg.append('If the website serving the url uses SNI you need python >= 2.7.9 on your managed machine')
if (not HAS_URLLIB3_SNI_SUPPORT):
msg.append('or you can install the `urllib3`, `pyopenssl`, `ndg-httpsclient`, and `pyasn1` python modules')
msg.append('to perform SNI verification in python >= 2.6.')
msg.append('You can use validate_certs=False if you do not need to confirm the servers identity but this is unsafe and not recommended. Paths checked for this platform: %s.')
if exc:
msg.append(('The exception msg was: %s.' % to_native(exc)))
raise SSLValidationError((' '.join(msg) % (hostname, port, ', '.join(paths))))
| null | null | null | what support
| codeqa | def build ssl validation error hostname port paths exc None msg [' Failedtovalidatethe SS Lcertificatefor%s %s Makesureyourmanagedsystemshaveavalid C Acertificateinstalled ']if not HAS SSLCONTEXT msg append ' Ifthewebsiteservingtheurluses SN Iyouneedpython> 2 7 9onyourmanagedmachine' if not HAS URLLIB 3 SNI SUPPORT msg append 'oryoucaninstallthe`urllib 3 ` `pyopenssl` `ndg-httpsclient` and`pyasn 1 `pythonmodules' msg append 'toperform SN Iverificationinpython> 2 6 ' msg append ' Youcanusevalidate certs Falseifyoudonotneedtoconfirmtheserversidentitybutthisisunsafeandnotrecommended Pathscheckedforthisplatform %s ' if exc msg append ' Theexceptionmsgwas %s ' % to native exc raise SSL Validation Error '' join msg % hostname port ' ' join paths
| null | null | null | null | Question:
What have you installed ?
Code:
def build_ssl_validation_error(hostname, port, paths, exc=None):
msg = ['Failed to validate the SSL certificate for %s:%s. Make sure your managed systems have a valid CA certificate installed.']
if (not HAS_SSLCONTEXT):
msg.append('If the website serving the url uses SNI you need python >= 2.7.9 on your managed machine')
if (not HAS_URLLIB3_SNI_SUPPORT):
msg.append('or you can install the `urllib3`, `pyopenssl`, `ndg-httpsclient`, and `pyasn1` python modules')
msg.append('to perform SNI verification in python >= 2.6.')
msg.append('You can use validate_certs=False if you do not need to confirm the servers identity but this is unsafe and not recommended. Paths checked for this platform: %s.')
if exc:
msg.append(('The exception msg was: %s.' % to_native(exc)))
raise SSLValidationError((' '.join(msg) % (hostname, port, ', '.join(paths))))
|
null | null | null | What does the code invalidate ?
| def invalidate_module_pricing_cache(driver_type, driver_name):
if (driver_name in PRICING_DATA[driver_type]):
del PRICING_DATA[driver_type][driver_name]
| null | null | null | the cache for the specified driver
| codeqa | def invalidate module pricing cache driver type driver name if driver name in PRICING DATA[driver type] del PRICING DATA[driver type][driver name]
| null | null | null | null | Question:
What does the code invalidate ?
Code:
def invalidate_module_pricing_cache(driver_type, driver_name):
if (driver_name in PRICING_DATA[driver_type]):
del PRICING_DATA[driver_type][driver_name]
|
null | null | null | What did the code put to the state ?
| def vb_machinestate_to_str(machinestate):
return vb_machinestate_to_tuple(machinestate)[0]
| null | null | null | a name
| codeqa | def vb machinestate to str machinestate return vb machinestate to tuple machinestate [0 ]
| null | null | null | null | Question:
What did the code put to the state ?
Code:
def vb_machinestate_to_str(machinestate):
return vb_machinestate_to_tuple(machinestate)[0]
|
null | null | null | What does the code add to a given entry body ?
| def _create_entry(entry_body):
updated_str = datetime.utcnow().isoformat()
if (datetime.utcnow().utcoffset() is None):
updated_str += '+00:00'
entry_start = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>\n<entry xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom" >\n<title /><updated>{updated}</updated><author><name /></author><id />\n<content type="application/xml">\n {body}</content></entry>'
return entry_start.format(updated=updated_str, body=entry_body)
| null | null | null | common part of entry
| codeqa | def create entry entry body updated str datetime utcnow isoformat if datetime utcnow utcoffset is None updated str + '+ 00 00 'entry start '<?xmlversion "1 0"encoding "utf- 8 "standalone "yes"?>\n<entryxmlns d "http //schemas microsoft com/ado/ 2007 / 08 /dataservices"xmlns m "http //schemas microsoft com/ado/ 2007 / 08 /dataservices/metadata"xmlns "http //www w3 org/ 2005 / Atom">\n<title/><updated>{updated}</updated><author><name/></author><id/>\n<contenttype "application/xml">\n{body}</content></entry>'return entry start format updated updated str body entry body
| null | null | null | null | Question:
What does the code add to a given entry body ?
Code:
def _create_entry(entry_body):
updated_str = datetime.utcnow().isoformat()
if (datetime.utcnow().utcoffset() is None):
updated_str += '+00:00'
entry_start = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>\n<entry xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom" >\n<title /><updated>{updated}</updated><author><name /></author><id />\n<content type="application/xml">\n {body}</content></entry>'
return entry_start.format(updated=updated_str, body=entry_body)
|
null | null | null | What does the code create ?
| def new(key, *args, **kwargs):
return ARC4Cipher(key, *args, **kwargs)
| null | null | null | a new arc4 cipher
| codeqa | def new key *args **kwargs return ARC 4 Cipher key *args **kwargs
| null | null | null | null | Question:
What does the code create ?
Code:
def new(key, *args, **kwargs):
return ARC4Cipher(key, *args, **kwargs)
|
null | null | null | What does the code get ?
| def getMin(first, second):
return min(first, second)
| null | null | null | the min
| codeqa | def get Min first second return min first second
| null | null | null | null | Question:
What does the code get ?
Code:
def getMin(first, second):
return min(first, second)
|
null | null | null | What does the code generate ?
| def create_sitemap(app, exception):
if ((not app.config['html_theme_options'].get('base_url', '')) or (exception is not None) or (not app.sitemap_links)):
return
filename = (app.outdir + '/sitemap.xml')
print ('Generating sitemap.xml in %s' % filename)
root = ET.Element('urlset')
root.set('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9')
for link in app.sitemap_links:
url = ET.SubElement(root, 'url')
ET.SubElement(url, 'loc').text = link
ET.ElementTree(root).write(filename)
| null | null | null | the sitemap
| codeqa | def create sitemap app exception if not app config['html theme options'] get 'base url' '' or exception is not None or not app sitemap links returnfilename app outdir + '/sitemap xml' print ' Generatingsitemap xmlin%s' % filename root ET Element 'urlset' root set 'xmlns' 'http //www sitemaps org/schemas/sitemap/ 0 9' for link in app sitemap links url ET Sub Element root 'url' ET Sub Element url 'loc' text link ET Element Tree root write filename
| null | null | null | null | Question:
What does the code generate ?
Code:
def create_sitemap(app, exception):
if ((not app.config['html_theme_options'].get('base_url', '')) or (exception is not None) or (not app.sitemap_links)):
return
filename = (app.outdir + '/sitemap.xml')
print ('Generating sitemap.xml in %s' % filename)
root = ET.Element('urlset')
root.set('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9')
for link in app.sitemap_links:
url = ET.SubElement(root, 'url')
ET.SubElement(url, 'loc').text = link
ET.ElementTree(root).write(filename)
|
null | null | null | How are the sections returned to return the list of sections for ?
| def survey_getAllSectionsForSeries(series_id):
table = current.s3db.survey_series
row = current.db((table.id == series_id)).select(table.template_id, limitby=(0, 1)).first()
return survey_getAllSectionsForTemplate(row.template_id)
| null | null | null | in the order of their position in the template
| codeqa | def survey get All Sections For Series series id table current s3 db survey seriesrow current db table id series id select table template id limitby 0 1 first return survey get All Sections For Template row template id
| null | null | null | null | Question:
How are the sections returned to return the list of sections for ?
Code:
def survey_getAllSectionsForSeries(series_id):
table = current.s3db.survey_series
row = current.db((table.id == series_id)).select(table.template_id, limitby=(0, 1)).first()
return survey_getAllSectionsForTemplate(row.template_id)
|
null | null | null | How does the code retrieve a user ?
| def get_user(keystone, name):
users = [x for x in keystone.users.list() if (x.name == name)]
count = len(users)
if (count == 0):
raise KeyError(('No keystone users with name %s' % name))
elif (count > 1):
raise ValueError(('%d users with name %s' % (count, name)))
else:
return users[0]
| null | null | null | by name
| codeqa | def get user keystone name users [x for x in keystone users list if x name name ]count len users if count 0 raise Key Error ' Nokeystoneuserswithname%s' % name elif count > 1 raise Value Error '%duserswithname%s' % count name else return users[ 0 ]
| null | null | null | null | Question:
How does the code retrieve a user ?
Code:
def get_user(keystone, name):
users = [x for x in keystone.users.list() if (x.name == name)]
count = len(users)
if (count == 0):
raise KeyError(('No keystone users with name %s' % name))
elif (count > 1):
raise ValueError(('%d users with name %s' % (count, name)))
else:
return users[0]
|
null | null | null | What does the code retrieve by name ?
| def get_user(keystone, name):
users = [x for x in keystone.users.list() if (x.name == name)]
count = len(users)
if (count == 0):
raise KeyError(('No keystone users with name %s' % name))
elif (count > 1):
raise ValueError(('%d users with name %s' % (count, name)))
else:
return users[0]
| null | null | null | a user
| codeqa | def get user keystone name users [x for x in keystone users list if x name name ]count len users if count 0 raise Key Error ' Nokeystoneuserswithname%s' % name elif count > 1 raise Value Error '%duserswithname%s' % count name else return users[ 0 ]
| null | null | null | null | Question:
What does the code retrieve by name ?
Code:
def get_user(keystone, name):
users = [x for x in keystone.users.list() if (x.name == name)]
count = len(users)
if (count == 0):
raise KeyError(('No keystone users with name %s' % name))
elif (count > 1):
raise ValueError(('%d users with name %s' % (count, name)))
else:
return users[0]
|
null | null | null | What does the code validate ?
| def get_scanner(hass, config):
scanner = ActiontecDeviceScanner(config[DOMAIN])
return (scanner if scanner.success_init else None)
| null | null | null | the configuration
| codeqa | def get scanner hass config scanner Actiontec Device Scanner config[DOMAIN] return scanner if scanner success init else None
| null | null | null | null | Question:
What does the code validate ?
Code:
def get_scanner(hass, config):
scanner = ActiontecDeviceScanner(config[DOMAIN])
return (scanner if scanner.success_init else None)
|
null | null | null | In which direction did some cruft throw to test column positioning ?
| def test_read_twoline_normal():
table = '\n Col1 Col2\n ---- ---------\n 1.2xx"hello"\n 2.4 \'s worlds\n'
dat = ascii.read(table, Reader=ascii.FixedWidthTwoLine)
assert_equal(dat.dtype.names, ('Col1', 'Col2'))
assert_almost_equal(dat[1][0], 2.4)
assert_equal(dat[0][1], '"hello"')
assert_equal(dat[1][1], "'s worlds")
| null | null | null | in
| codeqa | def test read twoline normal table '\n Col 1 Col 2 \n-------------\n 1 2xx"hello"\n 2 4\'sworlds\n'dat ascii read table Reader ascii Fixed Width Two Line assert equal dat dtype names ' Col 1 ' ' Col 2 ' assert almost equal dat[ 1 ][ 0 ] 2 4 assert equal dat[ 0 ][ 1 ] '"hello"' assert equal dat[ 1 ][ 1 ] "'sworlds"
| null | null | null | null | Question:
In which direction did some cruft throw to test column positioning ?
Code:
def test_read_twoline_normal():
table = '\n Col1 Col2\n ---- ---------\n 1.2xx"hello"\n 2.4 \'s worlds\n'
dat = ascii.read(table, Reader=ascii.FixedWidthTwoLine)
assert_equal(dat.dtype.names, ('Col1', 'Col2'))
assert_almost_equal(dat[1][0], 2.4)
assert_equal(dat[0][1], '"hello"')
assert_equal(dat[1][1], "'s worlds")
|
null | null | null | What thrown to test column positioning in ?
| def test_read_twoline_normal():
table = '\n Col1 Col2\n ---- ---------\n 1.2xx"hello"\n 2.4 \'s worlds\n'
dat = ascii.read(table, Reader=ascii.FixedWidthTwoLine)
assert_equal(dat.dtype.names, ('Col1', 'Col2'))
assert_almost_equal(dat[1][0], 2.4)
assert_equal(dat[0][1], '"hello"')
assert_equal(dat[1][1], "'s worlds")
| null | null | null | some cruft
| codeqa | def test read twoline normal table '\n Col 1 Col 2 \n-------------\n 1 2xx"hello"\n 2 4\'sworlds\n'dat ascii read table Reader ascii Fixed Width Two Line assert equal dat dtype names ' Col 1 ' ' Col 2 ' assert almost equal dat[ 1 ][ 0 ] 2 4 assert equal dat[ 0 ][ 1 ] '"hello"' assert equal dat[ 1 ][ 1 ] "'sworlds"
| null | null | null | null | Question:
What thrown to test column positioning in ?
Code:
def test_read_twoline_normal():
table = '\n Col1 Col2\n ---- ---------\n 1.2xx"hello"\n 2.4 \'s worlds\n'
dat = ascii.read(table, Reader=ascii.FixedWidthTwoLine)
assert_equal(dat.dtype.names, ('Col1', 'Col2'))
assert_almost_equal(dat[1][0], 2.4)
assert_equal(dat[0][1], '"hello"')
assert_equal(dat[1][1], "'s worlds")
|
null | null | null | What did some cruft throw in ?
| def test_read_twoline_normal():
table = '\n Col1 Col2\n ---- ---------\n 1.2xx"hello"\n 2.4 \'s worlds\n'
dat = ascii.read(table, Reader=ascii.FixedWidthTwoLine)
assert_equal(dat.dtype.names, ('Col1', 'Col2'))
assert_almost_equal(dat[1][0], 2.4)
assert_equal(dat[0][1], '"hello"')
assert_equal(dat[1][1], "'s worlds")
| null | null | null | to test column positioning
| codeqa | def test read twoline normal table '\n Col 1 Col 2 \n-------------\n 1 2xx"hello"\n 2 4\'sworlds\n'dat ascii read table Reader ascii Fixed Width Two Line assert equal dat dtype names ' Col 1 ' ' Col 2 ' assert almost equal dat[ 1 ][ 0 ] 2 4 assert equal dat[ 0 ][ 1 ] '"hello"' assert equal dat[ 1 ][ 1 ] "'sworlds"
| null | null | null | null | Question:
What did some cruft throw in ?
Code:
def test_read_twoline_normal():
table = '\n Col1 Col2\n ---- ---------\n 1.2xx"hello"\n 2.4 \'s worlds\n'
dat = ascii.read(table, Reader=ascii.FixedWidthTwoLine)
assert_equal(dat.dtype.names, ('Col1', 'Col2'))
assert_almost_equal(dat[1][0], 2.4)
assert_equal(dat[0][1], '"hello"')
assert_equal(dat[1][1], "'s worlds")
|
null | null | null | What serves an error page statically ?
| @util.positional(2)
def error(status_code, status_message=None, content_type='text/plain; charset=utf-8', headers=None, content=None):
if (status_message is None):
status_message = httplib.responses.get(status_code, 'Unknown Error')
if (content is None):
content = status_message
content = util.pad_string(content)
return static_page(content, status=(status_code, status_message), content_type=content_type, headers=headers)
| null | null | null | wsgi application
| codeqa | @util positional 2 def error status code status message None content type 'text/plain charset utf- 8 ' headers None content None if status message is None status message httplib responses get status code ' Unknown Error' if content is None content status messagecontent util pad string content return static page content status status code status message content type content type headers headers
| null | null | null | null | Question:
What serves an error page statically ?
Code:
@util.positional(2)
def error(status_code, status_message=None, content_type='text/plain; charset=utf-8', headers=None, content=None):
if (status_message is None):
status_message = httplib.responses.get(status_code, 'Unknown Error')
if (content is None):
content = status_message
content = util.pad_string(content)
return static_page(content, status=(status_code, status_message), content_type=content_type, headers=headers)
|
null | null | null | What do we get ?
| def _assert_reorder(cov_new, cov_orig, order):
inv_order = np.argsort(order)
assert_array_equal([cov_new['names'][ii] for ii in inv_order], cov_orig['names'])
assert_allclose(cov_new['data'][inv_order][:, inv_order], cov_orig['data'], atol=1e-20)
| null | null | null | the same result
| codeqa | def assert reorder cov new cov orig order inv order np argsort order assert array equal [cov new['names'][ii] for ii in inv order] cov orig['names'] assert allclose cov new['data'][inv order][ inv order] cov orig['data'] atol 1e- 20
| null | null | null | null | Question:
What do we get ?
Code:
def _assert_reorder(cov_new, cov_orig, order):
inv_order = np.argsort(order)
assert_array_equal([cov_new['names'][ii] for ii in inv_order], cov_orig['names'])
assert_allclose(cov_new['data'][inv_order][:, inv_order], cov_orig['data'], atol=1e-20)
|
null | null | null | What uses to remove trailing slashes from the request path ?
| def removeslash(method):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if self.request.path.endswith('/'):
if (self.request.method in ('GET', 'HEAD')):
uri = self.request.path.rstrip('/')
if uri:
if self.request.query:
uri += ('?' + self.request.query)
self.redirect(uri, permanent=True)
return
else:
raise HTTPError(404)
return method(self, *args, **kwargs)
return wrapper
| null | null | null | this decorator
| codeqa | def removeslash method @functools wraps method def wrapper self *args **kwargs if self request path endswith '/' if self request method in 'GET' 'HEAD' uri self request path rstrip '/' if uri if self request query uri + '?' + self request query self redirect uri permanent True returnelse raise HTTP Error 404 return method self *args **kwargs return wrapper
| null | null | null | null | Question:
What uses to remove trailing slashes from the request path ?
Code:
def removeslash(method):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if self.request.path.endswith('/'):
if (self.request.method in ('GET', 'HEAD')):
uri = self.request.path.rstrip('/')
if uri:
if self.request.query:
uri += ('?' + self.request.query)
self.redirect(uri, permanent=True)
return
else:
raise HTTPError(404)
return method(self, *args, **kwargs)
return wrapper
|
null | null | null | What does the code convert to a time tuple ?
| def parsedate_tz(data):
res = _parsedate_tz(data)
if (not res):
return
if (res[9] is None):
res[9] = 0
return tuple(res)
| null | null | null | a date string
| codeqa | def parsedate tz data res parsedate tz data if not res returnif res[ 9 ] is None res[ 9 ] 0return tuple res
| null | null | null | null | Question:
What does the code convert to a time tuple ?
Code:
def parsedate_tz(data):
res = _parsedate_tz(data)
if (not res):
return
if (res[9] is None):
res[9] = 0
return tuple(res)
|
null | null | null | What does the code check ?
| def check_password_hash(pwhash, password):
if (pwhash.count('$') < 2):
return False
(method, salt, hashval) = pwhash.split('$', 2)
return safe_str_cmp(_hash_internal(method, salt, password), hashval)
| null | null | null | a password against a given salted and hashed password value
| codeqa | def check password hash pwhash password if pwhash count '$' < 2 return False method salt hashval pwhash split '$' 2 return safe str cmp hash internal method salt password hashval
| null | null | null | null | Question:
What does the code check ?
Code:
def check_password_hash(pwhash, password):
if (pwhash.count('$') < 2):
return False
(method, salt, hashval) = pwhash.split('$', 2)
return safe_str_cmp(_hash_internal(method, salt, password), hashval)
|
null | null | null | What does the code compute ?
| def dot(a, b):
(a, b) = (as_tensor_variable(a), as_tensor_variable(b))
if ((a.ndim == 0) or (b.ndim == 0)):
return (a * b)
elif ((a.ndim > 2) or (b.ndim > 2)):
return tensordot(a, b, [[(a.ndim - 1)], [numpy.maximum(0, (b.ndim - 2))]])
else:
return _dot(a, b)
| null | null | null | the dot product of two variables
| codeqa | def dot a b a b as tensor variable a as tensor variable b if a ndim 0 or b ndim 0 return a * b elif a ndim > 2 or b ndim > 2 return tensordot a b [[ a ndim - 1 ] [numpy maximum 0 b ndim - 2 ]] else return dot a b
| null | null | null | null | Question:
What does the code compute ?
Code:
def dot(a, b):
(a, b) = (as_tensor_variable(a), as_tensor_variable(b))
if ((a.ndim == 0) or (b.ndim == 0)):
return (a * b)
elif ((a.ndim > 2) or (b.ndim > 2)):
return tensordot(a, b, [[(a.ndim - 1)], [numpy.maximum(0, (b.ndim - 2))]])
else:
return _dot(a, b)
|
null | null | null | What enforces computation ?
| def upcast_float16_ufunc(fn):
def ret(*args, **kwargs):
out_dtype = numpy.find_common_type([a.dtype for a in args], [numpy.float16])
if (out_dtype == 'float16'):
sig = ((('f' * fn.nin) + '->') + ('f' * fn.nout))
kwargs.update(sig=sig)
return fn(*args, **kwargs)
return ret
| null | null | null | decorator
| codeqa | def upcast float 16 ufunc fn def ret *args **kwargs out dtype numpy find common type [a dtype for a in args] [numpy float 16 ] if out dtype 'float 16 ' sig 'f' * fn nin + '->' + 'f' * fn nout kwargs update sig sig return fn *args **kwargs return ret
| null | null | null | null | Question:
What enforces computation ?
Code:
def upcast_float16_ufunc(fn):
def ret(*args, **kwargs):
out_dtype = numpy.find_common_type([a.dtype for a in args], [numpy.float16])
if (out_dtype == 'float16'):
sig = ((('f' * fn.nin) + '->') + ('f' * fn.nout))
kwargs.update(sig=sig)
return fn(*args, **kwargs)
return ret
|
null | null | null | What does decorator enforce ?
| def upcast_float16_ufunc(fn):
def ret(*args, **kwargs):
out_dtype = numpy.find_common_type([a.dtype for a in args], [numpy.float16])
if (out_dtype == 'float16'):
sig = ((('f' * fn.nin) + '->') + ('f' * fn.nout))
kwargs.update(sig=sig)
return fn(*args, **kwargs)
return ret
| null | null | null | computation
| codeqa | def upcast float 16 ufunc fn def ret *args **kwargs out dtype numpy find common type [a dtype for a in args] [numpy float 16 ] if out dtype 'float 16 ' sig 'f' * fn nin + '->' + 'f' * fn nout kwargs update sig sig return fn *args **kwargs return ret
| null | null | null | null | Question:
What does decorator enforce ?
Code:
def upcast_float16_ufunc(fn):
def ret(*args, **kwargs):
out_dtype = numpy.find_common_type([a.dtype for a in args], [numpy.float16])
if (out_dtype == 'float16'):
sig = ((('f' * fn.nin) + '->') + ('f' * fn.nout))
kwargs.update(sig=sig)
return fn(*args, **kwargs)
return ret
|
null | null | null | What did we get when ?
| def shutdown_signal(signum, frame):
LOG.warning('shutting down, got signal %d', signum)
shutdown()
| null | null | null | a signal
| codeqa | def shutdown signal signum frame LOG warning 'shuttingdown gotsignal%d' signum shutdown
| null | null | null | null | Question:
What did we get when ?
Code:
def shutdown_signal(signum, frame):
LOG.warning('shutting down, got signal %d', signum)
shutdown()
|
null | null | null | When did the code call ?
| def shutdown_signal(signum, frame):
LOG.warning('shutting down, got signal %d', signum)
shutdown()
| null | null | null | when we get a signal and need to terminate
| codeqa | def shutdown signal signum frame LOG warning 'shuttingdown gotsignal%d' signum shutdown
| null | null | null | null | Question:
When did the code call ?
Code:
def shutdown_signal(signum, frame):
LOG.warning('shutting down, got signal %d', signum)
shutdown()
|
null | null | null | What do we need when ?
| def shutdown_signal(signum, frame):
LOG.warning('shutting down, got signal %d', signum)
shutdown()
| null | null | null | to terminate
| codeqa | def shutdown signal signum frame LOG warning 'shuttingdown gotsignal%d' signum shutdown
| null | null | null | null | Question:
What do we need when ?
Code:
def shutdown_signal(signum, frame):
LOG.warning('shutting down, got signal %d', signum)
shutdown()
|
null | null | null | What does the code append ?
| def _AppendFirstLeafTokenSubtype(node, subtype):
if isinstance(node, pytree.Leaf):
_AppendTokenSubtype(node, subtype)
return
_AppendFirstLeafTokenSubtype(node.children[0], subtype)
| null | null | null | the first leaf tokens subtypes
| codeqa | def Append First Leaf Token Subtype node subtype if isinstance node pytree Leaf Append Token Subtype node subtype return Append First Leaf Token Subtype node children[ 0 ] subtype
| null | null | null | null | Question:
What does the code append ?
Code:
def _AppendFirstLeafTokenSubtype(node, subtype):
if isinstance(node, pytree.Leaf):
_AppendTokenSubtype(node, subtype)
return
_AppendFirstLeafTokenSubtype(node.children[0], subtype)
|
null | null | null | What did the code read ?
| def read_tfrs(fname, condition=None):
check_fname(fname, 'tfr', ('-tfr.h5',))
logger.info(('Reading %s ...' % fname))
tfr_data = read_hdf5(fname, title='mnepython')
for (k, tfr) in tfr_data:
tfr['info'] = Info(tfr['info'])
if (condition is not None):
tfr_dict = dict(tfr_data)
if (condition not in tfr_dict):
keys = [('%s' % k) for k in tfr_dict]
raise ValueError('Cannot find condition ("{0}") in this file. The file contains "{1}""'.format(condition, ' or '.join(keys)))
out = AverageTFR(**tfr_dict[condition])
else:
out = [AverageTFR(**d) for d in list(zip(*tfr_data))[1]]
return out
| null | null | null | tfr datasets
| codeqa | def read tfrs fname condition None check fname fname 'tfr' '-tfr h5 ' logger info ' Reading%s ' % fname tfr data read hdf 5 fname title 'mnepython' for k tfr in tfr data tfr['info'] Info tfr['info'] if condition is not None tfr dict dict tfr data if condition not in tfr dict keys [ '%s' % k for k in tfr dict]raise Value Error ' Cannotfindcondition "{ 0 }" inthisfile Thefilecontains"{ 1 }""' format condition 'or' join keys out Average TFR **tfr dict[condition] else out [ Average TFR **d for d in list zip *tfr data [1 ]]return out
| null | null | null | null | Question:
What did the code read ?
Code:
def read_tfrs(fname, condition=None):
check_fname(fname, 'tfr', ('-tfr.h5',))
logger.info(('Reading %s ...' % fname))
tfr_data = read_hdf5(fname, title='mnepython')
for (k, tfr) in tfr_data:
tfr['info'] = Info(tfr['info'])
if (condition is not None):
tfr_dict = dict(tfr_data)
if (condition not in tfr_dict):
keys = [('%s' % k) for k in tfr_dict]
raise ValueError('Cannot find condition ("{0}") in this file. The file contains "{1}""'.format(condition, ' or '.join(keys)))
out = AverageTFR(**tfr_dict[condition])
else:
out = [AverageTFR(**d) for d in list(zip(*tfr_data))[1]]
return out
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.