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 this function do? | def _EndGroup(buffer, pos, end):
return (-1)
| null | null | null | Skipping an END_GROUP tag returns -1 to tell the parent loop to break. | pcsd | def End Group buffer pos end return -1 | 8692 | def _EndGroup(buffer, pos, end):
return (-1)
| Skipping an END_GROUP tag returns -1 to tell the parent loop to break. | skipping an end _ group tag returns - 1 to tell the parent loop to break . | Question:
What does this function do?
Code:
def _EndGroup(buffer, pos, end):
return (-1)
|
null | null | null | What does this function do? | def _instance_name(instance):
return getattr(instance, 'OS-EXT-SRV-ATTR:instance_name', None)
| null | null | null | Shortcut to get instance name. | pcsd | def instance name instance return getattr instance 'OS-EXT-SRV-ATTR instance name' None | 8702 | def _instance_name(instance):
return getattr(instance, 'OS-EXT-SRV-ATTR:instance_name', None)
| Shortcut to get instance name. | shortcut to get instance name . | Question:
What does this function do?
Code:
def _instance_name(instance):
return getattr(instance, 'OS-EXT-SRV-ATTR:instance_name', None)
|
null | null | null | What does this function do? | def worker(options):
workerPid = os.getpid()
if (not options.noaffinity):
p = psutil.Process(workerPid)
print 'affinity [before]', p.cpu_affinity()
p.cpu_affinity([options.cpuid])
print 'affinity [after]', p.cpu_affinity()
factory = EchoServerFactory(options.wsuri)
reactor.adoptStreamPort(options.fd, AF_INET, factory)
if (not options.silence):
print ('Worker started on PID %s using factory %s and protocol %s' % (workerPid, factory, factory.protocol))
if options.profile:
statprof.reset(PROFILER_FREQ)
statprof.start()
if (not options.silence):
def stat():
if options.profile:
statprof.stop()
output = StringIO.StringIO()
output.write((('-' * 80) + '\n'))
output.write(('Worker Statistics (PID %s)\n\n%s' % (workerPid, factory.stats.stats())))
if options.profile:
output.write('\n')
statprof.display(output)
output.write((('-' * 80) + '\n\n'))
sys.stdout.write(output.getvalue())
if options.profile:
statprof.reset(PROFILER_FREQ)
statprof.start()
reactor.callLater(options.interval, stat)
reactor.callLater(options.interval, stat)
if False:
import cProfile
print 'RUNNING cProfile'
cProfile.run('reactor.run()')
else:
reactor.run()
| null | null | null | Start background worker process. | pcsd | def worker options worker Pid = os getpid if not options noaffinity p = psutil Process worker Pid print 'affinity [before]' p cpu affinity p cpu affinity [options cpuid] print 'affinity [after]' p cpu affinity factory = Echo Server Factory options wsuri reactor adopt Stream Port options fd AF INET factory if not options silence print 'Worker started on PID %s using factory %s and protocol %s' % worker Pid factory factory protocol if options profile statprof reset PROFILER FREQ statprof start if not options silence def stat if options profile statprof stop output = String IO String IO output write '-' * 80 + ' ' output write 'Worker Statistics PID %s %s' % worker Pid factory stats stats if options profile output write ' ' statprof display output output write '-' * 80 + ' ' sys stdout write output getvalue if options profile statprof reset PROFILER FREQ statprof start reactor call Later options interval stat reactor call Later options interval stat if False import c Profile print 'RUNNING c Profile' c Profile run 'reactor run ' else reactor run | 8712 | def worker(options):
workerPid = os.getpid()
if (not options.noaffinity):
p = psutil.Process(workerPid)
print 'affinity [before]', p.cpu_affinity()
p.cpu_affinity([options.cpuid])
print 'affinity [after]', p.cpu_affinity()
factory = EchoServerFactory(options.wsuri)
reactor.adoptStreamPort(options.fd, AF_INET, factory)
if (not options.silence):
print ('Worker started on PID %s using factory %s and protocol %s' % (workerPid, factory, factory.protocol))
if options.profile:
statprof.reset(PROFILER_FREQ)
statprof.start()
if (not options.silence):
def stat():
if options.profile:
statprof.stop()
output = StringIO.StringIO()
output.write((('-' * 80) + '\n'))
output.write(('Worker Statistics (PID %s)\n\n%s' % (workerPid, factory.stats.stats())))
if options.profile:
output.write('\n')
statprof.display(output)
output.write((('-' * 80) + '\n\n'))
sys.stdout.write(output.getvalue())
if options.profile:
statprof.reset(PROFILER_FREQ)
statprof.start()
reactor.callLater(options.interval, stat)
reactor.callLater(options.interval, stat)
if False:
import cProfile
print 'RUNNING cProfile'
cProfile.run('reactor.run()')
else:
reactor.run()
| Start background worker process. | start background worker process . | Question:
What does this function do?
Code:
def worker(options):
workerPid = os.getpid()
if (not options.noaffinity):
p = psutil.Process(workerPid)
print 'affinity [before]', p.cpu_affinity()
p.cpu_affinity([options.cpuid])
print 'affinity [after]', p.cpu_affinity()
factory = EchoServerFactory(options.wsuri)
reactor.adoptStreamPort(options.fd, AF_INET, factory)
if (not options.silence):
print ('Worker started on PID %s using factory %s and protocol %s' % (workerPid, factory, factory.protocol))
if options.profile:
statprof.reset(PROFILER_FREQ)
statprof.start()
if (not options.silence):
def stat():
if options.profile:
statprof.stop()
output = StringIO.StringIO()
output.write((('-' * 80) + '\n'))
output.write(('Worker Statistics (PID %s)\n\n%s' % (workerPid, factory.stats.stats())))
if options.profile:
output.write('\n')
statprof.display(output)
output.write((('-' * 80) + '\n\n'))
sys.stdout.write(output.getvalue())
if options.profile:
statprof.reset(PROFILER_FREQ)
statprof.start()
reactor.callLater(options.interval, stat)
reactor.callLater(options.interval, stat)
if False:
import cProfile
print 'RUNNING cProfile'
cProfile.run('reactor.run()')
else:
reactor.run()
|
null | null | null | What does this function do? | def _get_raw_path(src, dst):
if (len(path_map) == 0):
_calc_paths()
if (src is dst):
return []
if (path_map[src][dst][0] is None):
return None
intermediate = path_map[src][dst][1]
if (intermediate is None):
return []
return ((_get_raw_path(src, intermediate) + [intermediate]) + _get_raw_path(intermediate, dst))
| null | null | null | Get a raw path (just a list of nodes to traverse) | pcsd | def get raw path src dst if len path map == 0 calc paths if src is dst return [] if path map[src][dst][0] is None return None intermediate = path map[src][dst][1] if intermediate is None return [] return get raw path src intermediate + [intermediate] + get raw path intermediate dst | 8716 | def _get_raw_path(src, dst):
if (len(path_map) == 0):
_calc_paths()
if (src is dst):
return []
if (path_map[src][dst][0] is None):
return None
intermediate = path_map[src][dst][1]
if (intermediate is None):
return []
return ((_get_raw_path(src, intermediate) + [intermediate]) + _get_raw_path(intermediate, dst))
| Get a raw path (just a list of nodes to traverse) | get a raw path | Question:
What does this function do?
Code:
def _get_raw_path(src, dst):
if (len(path_map) == 0):
_calc_paths()
if (src is dst):
return []
if (path_map[src][dst][0] is None):
return None
intermediate = path_map[src][dst][1]
if (intermediate is None):
return []
return ((_get_raw_path(src, intermediate) + [intermediate]) + _get_raw_path(intermediate, dst))
|
null | null | null | What does this function do? | def month_by_name(name):
ENGLISH_NAMES = [u'January', u'February', u'March', u'April', u'May', u'June', u'July', u'August', u'September', u'October', u'November', u'December']
try:
return (ENGLISH_NAMES.index(name) + 1)
except ValueError:
return None
| null | null | null | Return the number of a month by (locale-independently) English name | pcsd | def month by name name ENGLISH NAMES = [u'January' u'February' u'March' u'April' u'May' u'June' u'July' u'August' u'September' u'October' u'November' u'December'] try return ENGLISH NAMES index name + 1 except Value Error return None | 8722 | def month_by_name(name):
ENGLISH_NAMES = [u'January', u'February', u'March', u'April', u'May', u'June', u'July', u'August', u'September', u'October', u'November', u'December']
try:
return (ENGLISH_NAMES.index(name) + 1)
except ValueError:
return None
| Return the number of a month by (locale-independently) English name | return the number of a month by english name | Question:
What does this function do?
Code:
def month_by_name(name):
ENGLISH_NAMES = [u'January', u'February', u'March', u'April', u'May', u'June', u'July', u'August', u'September', u'October', u'November', u'December']
try:
return (ENGLISH_NAMES.index(name) + 1)
except ValueError:
return None
|
null | null | null | What does this function do? | def remove_prefix(string, prefix):
if string.startswith(prefix):
return string[len(prefix):]
else:
return string
| null | null | null | This function removes the given prefix from a string, if the string does
indeed begin with the prefix; otherwise, it returns the string
unmodified. | pcsd | def remove prefix string prefix if string startswith prefix return string[len prefix ] else return string | 8731 | def remove_prefix(string, prefix):
if string.startswith(prefix):
return string[len(prefix):]
else:
return string
| This function removes the given prefix from a string, if the string does
indeed begin with the prefix; otherwise, it returns the string
unmodified. | this function removes the given prefix from a string , if the string does indeed begin with the prefix ; otherwise , it returns the string unmodified . | Question:
What does this function do?
Code:
def remove_prefix(string, prefix):
if string.startswith(prefix):
return string[len(prefix):]
else:
return string
|
null | null | null | What does this function do? | def create_imagefile(options, filename, latlon, ground_width, path_objs, mission_obj, fence_obj, width=600, height=600):
mt = mp_tile.MPTile(service=options.service)
map_img = mt.area_to_image(latlon[0], latlon[1], width, height, ground_width)
while (mt.tiles_pending() > 0):
print ('Waiting on %u tiles' % mt.tiles_pending())
time.sleep(1)
map_img = mt.area_to_image(latlon[0], latlon[1], width, height, ground_width)
pixmapper = functools.partial(pixel_coords, ground_width=ground_width, mt=mt, topleft=latlon, width=width)
for path_obj in path_objs:
path_obj.draw(map_img, pixmapper, None)
if (mission_obj is not None):
for m in mission_obj:
m.draw(map_img, pixmapper, None)
if (fence_obj is not None):
fence_obj.draw(map_img, pixmapper, None)
map_img = cv2.cvtColor(map_img, cv2.COLOR_BGR2RGB)
cv2.imwrite(filename, map_img)
| null | null | null | create path and mission as an image file | pcsd | def create imagefile options filename latlon ground width path objs mission obj fence obj width=600 height=600 mt = mp tile MP Tile service=options service map img = mt area to image latlon[0] latlon[1] width height ground width while mt tiles pending > 0 print 'Waiting on %u tiles' % mt tiles pending time sleep 1 map img = mt area to image latlon[0] latlon[1] width height ground width pixmapper = functools partial pixel coords ground width=ground width mt=mt topleft=latlon width=width for path obj in path objs path obj draw map img pixmapper None if mission obj is not None for m in mission obj m draw map img pixmapper None if fence obj is not None fence obj draw map img pixmapper None map img = cv2 cvt Color map img cv2 COLOR BGR2RGB cv2 imwrite filename map img | 8734 | def create_imagefile(options, filename, latlon, ground_width, path_objs, mission_obj, fence_obj, width=600, height=600):
mt = mp_tile.MPTile(service=options.service)
map_img = mt.area_to_image(latlon[0], latlon[1], width, height, ground_width)
while (mt.tiles_pending() > 0):
print ('Waiting on %u tiles' % mt.tiles_pending())
time.sleep(1)
map_img = mt.area_to_image(latlon[0], latlon[1], width, height, ground_width)
pixmapper = functools.partial(pixel_coords, ground_width=ground_width, mt=mt, topleft=latlon, width=width)
for path_obj in path_objs:
path_obj.draw(map_img, pixmapper, None)
if (mission_obj is not None):
for m in mission_obj:
m.draw(map_img, pixmapper, None)
if (fence_obj is not None):
fence_obj.draw(map_img, pixmapper, None)
map_img = cv2.cvtColor(map_img, cv2.COLOR_BGR2RGB)
cv2.imwrite(filename, map_img)
| create path and mission as an image file | create path and mission as an image file | Question:
What does this function do?
Code:
def create_imagefile(options, filename, latlon, ground_width, path_objs, mission_obj, fence_obj, width=600, height=600):
mt = mp_tile.MPTile(service=options.service)
map_img = mt.area_to_image(latlon[0], latlon[1], width, height, ground_width)
while (mt.tiles_pending() > 0):
print ('Waiting on %u tiles' % mt.tiles_pending())
time.sleep(1)
map_img = mt.area_to_image(latlon[0], latlon[1], width, height, ground_width)
pixmapper = functools.partial(pixel_coords, ground_width=ground_width, mt=mt, topleft=latlon, width=width)
for path_obj in path_objs:
path_obj.draw(map_img, pixmapper, None)
if (mission_obj is not None):
for m in mission_obj:
m.draw(map_img, pixmapper, None)
if (fence_obj is not None):
fence_obj.draw(map_img, pixmapper, None)
map_img = cv2.cvtColor(map_img, cv2.COLOR_BGR2RGB)
cv2.imwrite(filename, map_img)
|
null | null | null | What does this function do? | def MIN(ds, count, timeperiod=(- (2 ** 31))):
return call_talib_with_ds(ds, count, talib.MIN, timeperiod)
| null | null | null | Lowest value over a specified period | pcsd | def MIN ds count timeperiod= - 2 ** 31 return call talib with ds ds count talib MIN timeperiod | 8735 | def MIN(ds, count, timeperiod=(- (2 ** 31))):
return call_talib_with_ds(ds, count, talib.MIN, timeperiod)
| Lowest value over a specified period | lowest value over a specified period | Question:
What does this function do?
Code:
def MIN(ds, count, timeperiod=(- (2 ** 31))):
return call_talib_with_ds(ds, count, talib.MIN, timeperiod)
|
null | null | null | What does this function do? | def flatten(results):
for row in results:
(yield (c.value for c in row))
| null | null | null | Return cell values row-by-row | pcsd | def flatten results for row in results yield c value for c in row | 8753 | def flatten(results):
for row in results:
(yield (c.value for c in row))
| Return cell values row-by-row | return cell values row - by - row | Question:
What does this function do?
Code:
def flatten(results):
for row in results:
(yield (c.value for c in row))
|
null | null | null | What does this function do? | def systemInformationType2bis():
a = L2PseudoLength(l2pLength=21)
b = TpPd(pd=6)
c = MessageType(mesType=2)
d = NeighbourCellsDescription()
e = RachControlParameters()
f = Si2bisRestOctets()
packet = (((((a / b) / c) / d) / e) / f)
return packet
| null | null | null | SYSTEM INFORMATION TYPE 2bis Section 9.1.33 | pcsd | def system Information Type2bis a = L2Pseudo Length l2p Length=21 b = Tp Pd pd=6 c = Message Type mes Type=2 d = Neighbour Cells Description e = Rach Control Parameters f = Si2bis Rest Octets packet = a / b / c / d / e / f return packet | 8754 | def systemInformationType2bis():
a = L2PseudoLength(l2pLength=21)
b = TpPd(pd=6)
c = MessageType(mesType=2)
d = NeighbourCellsDescription()
e = RachControlParameters()
f = Si2bisRestOctets()
packet = (((((a / b) / c) / d) / e) / f)
return packet
| SYSTEM INFORMATION TYPE 2bis Section 9.1.33 | system information type 2bis section 9 . 1 . 33 | Question:
What does this function do?
Code:
def systemInformationType2bis():
a = L2PseudoLength(l2pLength=21)
b = TpPd(pd=6)
c = MessageType(mesType=2)
d = NeighbourCellsDescription()
e = RachControlParameters()
f = Si2bisRestOctets()
packet = (((((a / b) / c) / d) / e) / f)
return packet
|
null | null | null | What does this function do? | def getAddIndexedLoops(loop, vertexes, zList):
indexedLoops = []
for z in zList:
indexedLoop = getAddIndexedLoop(loop, vertexes, z)
indexedLoops.append(indexedLoop)
return indexedLoops
| null | null | null | Get and add indexed loops. | pcsd | def get Add Indexed Loops loop vertexes z List indexed Loops = [] for z in z List indexed Loop = get Add Indexed Loop loop vertexes z indexed Loops append indexed Loop return indexed Loops | 8757 | def getAddIndexedLoops(loop, vertexes, zList):
indexedLoops = []
for z in zList:
indexedLoop = getAddIndexedLoop(loop, vertexes, z)
indexedLoops.append(indexedLoop)
return indexedLoops
| Get and add indexed loops. | get and add indexed loops . | Question:
What does this function do?
Code:
def getAddIndexedLoops(loop, vertexes, zList):
indexedLoops = []
for z in zList:
indexedLoop = getAddIndexedLoop(loop, vertexes, z)
indexedLoops.append(indexedLoop)
return indexedLoops
|
null | null | null | What does this function do? | def up(count, group, zone, image_id, instance_type, username, key_name, subnet, bid=None):
(existing_username, existing_key_name, existing_zone, instance_ids) = _read_server_list(zone)
count = int(count)
if ((existing_username == username) and (existing_key_name == key_name) and (existing_zone == zone)):
ec2_connection = boto.ec2.connect_to_region(_get_region(zone))
existing_reservations = ec2_connection.get_all_instances(instance_ids=instance_ids)
existing_instances = filter((lambda i: (i.state == 'running')), [r.instances[0] for r in existing_reservations])
if (count <= len(existing_instances)):
print 'Bees are already assembled and awaiting orders.'
return
else:
count -= len(existing_instances)
elif instance_ids:
print 'Taking down {} unusable bees.'.format(len(instance_ids))
with _redirect_stdout():
down()
(existing_username, existing_key_name, existing_zone, instance_ids) = _read_server_list(zone)
pem_path = _get_pem_path(key_name)
if (not os.path.isfile(pem_path)):
print ('Warning. No key file found for %s. You will need to add this key to your SSH agent to connect.' % pem_path)
print 'Connecting to the hive.'
try:
ec2_connection = boto.ec2.connect_to_region(_get_region(zone))
except boto.exception.NoAuthHandlerFound as e:
print 'Authenciation config error, perhaps you do not have a ~/.boto file with correct permissions?'
print e.message
return e
except Exception as e:
print 'Unknown error occured:'
print e.message
return e
if (ec2_connection == None):
raise Exception('Invalid zone specified? Unable to connect to region using zone name')
groupId = (group if (subnet is None) else _get_security_group_id(ec2_connection, group, subnet))
print ('GroupId found: %s' % groupId)
placement = (None if ('gov' in zone) else zone)
print ('Placement: %s' % placement)
if bid:
print ('Attempting to call up %i spot bees, this can take a while...' % count)
spot_requests = ec2_connection.request_spot_instances(image_id=image_id, price=bid, count=count, key_name=key_name, security_group_ids=[groupId], instance_type=instance_type, placement=placement, subnet_id=subnet)
time.sleep(5)
instances = _wait_for_spot_request_fulfillment(ec2_connection, spot_requests)
else:
print ('Attempting to call up %i bees.' % count)
try:
reservation = ec2_connection.run_instances(image_id=image_id, min_count=count, max_count=count, key_name=key_name, security_group_ids=[groupId], instance_type=instance_type, placement=placement, subnet_id=subnet)
except boto.exception.EC2ResponseError as e:
print ('Unable to call bees:', e.message)
print 'Is your sec group available in this region?'
return e
instances = reservation.instances
if instance_ids:
existing_reservations = ec2_connection.get_all_instances(instance_ids=instance_ids)
existing_instances = filter((lambda i: (i.state == 'running')), [r.instances[0] for r in existing_reservations])
map(instances.append, existing_instances)
dead_instances = filter((lambda i: (i not in [j.id for j in existing_instances])), instance_ids)
map(instance_ids.pop, [instance_ids.index(i) for i in dead_instances])
print 'Waiting for bees to load their machine guns...'
instance_ids = (instance_ids or [])
for instance in [i for i in instances if (i.state == 'pending')]:
instance.update()
while (instance.state != 'running'):
print '.'
time.sleep(5)
instance.update()
instance_ids.append(instance.id)
print ('Bee %s is ready for the attack.' % instance.id)
ec2_connection.create_tags(instance_ids, {'Name': 'a bee!'})
_write_server_list(username, key_name, zone, instances)
print ('The swarm has assembled %i bees.' % len(instances))
| null | null | null | Startup the load testing server. | pcsd | def up count group zone image id instance type username key name subnet bid=None existing username existing key name existing zone instance ids = read server list zone count = int count if existing username == username and existing key name == key name and existing zone == zone ec2 connection = boto ec2 connect to region get region zone existing reservations = ec2 connection get all instances instance ids=instance ids existing instances = filter lambda i i state == 'running' [r instances[0] for r in existing reservations] if count <= len existing instances print 'Bees are already assembled and awaiting orders ' return else count -= len existing instances elif instance ids print 'Taking down {} unusable bees ' format len instance ids with redirect stdout down existing username existing key name existing zone instance ids = read server list zone pem path = get pem path key name if not os path isfile pem path print 'Warning No key file found for %s You will need to add this key to your SSH agent to connect ' % pem path print 'Connecting to the hive ' try ec2 connection = boto ec2 connect to region get region zone except boto exception No Auth Handler Found as e print 'Authenciation config error perhaps you do not have a ~/ boto file with correct permissions?' print e message return e except Exception as e print 'Unknown error occured ' print e message return e if ec2 connection == None raise Exception 'Invalid zone specified? Unable to connect to region using zone name' group Id = group if subnet is None else get security group id ec2 connection group subnet print 'Group Id found %s' % group Id placement = None if 'gov' in zone else zone print 'Placement %s' % placement if bid print 'Attempting to call up %i spot bees this can take a while ' % count spot requests = ec2 connection request spot instances image id=image id price=bid count=count key name=key name security group ids=[group Id] instance type=instance type placement=placement subnet id=subnet time sleep 5 instances = wait for spot request fulfillment ec2 connection spot requests else print 'Attempting to call up %i bees ' % count try reservation = ec2 connection run instances image id=image id min count=count max count=count key name=key name security group ids=[group Id] instance type=instance type placement=placement subnet id=subnet except boto exception EC2Response Error as e print 'Unable to call bees ' e message print 'Is your sec group available in this region?' return e instances = reservation instances if instance ids existing reservations = ec2 connection get all instances instance ids=instance ids existing instances = filter lambda i i state == 'running' [r instances[0] for r in existing reservations] map instances append existing instances dead instances = filter lambda i i not in [j id for j in existing instances] instance ids map instance ids pop [instance ids index i for i in dead instances] print 'Waiting for bees to load their machine guns ' instance ids = instance ids or [] for instance in [i for i in instances if i state == 'pending' ] instance update while instance state != 'running' print ' ' time sleep 5 instance update instance ids append instance id print 'Bee %s is ready for the attack ' % instance id ec2 connection create tags instance ids {'Name' 'a bee!'} write server list username key name zone instances print 'The swarm has assembled %i bees ' % len instances | 8759 | def up(count, group, zone, image_id, instance_type, username, key_name, subnet, bid=None):
(existing_username, existing_key_name, existing_zone, instance_ids) = _read_server_list(zone)
count = int(count)
if ((existing_username == username) and (existing_key_name == key_name) and (existing_zone == zone)):
ec2_connection = boto.ec2.connect_to_region(_get_region(zone))
existing_reservations = ec2_connection.get_all_instances(instance_ids=instance_ids)
existing_instances = filter((lambda i: (i.state == 'running')), [r.instances[0] for r in existing_reservations])
if (count <= len(existing_instances)):
print 'Bees are already assembled and awaiting orders.'
return
else:
count -= len(existing_instances)
elif instance_ids:
print 'Taking down {} unusable bees.'.format(len(instance_ids))
with _redirect_stdout():
down()
(existing_username, existing_key_name, existing_zone, instance_ids) = _read_server_list(zone)
pem_path = _get_pem_path(key_name)
if (not os.path.isfile(pem_path)):
print ('Warning. No key file found for %s. You will need to add this key to your SSH agent to connect.' % pem_path)
print 'Connecting to the hive.'
try:
ec2_connection = boto.ec2.connect_to_region(_get_region(zone))
except boto.exception.NoAuthHandlerFound as e:
print 'Authenciation config error, perhaps you do not have a ~/.boto file with correct permissions?'
print e.message
return e
except Exception as e:
print 'Unknown error occured:'
print e.message
return e
if (ec2_connection == None):
raise Exception('Invalid zone specified? Unable to connect to region using zone name')
groupId = (group if (subnet is None) else _get_security_group_id(ec2_connection, group, subnet))
print ('GroupId found: %s' % groupId)
placement = (None if ('gov' in zone) else zone)
print ('Placement: %s' % placement)
if bid:
print ('Attempting to call up %i spot bees, this can take a while...' % count)
spot_requests = ec2_connection.request_spot_instances(image_id=image_id, price=bid, count=count, key_name=key_name, security_group_ids=[groupId], instance_type=instance_type, placement=placement, subnet_id=subnet)
time.sleep(5)
instances = _wait_for_spot_request_fulfillment(ec2_connection, spot_requests)
else:
print ('Attempting to call up %i bees.' % count)
try:
reservation = ec2_connection.run_instances(image_id=image_id, min_count=count, max_count=count, key_name=key_name, security_group_ids=[groupId], instance_type=instance_type, placement=placement, subnet_id=subnet)
except boto.exception.EC2ResponseError as e:
print ('Unable to call bees:', e.message)
print 'Is your sec group available in this region?'
return e
instances = reservation.instances
if instance_ids:
existing_reservations = ec2_connection.get_all_instances(instance_ids=instance_ids)
existing_instances = filter((lambda i: (i.state == 'running')), [r.instances[0] for r in existing_reservations])
map(instances.append, existing_instances)
dead_instances = filter((lambda i: (i not in [j.id for j in existing_instances])), instance_ids)
map(instance_ids.pop, [instance_ids.index(i) for i in dead_instances])
print 'Waiting for bees to load their machine guns...'
instance_ids = (instance_ids or [])
for instance in [i for i in instances if (i.state == 'pending')]:
instance.update()
while (instance.state != 'running'):
print '.'
time.sleep(5)
instance.update()
instance_ids.append(instance.id)
print ('Bee %s is ready for the attack.' % instance.id)
ec2_connection.create_tags(instance_ids, {'Name': 'a bee!'})
_write_server_list(username, key_name, zone, instances)
print ('The swarm has assembled %i bees.' % len(instances))
| Startup the load testing server. | startup the load testing server . | Question:
What does this function do?
Code:
def up(count, group, zone, image_id, instance_type, username, key_name, subnet, bid=None):
(existing_username, existing_key_name, existing_zone, instance_ids) = _read_server_list(zone)
count = int(count)
if ((existing_username == username) and (existing_key_name == key_name) and (existing_zone == zone)):
ec2_connection = boto.ec2.connect_to_region(_get_region(zone))
existing_reservations = ec2_connection.get_all_instances(instance_ids=instance_ids)
existing_instances = filter((lambda i: (i.state == 'running')), [r.instances[0] for r in existing_reservations])
if (count <= len(existing_instances)):
print 'Bees are already assembled and awaiting orders.'
return
else:
count -= len(existing_instances)
elif instance_ids:
print 'Taking down {} unusable bees.'.format(len(instance_ids))
with _redirect_stdout():
down()
(existing_username, existing_key_name, existing_zone, instance_ids) = _read_server_list(zone)
pem_path = _get_pem_path(key_name)
if (not os.path.isfile(pem_path)):
print ('Warning. No key file found for %s. You will need to add this key to your SSH agent to connect.' % pem_path)
print 'Connecting to the hive.'
try:
ec2_connection = boto.ec2.connect_to_region(_get_region(zone))
except boto.exception.NoAuthHandlerFound as e:
print 'Authenciation config error, perhaps you do not have a ~/.boto file with correct permissions?'
print e.message
return e
except Exception as e:
print 'Unknown error occured:'
print e.message
return e
if (ec2_connection == None):
raise Exception('Invalid zone specified? Unable to connect to region using zone name')
groupId = (group if (subnet is None) else _get_security_group_id(ec2_connection, group, subnet))
print ('GroupId found: %s' % groupId)
placement = (None if ('gov' in zone) else zone)
print ('Placement: %s' % placement)
if bid:
print ('Attempting to call up %i spot bees, this can take a while...' % count)
spot_requests = ec2_connection.request_spot_instances(image_id=image_id, price=bid, count=count, key_name=key_name, security_group_ids=[groupId], instance_type=instance_type, placement=placement, subnet_id=subnet)
time.sleep(5)
instances = _wait_for_spot_request_fulfillment(ec2_connection, spot_requests)
else:
print ('Attempting to call up %i bees.' % count)
try:
reservation = ec2_connection.run_instances(image_id=image_id, min_count=count, max_count=count, key_name=key_name, security_group_ids=[groupId], instance_type=instance_type, placement=placement, subnet_id=subnet)
except boto.exception.EC2ResponseError as e:
print ('Unable to call bees:', e.message)
print 'Is your sec group available in this region?'
return e
instances = reservation.instances
if instance_ids:
existing_reservations = ec2_connection.get_all_instances(instance_ids=instance_ids)
existing_instances = filter((lambda i: (i.state == 'running')), [r.instances[0] for r in existing_reservations])
map(instances.append, existing_instances)
dead_instances = filter((lambda i: (i not in [j.id for j in existing_instances])), instance_ids)
map(instance_ids.pop, [instance_ids.index(i) for i in dead_instances])
print 'Waiting for bees to load their machine guns...'
instance_ids = (instance_ids or [])
for instance in [i for i in instances if (i.state == 'pending')]:
instance.update()
while (instance.state != 'running'):
print '.'
time.sleep(5)
instance.update()
instance_ids.append(instance.id)
print ('Bee %s is ready for the attack.' % instance.id)
ec2_connection.create_tags(instance_ids, {'Name': 'a bee!'})
_write_server_list(username, key_name, zone, instances)
print ('The swarm has assembled %i bees.' % len(instances))
|
null | null | null | What does this function do? | def get_profile_model():
if (not getattr(settings, u'ACCOUNTS_PROFILE_MODEL', None)):
raise ProfileNotConfigured
try:
return apps.get_model(settings.ACCOUNTS_PROFILE_MODEL)
except ValueError:
raise ImproperlyConfigured(u"ACCOUNTS_PROFILE_MODEL must be of the form 'app_label.model_name'")
except LookupError:
raise ImproperlyConfigured((u"ACCOUNTS_PROFILE_MODEL refers to model '%s' that has not been installed" % settings.ACCOUNTS_PROFILE_MODEL))
| null | null | null | Returns the Mezzanine profile model, defined in
``settings.ACCOUNTS_PROFILE_MODEL``, or ``None`` if no profile
model is configured. | pcsd | def get profile model if not getattr settings u'ACCOUNTS PROFILE MODEL' None raise Profile Not Configured try return apps get model settings ACCOUNTS PROFILE MODEL except Value Error raise Improperly Configured u"ACCOUNTS PROFILE MODEL must be of the form 'app label model name'" except Lookup Error raise Improperly Configured u"ACCOUNTS PROFILE MODEL refers to model '%s' that has not been installed" % settings ACCOUNTS PROFILE MODEL | 8769 | def get_profile_model():
if (not getattr(settings, u'ACCOUNTS_PROFILE_MODEL', None)):
raise ProfileNotConfigured
try:
return apps.get_model(settings.ACCOUNTS_PROFILE_MODEL)
except ValueError:
raise ImproperlyConfigured(u"ACCOUNTS_PROFILE_MODEL must be of the form 'app_label.model_name'")
except LookupError:
raise ImproperlyConfigured((u"ACCOUNTS_PROFILE_MODEL refers to model '%s' that has not been installed" % settings.ACCOUNTS_PROFILE_MODEL))
| Returns the Mezzanine profile model, defined in
``settings.ACCOUNTS_PROFILE_MODEL``, or ``None`` if no profile
model is configured. | returns the mezzanine profile model , defined in settings . accounts _ profile _ model , or none if no profile model is configured . | Question:
What does this function do?
Code:
def get_profile_model():
if (not getattr(settings, u'ACCOUNTS_PROFILE_MODEL', None)):
raise ProfileNotConfigured
try:
return apps.get_model(settings.ACCOUNTS_PROFILE_MODEL)
except ValueError:
raise ImproperlyConfigured(u"ACCOUNTS_PROFILE_MODEL must be of the form 'app_label.model_name'")
except LookupError:
raise ImproperlyConfigured((u"ACCOUNTS_PROFILE_MODEL refers to model '%s' that has not been installed" % settings.ACCOUNTS_PROFILE_MODEL))
|
null | null | null | What does this function do? | def _is_author(cc_content, context):
return (context['cc_requester']['id'] == cc_content['user_id'])
| null | null | null | Return True if the requester authored the given content, False otherwise | pcsd | def is author cc content context return context['cc requester']['id'] == cc content['user id'] | 8785 | def _is_author(cc_content, context):
return (context['cc_requester']['id'] == cc_content['user_id'])
| Return True if the requester authored the given content, False otherwise | return true if the requester authored the given content , false otherwise | Question:
What does this function do?
Code:
def _is_author(cc_content, context):
return (context['cc_requester']['id'] == cc_content['user_id'])
|
null | null | null | What does this function do? | def location_contact():
return s3_rest_controller(hide_filter=False)
| null | null | null | RESTful CRUD controller for Community Contacts | pcsd | def location contact return s3 rest controller hide filter=False | 8786 | def location_contact():
return s3_rest_controller(hide_filter=False)
| RESTful CRUD controller for Community Contacts | restful crud controller for community contacts | Question:
What does this function do?
Code:
def location_contact():
return s3_rest_controller(hide_filter=False)
|
null | null | null | What does this function do? | def clear_session(request, *names):
for name in names:
try:
del request.session[name]
except KeyError:
pass
| null | null | null | Removes values for the given session variables names
if they exist. | pcsd | def clear session request *names for name in names try del request session[name] except Key Error pass | 8802 | def clear_session(request, *names):
for name in names:
try:
del request.session[name]
except KeyError:
pass
| Removes values for the given session variables names
if they exist. | removes values for the given session variables names if they exist . | Question:
What does this function do?
Code:
def clear_session(request, *names):
for name in names:
try:
del request.session[name]
except KeyError:
pass
|
null | null | null | What does this function do? | def getCraftSequence():
return 'carve scale bottom preface widen inset fill multiply temperature raft skirt speed chamber tower jitter clip smooth stretch skin comb cool hop wipe oozebane dwindle splodge home lash fillet limit unpause dimension alteration export'.split()
| null | null | null | Get the extrusion craft sequence. | pcsd | def get Craft Sequence return 'carve scale bottom preface widen inset fill multiply temperature raft skirt speed chamber tower jitter clip smooth stretch skin comb cool hop wipe oozebane dwindle splodge home lash fillet limit unpause dimension alteration export' split | 8809 | def getCraftSequence():
return 'carve scale bottom preface widen inset fill multiply temperature raft skirt speed chamber tower jitter clip smooth stretch skin comb cool hop wipe oozebane dwindle splodge home lash fillet limit unpause dimension alteration export'.split()
| Get the extrusion craft sequence. | get the extrusion craft sequence . | Question:
What does this function do?
Code:
def getCraftSequence():
return 'carve scale bottom preface widen inset fill multiply temperature raft skirt speed chamber tower jitter clip smooth stretch skin comb cool hop wipe oozebane dwindle splodge home lash fillet limit unpause dimension alteration export'.split()
|
null | null | null | What does this function do? | @bp.route('/user/<int:uid>', methods=['GET', 'POST'])
@require_admin
def user(uid):
user = Account.query.get_or_404(uid)
form = UserForm(obj=user)
if form.validate_on_submit():
form.populate_obj(user)
user.save()
return redirect(url_for('.user', uid=uid))
return render_template('admin/user.html', form=form, user=user)
| null | null | null | Edit a specified user. | pcsd | @bp route '/user/<int uid>' methods=['GET' 'POST'] @require admin def user uid user = Account query get or 404 uid form = User Form obj=user if form validate on submit form populate obj user user save return redirect url for ' user' uid=uid return render template 'admin/user html' form=form user=user | 8813 | @bp.route('/user/<int:uid>', methods=['GET', 'POST'])
@require_admin
def user(uid):
user = Account.query.get_or_404(uid)
form = UserForm(obj=user)
if form.validate_on_submit():
form.populate_obj(user)
user.save()
return redirect(url_for('.user', uid=uid))
return render_template('admin/user.html', form=form, user=user)
| Edit a specified user. | edit a specified user . | Question:
What does this function do?
Code:
@bp.route('/user/<int:uid>', methods=['GET', 'POST'])
@require_admin
def user(uid):
user = Account.query.get_or_404(uid)
form = UserForm(obj=user)
if form.validate_on_submit():
form.populate_obj(user)
user.save()
return redirect(url_for('.user', uid=uid))
return render_template('admin/user.html', form=form, user=user)
|
null | null | null | What does this function do? | def parse_options(parser, args):
(options, args) = parser.parse_args(args)
if (not args):
parser.print_usage()
raise SystemExit(1)
if (args[0] not in ('start', 'stop', 'status')):
parser.print_usage()
raise SystemExit(1)
return (options, args)
| null | null | null | Parse command line options and print usage message if no arguments were
provided for the command. | pcsd | def parse options parser args options args = parser parse args args if not args parser print usage raise System Exit 1 if args[0] not in 'start' 'stop' 'status' parser print usage raise System Exit 1 return options args | 8815 | def parse_options(parser, args):
(options, args) = parser.parse_args(args)
if (not args):
parser.print_usage()
raise SystemExit(1)
if (args[0] not in ('start', 'stop', 'status')):
parser.print_usage()
raise SystemExit(1)
return (options, args)
| Parse command line options and print usage message if no arguments were
provided for the command. | parse command line options and print usage message if no arguments were provided for the command . | Question:
What does this function do?
Code:
def parse_options(parser, args):
(options, args) = parser.parse_args(args)
if (not args):
parser.print_usage()
raise SystemExit(1)
if (args[0] not in ('start', 'stop', 'status')):
parser.print_usage()
raise SystemExit(1)
return (options, args)
|
null | null | null | What does this function do? | @pytest.mark.network
def test_require_file_from_url():
from fabtools.require import file as require_file
try:
require_file(url='http://www.google.com/robots.txt')
assert is_file('robots.txt')
finally:
run('rm -f robots.txt')
| null | null | null | Require that a file exists, whose contents should come from a URL | pcsd | @pytest mark network def test require file from url from fabtools require import file as require file try require file url='http //www google com/robots txt' assert is file 'robots txt' finally run 'rm -f robots txt' | 8822 | @pytest.mark.network
def test_require_file_from_url():
from fabtools.require import file as require_file
try:
require_file(url='http://www.google.com/robots.txt')
assert is_file('robots.txt')
finally:
run('rm -f robots.txt')
| Require that a file exists, whose contents should come from a URL | require that a file exists , whose contents should come from a url | Question:
What does this function do?
Code:
@pytest.mark.network
def test_require_file_from_url():
from fabtools.require import file as require_file
try:
require_file(url='http://www.google.com/robots.txt')
assert is_file('robots.txt')
finally:
run('rm -f robots.txt')
|
null | null | null | What does this function do? | def addBevelGear(derivation, extrudeDerivation, pitchRadius, positives, teeth, vector3GearProfile):
totalPitchRadius = (derivation.pitchRadiusGear + derivation.pitchRadius)
totalTeeth = (derivation.teethPinion + derivation.teethGear)
portionDirections = extrude.getSpacedPortionDirections(extrudeDerivation.interpolationDictionary)
loopLists = extrude.getLoopListsByPath(extrudeDerivation, None, vector3GearProfile[0], portionDirections)
firstLoopList = loopLists[0]
gearOverPinion = (float((totalTeeth - teeth)) / float(teeth))
thirdLayerThickness = (0.33333333333 * evaluate.getLayerThickness(derivation.xmlElement))
pitchRadian = math.atan((math.sin(derivation.operatingRadian) / (gearOverPinion + math.cos(derivation.operatingRadian))))
coneDistance = (pitchRadius / math.sin(pitchRadian))
apex = Vector3(0.0, 0.0, math.sqrt(((coneDistance * coneDistance) - (pitchRadius * pitchRadius))))
cosPitch = (apex.z / coneDistance)
sinPitch = math.sin(pitchRadian)
for loop in firstLoopList:
for point in loop:
alongWay = (point.z / coneDistance)
oneMinusAlongWay = (1.0 - alongWay)
pointComplex = point.dropAxis()
pointComplexLength = abs(pointComplex)
deltaRadius = (pointComplexLength - pitchRadius)
cosDeltaRadius = (cosPitch * deltaRadius)
sinDeltaRadius = (sinPitch * deltaRadius)
pointComplex *= ((cosDeltaRadius + pitchRadius) / pointComplexLength)
point.x = pointComplex.real
point.y = pointComplex.imag
point.z += sinDeltaRadius
point.x *= oneMinusAlongWay
point.y *= oneMinusAlongWay
addBottomLoop((- thirdLayerThickness), firstLoopList)
topLoop = firstLoopList[(-1)]
topAddition = []
topZ = (euclidean.getTopPath(topLoop) + thirdLayerThickness)
oldIndex = topLoop[(-1)].index
for point in topLoop:
oldIndex += 1
topAddition.append(Vector3Index(oldIndex, (0.8 * point.x), (0.8 * point.y), topZ))
firstLoopList.append(topAddition)
translation = Vector3(0.0, 0.0, (- euclidean.getBottomPaths(firstLoopList)))
euclidean.translateVector3Paths(firstLoopList, translation)
geometryOutput = trianglemesh.getPillarsOutput(loopLists)
positives.append(geometryOutput)
| null | null | null | Get extrude output for a cylinder gear. | pcsd | def add Bevel Gear derivation extrude Derivation pitch Radius positives teeth vector3Gear Profile total Pitch Radius = derivation pitch Radius Gear + derivation pitch Radius total Teeth = derivation teeth Pinion + derivation teeth Gear portion Directions = extrude get Spaced Portion Directions extrude Derivation interpolation Dictionary loop Lists = extrude get Loop Lists By Path extrude Derivation None vector3Gear Profile[0] portion Directions first Loop List = loop Lists[0] gear Over Pinion = float total Teeth - teeth / float teeth third Layer Thickness = 0 33333333333 * evaluate get Layer Thickness derivation xml Element pitch Radian = math atan math sin derivation operating Radian / gear Over Pinion + math cos derivation operating Radian cone Distance = pitch Radius / math sin pitch Radian apex = Vector3 0 0 0 0 math sqrt cone Distance * cone Distance - pitch Radius * pitch Radius cos Pitch = apex z / cone Distance sin Pitch = math sin pitch Radian for loop in first Loop List for point in loop along Way = point z / cone Distance one Minus Along Way = 1 0 - along Way point Complex = point drop Axis point Complex Length = abs point Complex delta Radius = point Complex Length - pitch Radius cos Delta Radius = cos Pitch * delta Radius sin Delta Radius = sin Pitch * delta Radius point Complex *= cos Delta Radius + pitch Radius / point Complex Length point x = point Complex real point y = point Complex imag point z += sin Delta Radius point x *= one Minus Along Way point y *= one Minus Along Way add Bottom Loop - third Layer Thickness first Loop List top Loop = first Loop List[ -1 ] top Addition = [] top Z = euclidean get Top Path top Loop + third Layer Thickness old Index = top Loop[ -1 ] index for point in top Loop old Index += 1 top Addition append Vector3Index old Index 0 8 * point x 0 8 * point y top Z first Loop List append top Addition translation = Vector3 0 0 0 0 - euclidean get Bottom Paths first Loop List euclidean translate Vector3Paths first Loop List translation geometry Output = trianglemesh get Pillars Output loop Lists positives append geometry Output | 8827 | def addBevelGear(derivation, extrudeDerivation, pitchRadius, positives, teeth, vector3GearProfile):
totalPitchRadius = (derivation.pitchRadiusGear + derivation.pitchRadius)
totalTeeth = (derivation.teethPinion + derivation.teethGear)
portionDirections = extrude.getSpacedPortionDirections(extrudeDerivation.interpolationDictionary)
loopLists = extrude.getLoopListsByPath(extrudeDerivation, None, vector3GearProfile[0], portionDirections)
firstLoopList = loopLists[0]
gearOverPinion = (float((totalTeeth - teeth)) / float(teeth))
thirdLayerThickness = (0.33333333333 * evaluate.getLayerThickness(derivation.xmlElement))
pitchRadian = math.atan((math.sin(derivation.operatingRadian) / (gearOverPinion + math.cos(derivation.operatingRadian))))
coneDistance = (pitchRadius / math.sin(pitchRadian))
apex = Vector3(0.0, 0.0, math.sqrt(((coneDistance * coneDistance) - (pitchRadius * pitchRadius))))
cosPitch = (apex.z / coneDistance)
sinPitch = math.sin(pitchRadian)
for loop in firstLoopList:
for point in loop:
alongWay = (point.z / coneDistance)
oneMinusAlongWay = (1.0 - alongWay)
pointComplex = point.dropAxis()
pointComplexLength = abs(pointComplex)
deltaRadius = (pointComplexLength - pitchRadius)
cosDeltaRadius = (cosPitch * deltaRadius)
sinDeltaRadius = (sinPitch * deltaRadius)
pointComplex *= ((cosDeltaRadius + pitchRadius) / pointComplexLength)
point.x = pointComplex.real
point.y = pointComplex.imag
point.z += sinDeltaRadius
point.x *= oneMinusAlongWay
point.y *= oneMinusAlongWay
addBottomLoop((- thirdLayerThickness), firstLoopList)
topLoop = firstLoopList[(-1)]
topAddition = []
topZ = (euclidean.getTopPath(topLoop) + thirdLayerThickness)
oldIndex = topLoop[(-1)].index
for point in topLoop:
oldIndex += 1
topAddition.append(Vector3Index(oldIndex, (0.8 * point.x), (0.8 * point.y), topZ))
firstLoopList.append(topAddition)
translation = Vector3(0.0, 0.0, (- euclidean.getBottomPaths(firstLoopList)))
euclidean.translateVector3Paths(firstLoopList, translation)
geometryOutput = trianglemesh.getPillarsOutput(loopLists)
positives.append(geometryOutput)
| Get extrude output for a cylinder gear. | get extrude output for a cylinder gear . | Question:
What does this function do?
Code:
def addBevelGear(derivation, extrudeDerivation, pitchRadius, positives, teeth, vector3GearProfile):
totalPitchRadius = (derivation.pitchRadiusGear + derivation.pitchRadius)
totalTeeth = (derivation.teethPinion + derivation.teethGear)
portionDirections = extrude.getSpacedPortionDirections(extrudeDerivation.interpolationDictionary)
loopLists = extrude.getLoopListsByPath(extrudeDerivation, None, vector3GearProfile[0], portionDirections)
firstLoopList = loopLists[0]
gearOverPinion = (float((totalTeeth - teeth)) / float(teeth))
thirdLayerThickness = (0.33333333333 * evaluate.getLayerThickness(derivation.xmlElement))
pitchRadian = math.atan((math.sin(derivation.operatingRadian) / (gearOverPinion + math.cos(derivation.operatingRadian))))
coneDistance = (pitchRadius / math.sin(pitchRadian))
apex = Vector3(0.0, 0.0, math.sqrt(((coneDistance * coneDistance) - (pitchRadius * pitchRadius))))
cosPitch = (apex.z / coneDistance)
sinPitch = math.sin(pitchRadian)
for loop in firstLoopList:
for point in loop:
alongWay = (point.z / coneDistance)
oneMinusAlongWay = (1.0 - alongWay)
pointComplex = point.dropAxis()
pointComplexLength = abs(pointComplex)
deltaRadius = (pointComplexLength - pitchRadius)
cosDeltaRadius = (cosPitch * deltaRadius)
sinDeltaRadius = (sinPitch * deltaRadius)
pointComplex *= ((cosDeltaRadius + pitchRadius) / pointComplexLength)
point.x = pointComplex.real
point.y = pointComplex.imag
point.z += sinDeltaRadius
point.x *= oneMinusAlongWay
point.y *= oneMinusAlongWay
addBottomLoop((- thirdLayerThickness), firstLoopList)
topLoop = firstLoopList[(-1)]
topAddition = []
topZ = (euclidean.getTopPath(topLoop) + thirdLayerThickness)
oldIndex = topLoop[(-1)].index
for point in topLoop:
oldIndex += 1
topAddition.append(Vector3Index(oldIndex, (0.8 * point.x), (0.8 * point.y), topZ))
firstLoopList.append(topAddition)
translation = Vector3(0.0, 0.0, (- euclidean.getBottomPaths(firstLoopList)))
euclidean.translateVector3Paths(firstLoopList, translation)
geometryOutput = trianglemesh.getPillarsOutput(loopLists)
positives.append(geometryOutput)
|
null | null | null | What does this function do? | @utils.arg('image', metavar='<image>', help=_('Name or ID of image.'))
@utils.arg('action', metavar='<action>', choices=['set', 'delete'], help=_("Actions: 'set' or 'delete'."))
@utils.arg('metadata', metavar='<key=value>', nargs='+', action='append', default=[], help=_('Metadata to add/update or delete (only key is necessary on delete).'))
@deprecated_image
def do_image_meta(cs, args):
image = _find_image(cs, args.image)
metadata = _extract_metadata(args)
if (args.action == 'set'):
cs.images.set_meta(image, metadata)
elif (args.action == 'delete'):
cs.images.delete_meta(image, metadata.keys())
| null | null | null | Set or delete metadata on an image. | pcsd | @utils arg 'image' metavar='<image>' help= 'Name or ID of image ' @utils arg 'action' metavar='<action>' choices=['set' 'delete'] help= "Actions 'set' or 'delete' " @utils arg 'metadata' metavar='<key=value>' nargs='+' action='append' default=[] help= 'Metadata to add/update or delete only key is necessary on delete ' @deprecated image def do image meta cs args image = find image cs args image metadata = extract metadata args if args action == 'set' cs images set meta image metadata elif args action == 'delete' cs images delete meta image metadata keys | 8832 | @utils.arg('image', metavar='<image>', help=_('Name or ID of image.'))
@utils.arg('action', metavar='<action>', choices=['set', 'delete'], help=_("Actions: 'set' or 'delete'."))
@utils.arg('metadata', metavar='<key=value>', nargs='+', action='append', default=[], help=_('Metadata to add/update or delete (only key is necessary on delete).'))
@deprecated_image
def do_image_meta(cs, args):
image = _find_image(cs, args.image)
metadata = _extract_metadata(args)
if (args.action == 'set'):
cs.images.set_meta(image, metadata)
elif (args.action == 'delete'):
cs.images.delete_meta(image, metadata.keys())
| Set or delete metadata on an image. | set or delete metadata on an image . | Question:
What does this function do?
Code:
@utils.arg('image', metavar='<image>', help=_('Name or ID of image.'))
@utils.arg('action', metavar='<action>', choices=['set', 'delete'], help=_("Actions: 'set' or 'delete'."))
@utils.arg('metadata', metavar='<key=value>', nargs='+', action='append', default=[], help=_('Metadata to add/update or delete (only key is necessary on delete).'))
@deprecated_image
def do_image_meta(cs, args):
image = _find_image(cs, args.image)
metadata = _extract_metadata(args)
if (args.action == 'set'):
cs.images.set_meta(image, metadata)
elif (args.action == 'delete'):
cs.images.delete_meta(image, metadata.keys())
|
null | null | null | What does this function do? | def get_deprecated_login_lock_out_by_combination_browser_user_agent():
return AUTH.LOGIN_LOCK_OUT_BY_COMBINATION_BROWSER_USER_AGENT_AND_IP.get()
| null | null | null | Return value of deprecated LOGIN_LOCK_OUT_BY_COMBINATION_BROWSER_USER_AGENT_AND_IP config | pcsd | def get deprecated login lock out by combination browser user agent return AUTH LOGIN LOCK OUT BY COMBINATION BROWSER USER AGENT AND IP get | 8837 | def get_deprecated_login_lock_out_by_combination_browser_user_agent():
return AUTH.LOGIN_LOCK_OUT_BY_COMBINATION_BROWSER_USER_AGENT_AND_IP.get()
| Return value of deprecated LOGIN_LOCK_OUT_BY_COMBINATION_BROWSER_USER_AGENT_AND_IP config | return value of deprecated login _ lock _ out _ by _ combination _ browser _ user _ agent _ and _ ip config | Question:
What does this function do?
Code:
def get_deprecated_login_lock_out_by_combination_browser_user_agent():
return AUTH.LOGIN_LOCK_OUT_BY_COMBINATION_BROWSER_USER_AGENT_AND_IP.get()
|
null | null | null | What does this function do? | def create():
use_app(call_reuse=False)
return default_app.create()
| null | null | null | Create the native application. | pcsd | def create use app call reuse=False return default app create | 8840 | def create():
use_app(call_reuse=False)
return default_app.create()
| Create the native application. | create the native application . | Question:
What does this function do?
Code:
def create():
use_app(call_reuse=False)
return default_app.create()
|
null | null | null | What does this function do? | def getInstanceDetails(api, server):
instance = {'id': server['LINODEID'], 'name': server['LABEL'], 'public': [], 'private': []}
for ip in api.linode_ip_list(LinodeId=server['LINODEID']):
if (ip['ISPUBLIC'] and ('ipv4' not in instance)):
instance['ipv4'] = ip['IPADDRESS']
instance['fqdn'] = ip['RDNS_NAME']
if ip['ISPUBLIC']:
instance['public'].append({'ipv4': ip['IPADDRESS'], 'fqdn': ip['RDNS_NAME'], 'ip_id': ip['IPADDRESSID']})
else:
instance['private'].append({'ipv4': ip['IPADDRESS'], 'fqdn': ip['RDNS_NAME'], 'ip_id': ip['IPADDRESSID']})
return instance
| null | null | null | Return the details of an instance, populating IPs, etc. | pcsd | def get Instance Details api server instance = {'id' server['LINODEID'] 'name' server['LABEL'] 'public' [] 'private' []} for ip in api linode ip list Linode Id=server['LINODEID'] if ip['ISPUBLIC'] and 'ipv4' not in instance instance['ipv4'] = ip['IPADDRESS'] instance['fqdn'] = ip['RDNS NAME'] if ip['ISPUBLIC'] instance['public'] append {'ipv4' ip['IPADDRESS'] 'fqdn' ip['RDNS NAME'] 'ip id' ip['IPADDRESSID']} else instance['private'] append {'ipv4' ip['IPADDRESS'] 'fqdn' ip['RDNS NAME'] 'ip id' ip['IPADDRESSID']} return instance | 8846 | def getInstanceDetails(api, server):
instance = {'id': server['LINODEID'], 'name': server['LABEL'], 'public': [], 'private': []}
for ip in api.linode_ip_list(LinodeId=server['LINODEID']):
if (ip['ISPUBLIC'] and ('ipv4' not in instance)):
instance['ipv4'] = ip['IPADDRESS']
instance['fqdn'] = ip['RDNS_NAME']
if ip['ISPUBLIC']:
instance['public'].append({'ipv4': ip['IPADDRESS'], 'fqdn': ip['RDNS_NAME'], 'ip_id': ip['IPADDRESSID']})
else:
instance['private'].append({'ipv4': ip['IPADDRESS'], 'fqdn': ip['RDNS_NAME'], 'ip_id': ip['IPADDRESSID']})
return instance
| Return the details of an instance, populating IPs, etc. | return the details of an instance , populating ips , etc . | Question:
What does this function do?
Code:
def getInstanceDetails(api, server):
instance = {'id': server['LINODEID'], 'name': server['LABEL'], 'public': [], 'private': []}
for ip in api.linode_ip_list(LinodeId=server['LINODEID']):
if (ip['ISPUBLIC'] and ('ipv4' not in instance)):
instance['ipv4'] = ip['IPADDRESS']
instance['fqdn'] = ip['RDNS_NAME']
if ip['ISPUBLIC']:
instance['public'].append({'ipv4': ip['IPADDRESS'], 'fqdn': ip['RDNS_NAME'], 'ip_id': ip['IPADDRESSID']})
else:
instance['private'].append({'ipv4': ip['IPADDRESS'], 'fqdn': ip['RDNS_NAME'], 'ip_id': ip['IPADDRESSID']})
return instance
|
null | null | null | What does this function do? | def _old_process_multipart(entity):
process_multipart(entity)
params = entity.params
for part in entity.parts:
if (part.name is None):
key = u'parts'
else:
key = part.name
if (part.filename is None):
value = part.fullvalue()
else:
value = part
if (key in params):
if (not isinstance(params[key], list)):
params[key] = [params[key]]
params[key].append(value)
else:
params[key] = value
| null | null | null | The behavior of 3.2 and lower. Deprecated and will be changed in 3.3. | pcsd | def old process multipart entity process multipart entity params = entity params for part in entity parts if part name is None key = u'parts' else key = part name if part filename is None value = part fullvalue else value = part if key in params if not isinstance params[key] list params[key] = [params[key]] params[key] append value else params[key] = value | 8853 | def _old_process_multipart(entity):
process_multipart(entity)
params = entity.params
for part in entity.parts:
if (part.name is None):
key = u'parts'
else:
key = part.name
if (part.filename is None):
value = part.fullvalue()
else:
value = part
if (key in params):
if (not isinstance(params[key], list)):
params[key] = [params[key]]
params[key].append(value)
else:
params[key] = value
| The behavior of 3.2 and lower. Deprecated and will be changed in 3.3. | the behavior of 3 . 2 and lower . | Question:
What does this function do?
Code:
def _old_process_multipart(entity):
process_multipart(entity)
params = entity.params
for part in entity.parts:
if (part.name is None):
key = u'parts'
else:
key = part.name
if (part.filename is None):
value = part.fullvalue()
else:
value = part
if (key in params):
if (not isinstance(params[key], list)):
params[key] = [params[key]]
params[key].append(value)
else:
params[key] = value
|
null | null | null | What does this function do? | @app.route('/about', methods=['GET'])
def about():
return render('about.html')
| null | null | null | Render about page | pcsd | @app route '/about' methods=['GET'] def about return render 'about html' | 8858 | @app.route('/about', methods=['GET'])
def about():
return render('about.html')
| Render about page | render about page | Question:
What does this function do?
Code:
@app.route('/about', methods=['GET'])
def about():
return render('about.html')
|
null | null | null | What does this function do? | def _check_upload_response_headers(headers, body):
if ('status' not in headers):
try:
d = jsonutils.loads(body)
if (('image' in d) and ('status' in d['image'])):
return
except Exception:
raise exception.UploadException(body)
| null | null | null | Check that the headers of an upload are reasonable.
headers: the headers from the upload
body: the body from the upload | pcsd | def check upload response headers headers body if 'status' not in headers try d = jsonutils loads body if 'image' in d and 'status' in d['image'] return except Exception raise exception Upload Exception body | 8859 | def _check_upload_response_headers(headers, body):
if ('status' not in headers):
try:
d = jsonutils.loads(body)
if (('image' in d) and ('status' in d['image'])):
return
except Exception:
raise exception.UploadException(body)
| Check that the headers of an upload are reasonable.
headers: the headers from the upload
body: the body from the upload | check that the headers of an upload are reasonable . | Question:
What does this function do?
Code:
def _check_upload_response_headers(headers, body):
if ('status' not in headers):
try:
d = jsonutils.loads(body)
if (('image' in d) and ('status' in d['image'])):
return
except Exception:
raise exception.UploadException(body)
|
null | null | null | What does this function do? | def get_config():
config = tools.get_config_file()
session_config = session.get_session_config()
for config_key in config:
session_value = session_config.get(config_key)
if ((session_value is False) or session_value):
config[config_key] = session_value
return config
| null | null | null | Returns either module config or file config. | pcsd | def get config config = tools get config file session config = session get session config for config key in config session value = session config get config key if session value is False or session value config[config key] = session value return config | 8863 | def get_config():
config = tools.get_config_file()
session_config = session.get_session_config()
for config_key in config:
session_value = session_config.get(config_key)
if ((session_value is False) or session_value):
config[config_key] = session_value
return config
| Returns either module config or file config. | returns either module config or file config . | Question:
What does this function do?
Code:
def get_config():
config = tools.get_config_file()
session_config = session.get_session_config()
for config_key in config:
session_value = session_config.get(config_key)
if ((session_value is False) or session_value):
config[config_key] = session_value
return config
|
null | null | null | What does this function do? | def on_report_to_master(client_id, data):
data['content-length'] = stats['content-length']
stats['content-length'] = 0
| null | null | null | This event is triggered on the slave instances every time a stats report is
to be sent to the locust master. It will allow us to add our extra content-length
data to the dict that is being sent, and then we clear the local stats in the slave. | pcsd | def on report to master client id data data['content-length'] = stats['content-length'] stats['content-length'] = 0 | 8877 | def on_report_to_master(client_id, data):
data['content-length'] = stats['content-length']
stats['content-length'] = 0
| This event is triggered on the slave instances every time a stats report is
to be sent to the locust master. It will allow us to add our extra content-length
data to the dict that is being sent, and then we clear the local stats in the slave. | this event is triggered on the slave instances every time a stats report is to be sent to the locust master . | Question:
What does this function do?
Code:
def on_report_to_master(client_id, data):
data['content-length'] = stats['content-length']
stats['content-length'] = 0
|
null | null | null | What does this function do? | def local_open(url):
(scheme, server, path, param, query, frag) = urlparse.urlparse(url)
filename = urllib2.url2pathname(path)
if os.path.isfile(filename):
return urllib2.urlopen(url)
elif (path.endswith('/') and os.path.isdir(filename)):
files = []
for f in os.listdir(filename):
if (f == 'index.html'):
body = open(os.path.join(filename, f), 'rb').read()
break
elif os.path.isdir(os.path.join(filename, f)):
f += '/'
files.append(('<a href=%r>%s</a>' % (f, f)))
else:
body = (('<html><head><title>%s</title>' % url) + ('</head><body>%s</body></html>' % '\n'.join(files)))
(status, message) = (200, 'OK')
else:
(status, message, body) = (404, 'Path not found', 'Not found')
return urllib2.HTTPError(url, status, message, {'content-type': 'text/html'}, cStringIO.StringIO(body))
| null | null | null | Read a local path, with special support for directories | pcsd | def local open url scheme server path param query frag = urlparse urlparse url filename = urllib2 url2pathname path if os path isfile filename return urllib2 urlopen url elif path endswith '/' and os path isdir filename files = [] for f in os listdir filename if f == 'index html' body = open os path join filename f 'rb' read break elif os path isdir os path join filename f f += '/' files append '<a href=%r>%s</a>' % f f else body = '<html><head><title>%s</title>' % url + '</head><body>%s</body></html>' % ' ' join files status message = 200 'OK' else status message body = 404 'Path not found' 'Not found' return urllib2 HTTP Error url status message {'content-type' 'text/html'} c String IO String IO body | 8892 | def local_open(url):
(scheme, server, path, param, query, frag) = urlparse.urlparse(url)
filename = urllib2.url2pathname(path)
if os.path.isfile(filename):
return urllib2.urlopen(url)
elif (path.endswith('/') and os.path.isdir(filename)):
files = []
for f in os.listdir(filename):
if (f == 'index.html'):
body = open(os.path.join(filename, f), 'rb').read()
break
elif os.path.isdir(os.path.join(filename, f)):
f += '/'
files.append(('<a href=%r>%s</a>' % (f, f)))
else:
body = (('<html><head><title>%s</title>' % url) + ('</head><body>%s</body></html>' % '\n'.join(files)))
(status, message) = (200, 'OK')
else:
(status, message, body) = (404, 'Path not found', 'Not found')
return urllib2.HTTPError(url, status, message, {'content-type': 'text/html'}, cStringIO.StringIO(body))
| Read a local path, with special support for directories | read a local path , with special support for directories | Question:
What does this function do?
Code:
def local_open(url):
(scheme, server, path, param, query, frag) = urlparse.urlparse(url)
filename = urllib2.url2pathname(path)
if os.path.isfile(filename):
return urllib2.urlopen(url)
elif (path.endswith('/') and os.path.isdir(filename)):
files = []
for f in os.listdir(filename):
if (f == 'index.html'):
body = open(os.path.join(filename, f), 'rb').read()
break
elif os.path.isdir(os.path.join(filename, f)):
f += '/'
files.append(('<a href=%r>%s</a>' % (f, f)))
else:
body = (('<html><head><title>%s</title>' % url) + ('</head><body>%s</body></html>' % '\n'.join(files)))
(status, message) = (200, 'OK')
else:
(status, message, body) = (404, 'Path not found', 'Not found')
return urllib2.HTTPError(url, status, message, {'content-type': 'text/html'}, cStringIO.StringIO(body))
|
null | null | null | What does this function do? | def require_support_permission(func):
@wraps(func)
def inner(request, *args, **kwargs):
if has_access(request.user, 'support', 'global'):
return func(request, *args, **kwargs)
else:
return HttpResponseForbidden()
return login_required(inner)
| null | null | null | View decorator that requires the user to have permission to use the support UI. | pcsd | def require support permission func @wraps func def inner request *args **kwargs if has access request user 'support' 'global' return func request *args **kwargs else return Http Response Forbidden return login required inner | 8895 | def require_support_permission(func):
@wraps(func)
def inner(request, *args, **kwargs):
if has_access(request.user, 'support', 'global'):
return func(request, *args, **kwargs)
else:
return HttpResponseForbidden()
return login_required(inner)
| View decorator that requires the user to have permission to use the support UI. | view decorator that requires the user to have permission to use the support ui . | Question:
What does this function do?
Code:
def require_support_permission(func):
@wraps(func)
def inner(request, *args, **kwargs):
if has_access(request.user, 'support', 'global'):
return func(request, *args, **kwargs)
else:
return HttpResponseForbidden()
return login_required(inner)
|
null | null | null | What does this function do? | def is_image_visible(context, image, status=None):
if context.is_admin:
return True
if (image['owner'] is None):
return True
if (image['visibility'] in ['public', 'community']):
return True
if (context.owner is not None):
if (context.owner == image['owner']):
return True
if (status == 'all'):
status = None
if ('shared' == image['visibility']):
members = image_member_find(context, image_id=image['id'], member=context.owner, status=status)
if members:
return True
return False
| null | null | null | Return True if the image is visible in this context. | pcsd | def is image visible context image status=None if context is admin return True if image['owner'] is None return True if image['visibility'] in ['public' 'community'] return True if context owner is not None if context owner == image['owner'] return True if status == 'all' status = None if 'shared' == image['visibility'] members = image member find context image id=image['id'] member=context owner status=status if members return True return False | 8898 | def is_image_visible(context, image, status=None):
if context.is_admin:
return True
if (image['owner'] is None):
return True
if (image['visibility'] in ['public', 'community']):
return True
if (context.owner is not None):
if (context.owner == image['owner']):
return True
if (status == 'all'):
status = None
if ('shared' == image['visibility']):
members = image_member_find(context, image_id=image['id'], member=context.owner, status=status)
if members:
return True
return False
| Return True if the image is visible in this context. | return true if the image is visible in this context . | Question:
What does this function do?
Code:
def is_image_visible(context, image, status=None):
if context.is_admin:
return True
if (image['owner'] is None):
return True
if (image['visibility'] in ['public', 'community']):
return True
if (context.owner is not None):
if (context.owner == image['owner']):
return True
if (status == 'all'):
status = None
if ('shared' == image['visibility']):
members = image_member_find(context, image_id=image['id'], member=context.owner, status=status)
if members:
return True
return False
|
null | null | null | What does this function do? | @utils.arg('monitor_id', metavar='<monitor-id>', help='ID of the monitor to upload to an image')
@utils.arg('--force', metavar='<True|False>', help="Optional flag to indicate whether to upload a monitor even if it's attached to an instance. (Default=False)", default=False)
@utils.arg('--container-format', metavar='<container-format>', help='Optional type for container format (Default=bare)', default='bare')
@utils.arg('--disk-format', metavar='<disk-format>', help='Optional type for disk format (Default=raw)', default='raw')
@utils.arg('image_name', metavar='<image-name>', help='Name for created image')
@utils.service_type('monitor')
def do_upload_to_image(cs, args):
monitor = _find_monitor(cs, args.monitor_id)
monitor.upload_to_image(args.force, args.image_name, args.container_format, args.disk_format)
| null | null | null | Upload monitor to image service as image. | pcsd | @utils arg 'monitor id' metavar='<monitor-id>' help='ID of the monitor to upload to an image' @utils arg '--force' metavar='<True|False>' help="Optional flag to indicate whether to upload a monitor even if it's attached to an instance Default=False " default=False @utils arg '--container-format' metavar='<container-format>' help='Optional type for container format Default=bare ' default='bare' @utils arg '--disk-format' metavar='<disk-format>' help='Optional type for disk format Default=raw ' default='raw' @utils arg 'image name' metavar='<image-name>' help='Name for created image' @utils service type 'monitor' def do upload to image cs args monitor = find monitor cs args monitor id monitor upload to image args force args image name args container format args disk format | 8903 | @utils.arg('monitor_id', metavar='<monitor-id>', help='ID of the monitor to upload to an image')
@utils.arg('--force', metavar='<True|False>', help="Optional flag to indicate whether to upload a monitor even if it's attached to an instance. (Default=False)", default=False)
@utils.arg('--container-format', metavar='<container-format>', help='Optional type for container format (Default=bare)', default='bare')
@utils.arg('--disk-format', metavar='<disk-format>', help='Optional type for disk format (Default=raw)', default='raw')
@utils.arg('image_name', metavar='<image-name>', help='Name for created image')
@utils.service_type('monitor')
def do_upload_to_image(cs, args):
monitor = _find_monitor(cs, args.monitor_id)
monitor.upload_to_image(args.force, args.image_name, args.container_format, args.disk_format)
| Upload monitor to image service as image. | upload monitor to image service as image . | Question:
What does this function do?
Code:
@utils.arg('monitor_id', metavar='<monitor-id>', help='ID of the monitor to upload to an image')
@utils.arg('--force', metavar='<True|False>', help="Optional flag to indicate whether to upload a monitor even if it's attached to an instance. (Default=False)", default=False)
@utils.arg('--container-format', metavar='<container-format>', help='Optional type for container format (Default=bare)', default='bare')
@utils.arg('--disk-format', metavar='<disk-format>', help='Optional type for disk format (Default=raw)', default='raw')
@utils.arg('image_name', metavar='<image-name>', help='Name for created image')
@utils.service_type('monitor')
def do_upload_to_image(cs, args):
monitor = _find_monitor(cs, args.monitor_id)
monitor.upload_to_image(args.force, args.image_name, args.container_format, args.disk_format)
|
null | null | null | What does this function do? | @pytest.mark.parametrize('parallel', [True, False])
def test_rstrip_whitespace(parallel, read_basic):
text = ' 1 ,2 DCTB ,3 \nA DCTB ,B ,C DCTB DCTB \n DCTB a ,b , c \n'
table = read_basic(text, delimiter=',', parallel=parallel)
expected = Table([['A', 'a'], ['B', 'b'], ['C', 'c']], names=('1', '2', '3'))
assert_table_equal(table, expected)
| null | null | null | Test to make sure the reader ignores whitespace at the end of fields. | pcsd | @pytest mark parametrize 'parallel' [True False] def test rstrip whitespace parallel read basic text = ' 1 2 DCTB 3 A DCTB B C DCTB DCTB DCTB a b c ' table = read basic text delimiter=' ' parallel=parallel expected = Table [['A' 'a'] ['B' 'b'] ['C' 'c']] names= '1' '2' '3' assert table equal table expected | 8904 | @pytest.mark.parametrize('parallel', [True, False])
def test_rstrip_whitespace(parallel, read_basic):
text = ' 1 ,2 DCTB ,3 \nA DCTB ,B ,C DCTB DCTB \n DCTB a ,b , c \n'
table = read_basic(text, delimiter=',', parallel=parallel)
expected = Table([['A', 'a'], ['B', 'b'], ['C', 'c']], names=('1', '2', '3'))
assert_table_equal(table, expected)
| Test to make sure the reader ignores whitespace at the end of fields. | test to make sure the reader ignores whitespace at the end of fields . | Question:
What does this function do?
Code:
@pytest.mark.parametrize('parallel', [True, False])
def test_rstrip_whitespace(parallel, read_basic):
text = ' 1 ,2 DCTB ,3 \nA DCTB ,B ,C DCTB DCTB \n DCTB a ,b , c \n'
table = read_basic(text, delimiter=',', parallel=parallel)
expected = Table([['A', 'a'], ['B', 'b'], ['C', 'c']], names=('1', '2', '3'))
assert_table_equal(table, expected)
|
null | null | null | What does this function do? | def results_extractor(train_obj):
return DD()
| null | null | null | Default results extractor that does nothing. Good for tutorials. | pcsd | def results extractor train obj return DD | 8919 | def results_extractor(train_obj):
return DD()
| Default results extractor that does nothing. Good for tutorials. | default results extractor that does nothing . | Question:
What does this function do?
Code:
def results_extractor(train_obj):
return DD()
|
null | null | null | What does this function do? | def addToThreadsRemove(extrusionHalfWidth, nestedRings, oldOrderedLocation, skein, threadSequence):
while (len(nestedRings) > 0):
getTransferClosestNestedRing(extrusionHalfWidth, nestedRings, oldOrderedLocation, skein, threadSequence)
| null | null | null | Add to threads from the last location from nested rings. | pcsd | def add To Threads Remove extrusion Half Width nested Rings old Ordered Location skein thread Sequence while len nested Rings > 0 get Transfer Closest Nested Ring extrusion Half Width nested Rings old Ordered Location skein thread Sequence | 8925 | def addToThreadsRemove(extrusionHalfWidth, nestedRings, oldOrderedLocation, skein, threadSequence):
while (len(nestedRings) > 0):
getTransferClosestNestedRing(extrusionHalfWidth, nestedRings, oldOrderedLocation, skein, threadSequence)
| Add to threads from the last location from nested rings. | add to threads from the last location from nested rings . | Question:
What does this function do?
Code:
def addToThreadsRemove(extrusionHalfWidth, nestedRings, oldOrderedLocation, skein, threadSequence):
while (len(nestedRings) > 0):
getTransferClosestNestedRing(extrusionHalfWidth, nestedRings, oldOrderedLocation, skein, threadSequence)
|
null | null | null | What does this function do? | def _CopyProperties(target_dict, source_dict):
for (key, value) in source_dict['properties'].items():
assert ((key not in target_dict['properties']) or (target_dict['properties'][key] == value)), (source_dict, target_dict)
target_dict['properties'][key] = deepcopy(value)
| null | null | null | Deep copies properties in source_dict[\'properties\'] to target_dict[\'properties\']. Asserts
if a property of the same name already exists in source_dict[\'properties\'], but has a
different value. | pcsd | def Copy Properties target dict source dict for key value in source dict['properties'] items assert key not in target dict['properties'] or target dict['properties'][key] == value source dict target dict target dict['properties'][key] = deepcopy value | 8927 | def _CopyProperties(target_dict, source_dict):
for (key, value) in source_dict['properties'].items():
assert ((key not in target_dict['properties']) or (target_dict['properties'][key] == value)), (source_dict, target_dict)
target_dict['properties'][key] = deepcopy(value)
| Deep copies properties in source_dict[\'properties\'] to target_dict[\'properties\']. Asserts
if a property of the same name already exists in source_dict[\'properties\'], but has a
different value. | deep copies properties in source _ dict [ properties ] to target _ dict [ properties ] . | Question:
What does this function do?
Code:
def _CopyProperties(target_dict, source_dict):
for (key, value) in source_dict['properties'].items():
assert ((key not in target_dict['properties']) or (target_dict['properties'][key] == value)), (source_dict, target_dict)
target_dict['properties'][key] = deepcopy(value)
|
null | null | null | What does this function do? | def get_edit_filetypes():
pygments_exts = _get_pygments_extensions()
favorite_exts = ['.py', '.R', '.jl', '.ipynb', '.md', '.pyw', '.pyx', '.C', '.CPP']
other_exts = [ext for ext in pygments_exts if (ext not in favorite_exts)]
all_exts = tuple((favorite_exts + other_exts))
text_filetypes = (_('Supported text files'), all_exts)
return ([text_filetypes] + EDIT_FILETYPES)
| null | null | null | Get all file types supported by the Editor | pcsd | def get edit filetypes pygments exts = get pygments extensions favorite exts = [' py' ' R' ' jl' ' ipynb' ' md' ' pyw' ' pyx' ' C' ' CPP'] other exts = [ext for ext in pygments exts if ext not in favorite exts ] all exts = tuple favorite exts + other exts text filetypes = 'Supported text files' all exts return [text filetypes] + EDIT FILETYPES | 8931 | def get_edit_filetypes():
pygments_exts = _get_pygments_extensions()
favorite_exts = ['.py', '.R', '.jl', '.ipynb', '.md', '.pyw', '.pyx', '.C', '.CPP']
other_exts = [ext for ext in pygments_exts if (ext not in favorite_exts)]
all_exts = tuple((favorite_exts + other_exts))
text_filetypes = (_('Supported text files'), all_exts)
return ([text_filetypes] + EDIT_FILETYPES)
| Get all file types supported by the Editor | get all file types supported by the editor | Question:
What does this function do?
Code:
def get_edit_filetypes():
pygments_exts = _get_pygments_extensions()
favorite_exts = ['.py', '.R', '.jl', '.ipynb', '.md', '.pyw', '.pyx', '.C', '.CPP']
other_exts = [ext for ext in pygments_exts if (ext not in favorite_exts)]
all_exts = tuple((favorite_exts + other_exts))
text_filetypes = (_('Supported text files'), all_exts)
return ([text_filetypes] + EDIT_FILETYPES)
|
null | null | null | What does this function do? | def getFirstTranslatorFileNameUnmodified(fileName):
if (fileName != ''):
return fileName
unmodified = getGNUTranslatorFilesUnmodified()
if (len(unmodified) == 0):
print 'There are no unmodified gcode files in this folder.'
return ''
return unmodified[0]
| null | null | null | Get the first file name from the translators in the import plugins folder, if the file name is not already set. | pcsd | def get First Translator File Name Unmodified file Name if file Name != '' return file Name unmodified = get GNU Translator Files Unmodified if len unmodified == 0 print 'There are no unmodified gcode files in this folder ' return '' return unmodified[0] | 8935 | def getFirstTranslatorFileNameUnmodified(fileName):
if (fileName != ''):
return fileName
unmodified = getGNUTranslatorFilesUnmodified()
if (len(unmodified) == 0):
print 'There are no unmodified gcode files in this folder.'
return ''
return unmodified[0]
| Get the first file name from the translators in the import plugins folder, if the file name is not already set. | get the first file name from the translators in the import plugins folder , if the file name is not already set . | Question:
What does this function do?
Code:
def getFirstTranslatorFileNameUnmodified(fileName):
if (fileName != ''):
return fileName
unmodified = getGNUTranslatorFilesUnmodified()
if (len(unmodified) == 0):
print 'There are no unmodified gcode files in this folder.'
return ''
return unmodified[0]
|
null | null | null | What does this function do? | def getNewRepository():
return CarveRepository()
| null | null | null | Get new repository. | pcsd | def get New Repository return Carve Repository | 8947 | def getNewRepository():
return CarveRepository()
| Get new repository. | get new repository . | Question:
What does this function do?
Code:
def getNewRepository():
return CarveRepository()
|
null | null | null | What does this function do? | def current_request():
return getattr(_thread_local, u'request', None)
| null | null | null | Retrieves the request from the current thread. | pcsd | def current request return getattr thread local u'request' None | 8948 | def current_request():
return getattr(_thread_local, u'request', None)
| Retrieves the request from the current thread. | retrieves the request from the current thread . | Question:
What does this function do?
Code:
def current_request():
return getattr(_thread_local, u'request', None)
|
null | null | null | What does this function do? | def identityResponse():
a = TpPd(pd=5)
b = MessageType(mesType=9)
c = MobileId()
packet = ((a / b) / c)
return packet
| null | null | null | IDENTITY RESPONSE Section 9.2.11 | pcsd | def identity Response a = Tp Pd pd=5 b = Message Type mes Type=9 c = Mobile Id packet = a / b / c return packet | 8958 | def identityResponse():
a = TpPd(pd=5)
b = MessageType(mesType=9)
c = MobileId()
packet = ((a / b) / c)
return packet
| IDENTITY RESPONSE Section 9.2.11 | identity response section 9 . 2 . 11 | Question:
What does this function do?
Code:
def identityResponse():
a = TpPd(pd=5)
b = MessageType(mesType=9)
c = MobileId()
packet = ((a / b) / c)
return packet
|
null | null | null | What does this function do? | @require_safe
def remove(request, task_id):
analyses = results_db.analysis.find({'info.id': int(task_id)})
if (analyses.count() > 1):
message = 'Multiple tasks with this ID deleted, thanks for all the fish (the specified analysis was present multiple times in mongo).'
elif (analyses.count() == 1):
message = 'Task deleted, thanks for all the fish.'
if (not analyses.count()):
return render(request, 'error.html', {'error': 'The specified analysis does not exist'})
for analysis in analyses:
if ('file_id' in analysis['target']):
if (results_db.analysis.find({'target.file_id': ObjectId(analysis['target']['file_id'])}).count() == 1):
fs.delete(ObjectId(analysis['target']['file_id']))
for shot in analysis['shots']:
if (results_db.analysis.find({'shots': ObjectId(shot)}).count() == 1):
fs.delete(ObjectId(shot))
if (('pcap_id' in analysis['network']) and (results_db.analysis.find({'network.pcap_id': ObjectId(analysis['network']['pcap_id'])}).count() == 1)):
fs.delete(ObjectId(analysis['network']['pcap_id']))
if (('sorted_pcap_id' in analysis['network']) and (results_db.analysis.find({'network.sorted_pcap_id': ObjectId(analysis['network']['sorted_pcap_id'])}).count() == 1)):
fs.delete(ObjectId(analysis['network']['sorted_pcap_id']))
if (('mitmproxy_id' in analysis['network']) and (results_db.analysis.find({'network.mitmproxy_id': ObjectId(analysis['network']['mitmproxy_id'])}).count() == 1)):
fs.delete(ObjectId(analysis['network']['mitmproxy_id']))
for drop in analysis.get('dropped', []):
if (('object_id' in drop) and (results_db.analysis.find({'dropped.object_id': ObjectId(drop['object_id'])}).count() == 1)):
fs.delete(ObjectId(drop['object_id']))
for process in analysis.get('behavior', {}).get('processes', []):
for call in process['calls']:
results_db.calls.remove({'_id': ObjectId(call)})
results_db.analysis.remove({'_id': ObjectId(analysis['_id'])})
db = Database()
db.delete_task(task_id)
return render(request, 'success.html', {'message': message})
| null | null | null | Remove an analysis.
@todo: remove folder from storage. | pcsd | @require safe def remove request task id analyses = results db analysis find {'info id' int task id } if analyses count > 1 message = 'Multiple tasks with this ID deleted thanks for all the fish the specified analysis was present multiple times in mongo ' elif analyses count == 1 message = 'Task deleted thanks for all the fish ' if not analyses count return render request 'error html' {'error' 'The specified analysis does not exist'} for analysis in analyses if 'file id' in analysis['target'] if results db analysis find {'target file id' Object Id analysis['target']['file id'] } count == 1 fs delete Object Id analysis['target']['file id'] for shot in analysis['shots'] if results db analysis find {'shots' Object Id shot } count == 1 fs delete Object Id shot if 'pcap id' in analysis['network'] and results db analysis find {'network pcap id' Object Id analysis['network']['pcap id'] } count == 1 fs delete Object Id analysis['network']['pcap id'] if 'sorted pcap id' in analysis['network'] and results db analysis find {'network sorted pcap id' Object Id analysis['network']['sorted pcap id'] } count == 1 fs delete Object Id analysis['network']['sorted pcap id'] if 'mitmproxy id' in analysis['network'] and results db analysis find {'network mitmproxy id' Object Id analysis['network']['mitmproxy id'] } count == 1 fs delete Object Id analysis['network']['mitmproxy id'] for drop in analysis get 'dropped' [] if 'object id' in drop and results db analysis find {'dropped object id' Object Id drop['object id'] } count == 1 fs delete Object Id drop['object id'] for process in analysis get 'behavior' {} get 'processes' [] for call in process['calls'] results db calls remove {' id' Object Id call } results db analysis remove {' id' Object Id analysis[' id'] } db = Database db delete task task id return render request 'success html' {'message' message} | 8963 | @require_safe
def remove(request, task_id):
analyses = results_db.analysis.find({'info.id': int(task_id)})
if (analyses.count() > 1):
message = 'Multiple tasks with this ID deleted, thanks for all the fish (the specified analysis was present multiple times in mongo).'
elif (analyses.count() == 1):
message = 'Task deleted, thanks for all the fish.'
if (not analyses.count()):
return render(request, 'error.html', {'error': 'The specified analysis does not exist'})
for analysis in analyses:
if ('file_id' in analysis['target']):
if (results_db.analysis.find({'target.file_id': ObjectId(analysis['target']['file_id'])}).count() == 1):
fs.delete(ObjectId(analysis['target']['file_id']))
for shot in analysis['shots']:
if (results_db.analysis.find({'shots': ObjectId(shot)}).count() == 1):
fs.delete(ObjectId(shot))
if (('pcap_id' in analysis['network']) and (results_db.analysis.find({'network.pcap_id': ObjectId(analysis['network']['pcap_id'])}).count() == 1)):
fs.delete(ObjectId(analysis['network']['pcap_id']))
if (('sorted_pcap_id' in analysis['network']) and (results_db.analysis.find({'network.sorted_pcap_id': ObjectId(analysis['network']['sorted_pcap_id'])}).count() == 1)):
fs.delete(ObjectId(analysis['network']['sorted_pcap_id']))
if (('mitmproxy_id' in analysis['network']) and (results_db.analysis.find({'network.mitmproxy_id': ObjectId(analysis['network']['mitmproxy_id'])}).count() == 1)):
fs.delete(ObjectId(analysis['network']['mitmproxy_id']))
for drop in analysis.get('dropped', []):
if (('object_id' in drop) and (results_db.analysis.find({'dropped.object_id': ObjectId(drop['object_id'])}).count() == 1)):
fs.delete(ObjectId(drop['object_id']))
for process in analysis.get('behavior', {}).get('processes', []):
for call in process['calls']:
results_db.calls.remove({'_id': ObjectId(call)})
results_db.analysis.remove({'_id': ObjectId(analysis['_id'])})
db = Database()
db.delete_task(task_id)
return render(request, 'success.html', {'message': message})
| Remove an analysis.
@todo: remove folder from storage. | remove an analysis . | Question:
What does this function do?
Code:
@require_safe
def remove(request, task_id):
analyses = results_db.analysis.find({'info.id': int(task_id)})
if (analyses.count() > 1):
message = 'Multiple tasks with this ID deleted, thanks for all the fish (the specified analysis was present multiple times in mongo).'
elif (analyses.count() == 1):
message = 'Task deleted, thanks for all the fish.'
if (not analyses.count()):
return render(request, 'error.html', {'error': 'The specified analysis does not exist'})
for analysis in analyses:
if ('file_id' in analysis['target']):
if (results_db.analysis.find({'target.file_id': ObjectId(analysis['target']['file_id'])}).count() == 1):
fs.delete(ObjectId(analysis['target']['file_id']))
for shot in analysis['shots']:
if (results_db.analysis.find({'shots': ObjectId(shot)}).count() == 1):
fs.delete(ObjectId(shot))
if (('pcap_id' in analysis['network']) and (results_db.analysis.find({'network.pcap_id': ObjectId(analysis['network']['pcap_id'])}).count() == 1)):
fs.delete(ObjectId(analysis['network']['pcap_id']))
if (('sorted_pcap_id' in analysis['network']) and (results_db.analysis.find({'network.sorted_pcap_id': ObjectId(analysis['network']['sorted_pcap_id'])}).count() == 1)):
fs.delete(ObjectId(analysis['network']['sorted_pcap_id']))
if (('mitmproxy_id' in analysis['network']) and (results_db.analysis.find({'network.mitmproxy_id': ObjectId(analysis['network']['mitmproxy_id'])}).count() == 1)):
fs.delete(ObjectId(analysis['network']['mitmproxy_id']))
for drop in analysis.get('dropped', []):
if (('object_id' in drop) and (results_db.analysis.find({'dropped.object_id': ObjectId(drop['object_id'])}).count() == 1)):
fs.delete(ObjectId(drop['object_id']))
for process in analysis.get('behavior', {}).get('processes', []):
for call in process['calls']:
results_db.calls.remove({'_id': ObjectId(call)})
results_db.analysis.remove({'_id': ObjectId(analysis['_id'])})
db = Database()
db.delete_task(task_id)
return render(request, 'success.html', {'message': message})
|
null | null | null | What does this function do? | def handle_upload_form(request, tp):
valid_extensions = tp.project.filetype_tool.valid_extensions
if ('po' not in valid_extensions):
return {}
language = tp.language
team = language_team.get(tp.language.__class__)(language)
uploader_list = [(request.user.id, request.user.display_name)]
if check_permission('administrate', request):
User = get_user_model()
uploader_list = [(user.id, user.display_name) for user in (((team.submitters | team.reviewers) | team.admins) | team.superusers)]
if ((request.method == 'POST') and ('file' in request.FILES)):
upload_form = UploadForm(request.POST, request.FILES, uploader_list=uploader_list)
if upload_form.is_valid():
uploader_id = upload_form.cleaned_data['user_id']
django_file = request.FILES['file']
uploader = request.user
if (uploader_id and (uploader_id != uploader.id)):
User = get_user_model()
uploader = User.objects.get(id=upload_form.cleaned_data['user_id'])
try:
if is_zipfile(django_file):
with ZipFile(django_file, 'r') as zf:
for path in zf.namelist():
if path.endswith('/'):
continue
ext = os.path.splitext(path)[1].strip('.')
if (ext not in valid_extensions):
continue
with zf.open(path, 'r') as f:
import_file(f, user=uploader)
else:
django_file.seek(0)
import_file(django_file, user=uploader)
except Exception as e:
upload_form.add_error('file', e)
return {'upload_form': upload_form}
else:
return {'upload_form': upload_form}
return {'upload_form': UploadForm(uploader_list=uploader_list, initial=dict(user_id=request.user.id))}
| null | null | null | Process the upload form. | pcsd | def handle upload form request tp valid extensions = tp project filetype tool valid extensions if 'po' not in valid extensions return {} language = tp language team = language team get tp language class language uploader list = [ request user id request user display name ] if check permission 'administrate' request User = get user model uploader list = [ user id user display name for user in team submitters | team reviewers | team admins | team superusers ] if request method == 'POST' and 'file' in request FILES upload form = Upload Form request POST request FILES uploader list=uploader list if upload form is valid uploader id = upload form cleaned data['user id'] django file = request FILES['file'] uploader = request user if uploader id and uploader id != uploader id User = get user model uploader = User objects get id=upload form cleaned data['user id'] try if is zipfile django file with Zip File django file 'r' as zf for path in zf namelist if path endswith '/' continue ext = os path splitext path [1] strip ' ' if ext not in valid extensions continue with zf open path 'r' as f import file f user=uploader else django file seek 0 import file django file user=uploader except Exception as e upload form add error 'file' e return {'upload form' upload form} else return {'upload form' upload form} return {'upload form' Upload Form uploader list=uploader list initial=dict user id=request user id } | 8987 | def handle_upload_form(request, tp):
valid_extensions = tp.project.filetype_tool.valid_extensions
if ('po' not in valid_extensions):
return {}
language = tp.language
team = language_team.get(tp.language.__class__)(language)
uploader_list = [(request.user.id, request.user.display_name)]
if check_permission('administrate', request):
User = get_user_model()
uploader_list = [(user.id, user.display_name) for user in (((team.submitters | team.reviewers) | team.admins) | team.superusers)]
if ((request.method == 'POST') and ('file' in request.FILES)):
upload_form = UploadForm(request.POST, request.FILES, uploader_list=uploader_list)
if upload_form.is_valid():
uploader_id = upload_form.cleaned_data['user_id']
django_file = request.FILES['file']
uploader = request.user
if (uploader_id and (uploader_id != uploader.id)):
User = get_user_model()
uploader = User.objects.get(id=upload_form.cleaned_data['user_id'])
try:
if is_zipfile(django_file):
with ZipFile(django_file, 'r') as zf:
for path in zf.namelist():
if path.endswith('/'):
continue
ext = os.path.splitext(path)[1].strip('.')
if (ext not in valid_extensions):
continue
with zf.open(path, 'r') as f:
import_file(f, user=uploader)
else:
django_file.seek(0)
import_file(django_file, user=uploader)
except Exception as e:
upload_form.add_error('file', e)
return {'upload_form': upload_form}
else:
return {'upload_form': upload_form}
return {'upload_form': UploadForm(uploader_list=uploader_list, initial=dict(user_id=request.user.id))}
| Process the upload form. | process the upload form . | Question:
What does this function do?
Code:
def handle_upload_form(request, tp):
valid_extensions = tp.project.filetype_tool.valid_extensions
if ('po' not in valid_extensions):
return {}
language = tp.language
team = language_team.get(tp.language.__class__)(language)
uploader_list = [(request.user.id, request.user.display_name)]
if check_permission('administrate', request):
User = get_user_model()
uploader_list = [(user.id, user.display_name) for user in (((team.submitters | team.reviewers) | team.admins) | team.superusers)]
if ((request.method == 'POST') and ('file' in request.FILES)):
upload_form = UploadForm(request.POST, request.FILES, uploader_list=uploader_list)
if upload_form.is_valid():
uploader_id = upload_form.cleaned_data['user_id']
django_file = request.FILES['file']
uploader = request.user
if (uploader_id and (uploader_id != uploader.id)):
User = get_user_model()
uploader = User.objects.get(id=upload_form.cleaned_data['user_id'])
try:
if is_zipfile(django_file):
with ZipFile(django_file, 'r') as zf:
for path in zf.namelist():
if path.endswith('/'):
continue
ext = os.path.splitext(path)[1].strip('.')
if (ext not in valid_extensions):
continue
with zf.open(path, 'r') as f:
import_file(f, user=uploader)
else:
django_file.seek(0)
import_file(django_file, user=uploader)
except Exception as e:
upload_form.add_error('file', e)
return {'upload_form': upload_form}
else:
return {'upload_form': upload_form}
return {'upload_form': UploadForm(uploader_list=uploader_list, initial=dict(user_id=request.user.id))}
|
null | null | null | What does this function do? | def traverse_translatable_index(doctree):
def is_block_index(node):
return (isinstance(node, addnodes.index) and (node.get('inline') == False))
for node in doctree.traverse(is_block_index):
if ('raw_entries' in node):
entries = node['raw_entries']
else:
entries = node['entries']
(yield (node, entries))
| null | null | null | Traverse translatable index node from a document tree. | pcsd | def traverse translatable index doctree def is block index node return isinstance node addnodes index and node get 'inline' == False for node in doctree traverse is block index if 'raw entries' in node entries = node['raw entries'] else entries = node['entries'] yield node entries | 8990 | def traverse_translatable_index(doctree):
def is_block_index(node):
return (isinstance(node, addnodes.index) and (node.get('inline') == False))
for node in doctree.traverse(is_block_index):
if ('raw_entries' in node):
entries = node['raw_entries']
else:
entries = node['entries']
(yield (node, entries))
| Traverse translatable index node from a document tree. | traverse translatable index node from a document tree . | Question:
What does this function do?
Code:
def traverse_translatable_index(doctree):
def is_block_index(node):
return (isinstance(node, addnodes.index) and (node.get('inline') == False))
for node in doctree.traverse(is_block_index):
if ('raw_entries' in node):
entries = node['raw_entries']
else:
entries = node['entries']
(yield (node, entries))
|
null | null | null | What does this function do? | def get_type_string(item):
if isinstance(item, DataFrame):
return 'DataFrame'
if isinstance(item, DatetimeIndex):
return 'DatetimeIndex'
if isinstance(item, Series):
return 'Series'
found = re.findall("<(?:type|class) '(\\S*)'>", to_text_string(type(item)))
if found:
return found[0]
| null | null | null | Return type string of an object. | pcsd | def get type string item if isinstance item Data Frame return 'Data Frame' if isinstance item Datetime Index return 'Datetime Index' if isinstance item Series return 'Series' found = re findall "< ? type|class ' \\S* '>" to text string type item if found return found[0] | 8992 | def get_type_string(item):
if isinstance(item, DataFrame):
return 'DataFrame'
if isinstance(item, DatetimeIndex):
return 'DatetimeIndex'
if isinstance(item, Series):
return 'Series'
found = re.findall("<(?:type|class) '(\\S*)'>", to_text_string(type(item)))
if found:
return found[0]
| Return type string of an object. | return type string of an object . | Question:
What does this function do?
Code:
def get_type_string(item):
if isinstance(item, DataFrame):
return 'DataFrame'
if isinstance(item, DatetimeIndex):
return 'DatetimeIndex'
if isinstance(item, Series):
return 'Series'
found = re.findall("<(?:type|class) '(\\S*)'>", to_text_string(type(item)))
if found:
return found[0]
|
null | null | null | What does this function do? | def getEndsWithList(word, wordEndings):
for wordEnding in wordEndings:
if word.endswith(wordEnding):
return True
return False
| null | null | null | Determine if the word ends with a list. | pcsd | def get Ends With List word word Endings for word Ending in word Endings if word endswith word Ending return True return False | 8996 | def getEndsWithList(word, wordEndings):
for wordEnding in wordEndings:
if word.endswith(wordEnding):
return True
return False
| Determine if the word ends with a list. | determine if the word ends with a list . | Question:
What does this function do?
Code:
def getEndsWithList(word, wordEndings):
for wordEnding in wordEndings:
if word.endswith(wordEnding):
return True
return False
|
null | null | null | What does this function do? | def runReducedExperiment(path, reduced=True):
initExperimentPrng()
if reduced:
args = [path, '--testMode']
else:
args = [path]
runExperiment(args)
| null | null | null | Run the experiment in the <path> with a reduced iteration count | pcsd | def run Reduced Experiment path reduced=True init Experiment Prng if reduced args = [path '--test Mode'] else args = [path] run Experiment args | 8997 | def runReducedExperiment(path, reduced=True):
initExperimentPrng()
if reduced:
args = [path, '--testMode']
else:
args = [path]
runExperiment(args)
| Run the experiment in the <path> with a reduced iteration count | run the experiment in the with a reduced iteration count | Question:
What does this function do?
Code:
def runReducedExperiment(path, reduced=True):
initExperimentPrng()
if reduced:
args = [path, '--testMode']
else:
args = [path]
runExperiment(args)
|
null | null | null | What does this function do? | def get_settings_from_file(path, default_settings=DEFAULT_CONFIG):
(name, ext) = os.path.splitext(os.path.basename(path))
module = load_source(name, path)
return get_settings_from_module(module, default_settings=default_settings)
| null | null | null | Loads settings from a file path, returning a dict. | pcsd | def get settings from file path default settings=DEFAULT CONFIG name ext = os path splitext os path basename path module = load source name path return get settings from module module default settings=default settings | 8998 | def get_settings_from_file(path, default_settings=DEFAULT_CONFIG):
(name, ext) = os.path.splitext(os.path.basename(path))
module = load_source(name, path)
return get_settings_from_module(module, default_settings=default_settings)
| Loads settings from a file path, returning a dict. | loads settings from a file path , returning a dict . | Question:
What does this function do?
Code:
def get_settings_from_file(path, default_settings=DEFAULT_CONFIG):
(name, ext) = os.path.splitext(os.path.basename(path))
module = load_source(name, path)
return get_settings_from_module(module, default_settings=default_settings)
|
null | null | null | What does this function do? | @pytest.fixture('module')
def browser(request):
_browser = config.get_browser()
_browser.set_window_size(800, 600)
_browser.set_window_position(((1024 - 800) - 10), 40)
request.addfinalizer((lambda : _browser.quit()))
return _browser
| null | null | null | Starts and stops the server for each app in APPS | pcsd | @pytest fixture 'module' def browser request browser = config get browser browser set window size 800 600 browser set window position 1024 - 800 - 10 40 request addfinalizer lambda browser quit return browser | 9000 | @pytest.fixture('module')
def browser(request):
_browser = config.get_browser()
_browser.set_window_size(800, 600)
_browser.set_window_position(((1024 - 800) - 10), 40)
request.addfinalizer((lambda : _browser.quit()))
return _browser
| Starts and stops the server for each app in APPS | starts and stops the server for each app in apps | Question:
What does this function do?
Code:
@pytest.fixture('module')
def browser(request):
_browser = config.get_browser()
_browser.set_window_size(800, 600)
_browser.set_window_position(((1024 - 800) - 10), 40)
request.addfinalizer((lambda : _browser.quit()))
return _browser
|
null | null | null | What does this function do? | 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 | Generates the sitemap.xml from the collected HTML page links | pcsd | 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 Sub Element root 'url' ET Sub Element url 'loc' text = link ET Element Tree root write filename | 9005 | 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)
| Generates the sitemap.xml from the collected HTML page links | generates the sitemap . xml from the collected html page links | Question:
What does this function do?
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 | What does this function do? | def main():
argument_spec = dict(http=dict(aliases=['enable_http'], default=True, type='bool', setter='set_http'), http_port=dict(default=80, type='int', setter='set_http'), https=dict(aliases=['enable_https'], default=False, type='bool', setter='set_https'), https_port=dict(default=443, type='int', setter='set_https'), sandbox=dict(aliases=['enable_sandbox'], default=False, type='bool'), transport=dict(required=True, choices=['cli']), config=dict(), state=dict(default='present', choices=['started', 'stopped', 'present', 'absent']))
module = NetworkModule(argument_spec=argument_spec, connect_on_load=False, supports_check_mode=True)
state = module.params['state']
warnings = list()
result = dict(changed=False, warnings=warnings)
if (state == 'started'):
state = 'present'
warnings.append('state=started is deprecated and will be removed in a a future release. Please use state=present instead')
elif (state == 'stopped'):
state = 'absent'
warnings.append('state=stopped is deprecated and will be removed in a a future release. Please use state=absent instead')
commands = list()
instance = get_instance(module)
invoke(state, module, instance, commands)
try:
load(module, commands, result)
except (ValueError, NetworkError):
load_checkpoint(module, result)
exc = get_exception()
module.fail_json(msg=str(exc), **exc.kwargs)
clean_result(result)
module.exit_json(**result)
| null | null | null | main entry point for module execution | pcsd | def main argument spec = dict http=dict aliases=['enable http'] default=True type='bool' setter='set http' http port=dict default=80 type='int' setter='set http' https=dict aliases=['enable https'] default=False type='bool' setter='set https' https port=dict default=443 type='int' setter='set https' sandbox=dict aliases=['enable sandbox'] default=False type='bool' transport=dict required=True choices=['cli'] config=dict state=dict default='present' choices=['started' 'stopped' 'present' 'absent'] module = Network Module argument spec=argument spec connect on load=False supports check mode=True state = module params['state'] warnings = list result = dict changed=False warnings=warnings if state == 'started' state = 'present' warnings append 'state=started is deprecated and will be removed in a a future release Please use state=present instead' elif state == 'stopped' state = 'absent' warnings append 'state=stopped is deprecated and will be removed in a a future release Please use state=absent instead' commands = list instance = get instance module invoke state module instance commands try load module commands result except Value Error Network Error load checkpoint module result exc = get exception module fail json msg=str exc **exc kwargs clean result result module exit json **result | 9010 | def main():
argument_spec = dict(http=dict(aliases=['enable_http'], default=True, type='bool', setter='set_http'), http_port=dict(default=80, type='int', setter='set_http'), https=dict(aliases=['enable_https'], default=False, type='bool', setter='set_https'), https_port=dict(default=443, type='int', setter='set_https'), sandbox=dict(aliases=['enable_sandbox'], default=False, type='bool'), transport=dict(required=True, choices=['cli']), config=dict(), state=dict(default='present', choices=['started', 'stopped', 'present', 'absent']))
module = NetworkModule(argument_spec=argument_spec, connect_on_load=False, supports_check_mode=True)
state = module.params['state']
warnings = list()
result = dict(changed=False, warnings=warnings)
if (state == 'started'):
state = 'present'
warnings.append('state=started is deprecated and will be removed in a a future release. Please use state=present instead')
elif (state == 'stopped'):
state = 'absent'
warnings.append('state=stopped is deprecated and will be removed in a a future release. Please use state=absent instead')
commands = list()
instance = get_instance(module)
invoke(state, module, instance, commands)
try:
load(module, commands, result)
except (ValueError, NetworkError):
load_checkpoint(module, result)
exc = get_exception()
module.fail_json(msg=str(exc), **exc.kwargs)
clean_result(result)
module.exit_json(**result)
| main entry point for module execution | main entry point for module execution | Question:
What does this function do?
Code:
def main():
argument_spec = dict(http=dict(aliases=['enable_http'], default=True, type='bool', setter='set_http'), http_port=dict(default=80, type='int', setter='set_http'), https=dict(aliases=['enable_https'], default=False, type='bool', setter='set_https'), https_port=dict(default=443, type='int', setter='set_https'), sandbox=dict(aliases=['enable_sandbox'], default=False, type='bool'), transport=dict(required=True, choices=['cli']), config=dict(), state=dict(default='present', choices=['started', 'stopped', 'present', 'absent']))
module = NetworkModule(argument_spec=argument_spec, connect_on_load=False, supports_check_mode=True)
state = module.params['state']
warnings = list()
result = dict(changed=False, warnings=warnings)
if (state == 'started'):
state = 'present'
warnings.append('state=started is deprecated and will be removed in a a future release. Please use state=present instead')
elif (state == 'stopped'):
state = 'absent'
warnings.append('state=stopped is deprecated and will be removed in a a future release. Please use state=absent instead')
commands = list()
instance = get_instance(module)
invoke(state, module, instance, commands)
try:
load(module, commands, result)
except (ValueError, NetworkError):
load_checkpoint(module, result)
exc = get_exception()
module.fail_json(msg=str(exc), **exc.kwargs)
clean_result(result)
module.exit_json(**result)
|
null | null | null | What does this function do? | def encode_sentences(model, X, verbose=False, batch_size=128):
features = numpy.zeros((len(X), model['options']['dim']), dtype='float32')
ds = defaultdict(list)
captions = [s.split() for s in X]
for (i, s) in enumerate(captions):
ds[len(s)].append(i)
d = defaultdict((lambda : 0))
for w in model['worddict'].keys():
d[w] = 1
for k in ds.keys():
if verbose:
print k
numbatches = ((len(ds[k]) / batch_size) + 1)
for minibatch in range(numbatches):
caps = ds[k][minibatch::numbatches]
caption = [captions[c] for c in caps]
seqs = []
for (i, cc) in enumerate(caption):
seqs.append([(model['worddict'][w] if ((d[w] > 0) and (model['worddict'][w] < model['options']['n_words'])) else 1) for w in cc])
x = numpy.zeros(((k + 1), len(caption))).astype('int64')
x_mask = numpy.zeros(((k + 1), len(caption))).astype('float32')
for (idx, s) in enumerate(seqs):
x[:k, idx] = s
x_mask[:(k + 1), idx] = 1.0
ff = model['f_senc'](x, x_mask)
for (ind, c) in enumerate(caps):
features[c] = ff[ind]
return features
| null | null | null | Encode sentences into the joint embedding space | pcsd | def encode sentences model X verbose=False batch size=128 features = numpy zeros len X model['options']['dim'] dtype='float32' ds = defaultdict list captions = [s split for s in X] for i s in enumerate captions ds[len s ] append i d = defaultdict lambda 0 for w in model['worddict'] keys d[w] = 1 for k in ds keys if verbose print k numbatches = len ds[k] / batch size + 1 for minibatch in range numbatches caps = ds[k][minibatch numbatches] caption = [captions[c] for c in caps] seqs = [] for i cc in enumerate caption seqs append [ model['worddict'][w] if d[w] > 0 and model['worddict'][w] < model['options']['n words'] else 1 for w in cc] x = numpy zeros k + 1 len caption astype 'int64' x mask = numpy zeros k + 1 len caption astype 'float32' for idx s in enumerate seqs x[ k idx] = s x mask[ k + 1 idx] = 1 0 ff = model['f senc'] x x mask for ind c in enumerate caps features[c] = ff[ind] return features | 9021 | def encode_sentences(model, X, verbose=False, batch_size=128):
features = numpy.zeros((len(X), model['options']['dim']), dtype='float32')
ds = defaultdict(list)
captions = [s.split() for s in X]
for (i, s) in enumerate(captions):
ds[len(s)].append(i)
d = defaultdict((lambda : 0))
for w in model['worddict'].keys():
d[w] = 1
for k in ds.keys():
if verbose:
print k
numbatches = ((len(ds[k]) / batch_size) + 1)
for minibatch in range(numbatches):
caps = ds[k][minibatch::numbatches]
caption = [captions[c] for c in caps]
seqs = []
for (i, cc) in enumerate(caption):
seqs.append([(model['worddict'][w] if ((d[w] > 0) and (model['worddict'][w] < model['options']['n_words'])) else 1) for w in cc])
x = numpy.zeros(((k + 1), len(caption))).astype('int64')
x_mask = numpy.zeros(((k + 1), len(caption))).astype('float32')
for (idx, s) in enumerate(seqs):
x[:k, idx] = s
x_mask[:(k + 1), idx] = 1.0
ff = model['f_senc'](x, x_mask)
for (ind, c) in enumerate(caps):
features[c] = ff[ind]
return features
| Encode sentences into the joint embedding space | encode sentences into the joint embedding space | Question:
What does this function do?
Code:
def encode_sentences(model, X, verbose=False, batch_size=128):
features = numpy.zeros((len(X), model['options']['dim']), dtype='float32')
ds = defaultdict(list)
captions = [s.split() for s in X]
for (i, s) in enumerate(captions):
ds[len(s)].append(i)
d = defaultdict((lambda : 0))
for w in model['worddict'].keys():
d[w] = 1
for k in ds.keys():
if verbose:
print k
numbatches = ((len(ds[k]) / batch_size) + 1)
for minibatch in range(numbatches):
caps = ds[k][minibatch::numbatches]
caption = [captions[c] for c in caps]
seqs = []
for (i, cc) in enumerate(caption):
seqs.append([(model['worddict'][w] if ((d[w] > 0) and (model['worddict'][w] < model['options']['n_words'])) else 1) for w in cc])
x = numpy.zeros(((k + 1), len(caption))).astype('int64')
x_mask = numpy.zeros(((k + 1), len(caption))).astype('float32')
for (idx, s) in enumerate(seqs):
x[:k, idx] = s
x_mask[:(k + 1), idx] = 1.0
ff = model['f_senc'](x, x_mask)
for (ind, c) in enumerate(caps):
features[c] = ff[ind]
return features
|
null | null | null | What does this function do? | def get_unsupported_lower_protocol():
if (Version(CASSANDRA_VERSION) >= Version('3.0')):
return 2
else:
return None
| null | null | null | This is used to determine the lowest protocol version that is NOT
supported by the version of C* running | pcsd | def get unsupported lower protocol if Version CASSANDRA VERSION >= Version '3 0' return 2 else return None | 9025 | def get_unsupported_lower_protocol():
if (Version(CASSANDRA_VERSION) >= Version('3.0')):
return 2
else:
return None
| This is used to determine the lowest protocol version that is NOT
supported by the version of C* running | this is used to determine the lowest protocol version that is not supported by the version of c * running | Question:
What does this function do?
Code:
def get_unsupported_lower_protocol():
if (Version(CASSANDRA_VERSION) >= Version('3.0')):
return 2
else:
return None
|
null | null | null | What does this function do? | 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 | Create a new figure manager instance | pcsd | 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 | 9027 | 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)
| Create a new figure manager instance | create a new figure manager instance | Question:
What does this function do?
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 this function do? | def _check_and_uninstall_python(ret, python, user=None):
ret = _python_installed(ret, python, user=user)
if ret['result']:
if ret['default']:
__salt__['pyenv.default']('system', runas=user)
if __salt__['pyenv.uninstall_python'](python, runas=user):
ret['result'] = True
ret['changes'][python] = 'Uninstalled'
ret['comment'] = 'Successfully removed python'
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to uninstall python'
return ret
else:
ret['result'] = True
ret['comment'] = 'python {0} is already absent'.format(python)
return ret
| null | null | null | Verify that python is uninstalled | pcsd | def check and uninstall python ret python user=None ret = python installed ret python user=user if ret['result'] if ret['default'] salt ['pyenv default'] 'system' runas=user if salt ['pyenv uninstall python'] python runas=user ret['result'] = True ret['changes'][python] = 'Uninstalled' ret['comment'] = 'Successfully removed python' return ret else ret['result'] = False ret['comment'] = 'Failed to uninstall python' return ret else ret['result'] = True ret['comment'] = 'python {0} is already absent' format python return ret | 9029 | def _check_and_uninstall_python(ret, python, user=None):
ret = _python_installed(ret, python, user=user)
if ret['result']:
if ret['default']:
__salt__['pyenv.default']('system', runas=user)
if __salt__['pyenv.uninstall_python'](python, runas=user):
ret['result'] = True
ret['changes'][python] = 'Uninstalled'
ret['comment'] = 'Successfully removed python'
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to uninstall python'
return ret
else:
ret['result'] = True
ret['comment'] = 'python {0} is already absent'.format(python)
return ret
| Verify that python is uninstalled | verify that python is uninstalled | Question:
What does this function do?
Code:
def _check_and_uninstall_python(ret, python, user=None):
ret = _python_installed(ret, python, user=user)
if ret['result']:
if ret['default']:
__salt__['pyenv.default']('system', runas=user)
if __salt__['pyenv.uninstall_python'](python, runas=user):
ret['result'] = True
ret['changes'][python] = 'Uninstalled'
ret['comment'] = 'Successfully removed python'
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to uninstall python'
return ret
else:
ret['result'] = True
ret['comment'] = 'python {0} is already absent'.format(python)
return ret
|
null | null | null | What does this function do? | def show(job, related_jobs=None):
return flask.render_template('models/images/classification/show.html', job=job, framework_ids=[fw.get_id() for fw in frameworks.get_frameworks()], related_jobs=related_jobs)
| null | null | null | Called from digits.model.views.models_show() | pcsd | def show job related jobs=None return flask render template 'models/images/classification/show html' job=job framework ids=[fw get id for fw in frameworks get frameworks ] related jobs=related jobs | 9034 | def show(job, related_jobs=None):
return flask.render_template('models/images/classification/show.html', job=job, framework_ids=[fw.get_id() for fw in frameworks.get_frameworks()], related_jobs=related_jobs)
| Called from digits.model.views.models_show() | called from digits . model . views . models _ show ( ) | Question:
What does this function do?
Code:
def show(job, related_jobs=None):
return flask.render_template('models/images/classification/show.html', job=job, framework_ids=[fw.get_id() for fw in frameworks.get_frameworks()], related_jobs=related_jobs)
|
null | null | null | What does this function do? | @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 | Get the job data for the front page tables | pcsd | @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 'Job not found' model output fields = set return flask jsonify {'job' json dict job model output fields } | 9035 | @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)})
| Get the job data for the front page tables | get the job data for the front page tables | Question:
What does this function do?
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 this function do? | def _check_logger_class():
import logging
if hasattr(logging, 'multiprocessing'):
return
logging._acquireLock()
try:
OldLoggerClass = logging.getLoggerClass()
if (not getattr(OldLoggerClass, '_process_aware', False)):
class ProcessAwareLogger(OldLoggerClass, ):
_process_aware = True
def makeRecord(self, *args, **kwds):
record = OldLoggerClass.makeRecord(self, *args, **kwds)
record.processName = current_process()._name
return record
logging.setLoggerClass(ProcessAwareLogger)
finally:
logging._releaseLock()
| null | null | null | Make sure process name is recorded when loggers are used | pcsd | def check logger class import logging if hasattr logging 'multiprocessing' return logging acquire Lock try Old Logger Class = logging get Logger Class if not getattr Old Logger Class ' process aware' False class Process Aware Logger Old Logger Class process aware = True def make Record self *args **kwds record = Old Logger Class make Record self *args **kwds record process Name = current process name return record logging set Logger Class Process Aware Logger finally logging release Lock | 9059 | def _check_logger_class():
import logging
if hasattr(logging, 'multiprocessing'):
return
logging._acquireLock()
try:
OldLoggerClass = logging.getLoggerClass()
if (not getattr(OldLoggerClass, '_process_aware', False)):
class ProcessAwareLogger(OldLoggerClass, ):
_process_aware = True
def makeRecord(self, *args, **kwds):
record = OldLoggerClass.makeRecord(self, *args, **kwds)
record.processName = current_process()._name
return record
logging.setLoggerClass(ProcessAwareLogger)
finally:
logging._releaseLock()
| Make sure process name is recorded when loggers are used | make sure process name is recorded when loggers are used | Question:
What does this function do?
Code:
def _check_logger_class():
import logging
if hasattr(logging, 'multiprocessing'):
return
logging._acquireLock()
try:
OldLoggerClass = logging.getLoggerClass()
if (not getattr(OldLoggerClass, '_process_aware', False)):
class ProcessAwareLogger(OldLoggerClass, ):
_process_aware = True
def makeRecord(self, *args, **kwds):
record = OldLoggerClass.makeRecord(self, *args, **kwds)
record.processName = current_process()._name
return record
logging.setLoggerClass(ProcessAwareLogger)
finally:
logging._releaseLock()
|
null | null | null | What does this function do? | def getNewDerivation(elementNode):
return SpongeSliceDerivation(elementNode)
| null | null | null | Get new derivation. | pcsd | def get New Derivation element Node return Sponge Slice Derivation element Node | 9065 | def getNewDerivation(elementNode):
return SpongeSliceDerivation(elementNode)
| Get new derivation. | get new derivation . | Question:
What does this function do?
Code:
def getNewDerivation(elementNode):
return SpongeSliceDerivation(elementNode)
|
null | null | null | What does this function do? | @auth.route('/activate', methods=['GET', 'POST'])
def request_activation_token(token=None):
if (current_user.is_active or (not flaskbb_config['ACTIVATE_ACCOUNT'])):
flash(_('This account is already activated.'), 'info')
return redirect(url_for('forum.index'))
form = RequestActivationForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
send_activation_token.delay(user)
flash(_('A new account activation token has been sent to your email address.'), 'success')
return redirect(url_for('auth.activate_account'))
return render_template('auth/request_account_activation.html', form=form)
| null | null | null | Requests a new account activation token. | pcsd | @auth route '/activate' methods=['GET' 'POST'] def request activation token token=None if current user is active or not flaskbb config['ACTIVATE ACCOUNT'] flash 'This account is already activated ' 'info' return redirect url for 'forum index' form = Request Activation Form if form validate on submit user = User query filter by email=form email data first send activation token delay user flash 'A new account activation token has been sent to your email address ' 'success' return redirect url for 'auth activate account' return render template 'auth/request account activation html' form=form | 9074 | @auth.route('/activate', methods=['GET', 'POST'])
def request_activation_token(token=None):
if (current_user.is_active or (not flaskbb_config['ACTIVATE_ACCOUNT'])):
flash(_('This account is already activated.'), 'info')
return redirect(url_for('forum.index'))
form = RequestActivationForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
send_activation_token.delay(user)
flash(_('A new account activation token has been sent to your email address.'), 'success')
return redirect(url_for('auth.activate_account'))
return render_template('auth/request_account_activation.html', form=form)
| Requests a new account activation token. | requests a new account activation token . | Question:
What does this function do?
Code:
@auth.route('/activate', methods=['GET', 'POST'])
def request_activation_token(token=None):
if (current_user.is_active or (not flaskbb_config['ACTIVATE_ACCOUNT'])):
flash(_('This account is already activated.'), 'info')
return redirect(url_for('forum.index'))
form = RequestActivationForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
send_activation_token.delay(user)
flash(_('A new account activation token has been sent to your email address.'), 'success')
return redirect(url_for('auth.activate_account'))
return render_template('auth/request_account_activation.html', form=form)
|
null | null | null | What does this function do? | @task(default_retry_delay=settings.BLOCK_STRUCTURES_SETTINGS['BLOCK_STRUCTURES_TASK_DEFAULT_RETRY_DELAY'], max_retries=settings.BLOCK_STRUCTURES_SETTINGS['BLOCK_STRUCTURES_TASK_MAX_RETRIES'])
def update_course_in_cache(course_id):
try:
course_key = CourseKey.from_string(course_id)
api.update_course_in_cache(course_key)
except NO_RETRY_TASKS as exc:
raise
except RETRY_TASKS as exc:
log.exception('update_course_in_cache encounted expected error, retrying.')
raise update_course_in_cache.retry(args=[course_id], exc=exc)
except Exception as exc:
log.exception('update_course_in_cache encounted unknown error. Retry #{}'.format(update_course_in_cache.request.retries))
raise update_course_in_cache.retry(args=[course_id], exc=exc)
| null | null | null | Updates the course blocks (in the database) for the specified course. | pcsd | @task default retry delay=settings BLOCK STRUCTURES SETTINGS['BLOCK STRUCTURES TASK DEFAULT RETRY DELAY'] max retries=settings BLOCK STRUCTURES SETTINGS['BLOCK STRUCTURES TASK MAX RETRIES'] def update course in cache course id try course key = Course Key from string course id api update course in cache course key except NO RETRY TASKS as exc raise except RETRY TASKS as exc log exception 'update course in cache encounted expected error retrying ' raise update course in cache retry args=[course id] exc=exc except Exception as exc log exception 'update course in cache encounted unknown error Retry #{}' format update course in cache request retries raise update course in cache retry args=[course id] exc=exc | 9082 | @task(default_retry_delay=settings.BLOCK_STRUCTURES_SETTINGS['BLOCK_STRUCTURES_TASK_DEFAULT_RETRY_DELAY'], max_retries=settings.BLOCK_STRUCTURES_SETTINGS['BLOCK_STRUCTURES_TASK_MAX_RETRIES'])
def update_course_in_cache(course_id):
try:
course_key = CourseKey.from_string(course_id)
api.update_course_in_cache(course_key)
except NO_RETRY_TASKS as exc:
raise
except RETRY_TASKS as exc:
log.exception('update_course_in_cache encounted expected error, retrying.')
raise update_course_in_cache.retry(args=[course_id], exc=exc)
except Exception as exc:
log.exception('update_course_in_cache encounted unknown error. Retry #{}'.format(update_course_in_cache.request.retries))
raise update_course_in_cache.retry(args=[course_id], exc=exc)
| Updates the course blocks (in the database) for the specified course. | updates the course blocks for the specified course . | Question:
What does this function do?
Code:
@task(default_retry_delay=settings.BLOCK_STRUCTURES_SETTINGS['BLOCK_STRUCTURES_TASK_DEFAULT_RETRY_DELAY'], max_retries=settings.BLOCK_STRUCTURES_SETTINGS['BLOCK_STRUCTURES_TASK_MAX_RETRIES'])
def update_course_in_cache(course_id):
try:
course_key = CourseKey.from_string(course_id)
api.update_course_in_cache(course_key)
except NO_RETRY_TASKS as exc:
raise
except RETRY_TASKS as exc:
log.exception('update_course_in_cache encounted expected error, retrying.')
raise update_course_in_cache.retry(args=[course_id], exc=exc)
except Exception as exc:
log.exception('update_course_in_cache encounted unknown error. Retry #{}'.format(update_course_in_cache.request.retries))
raise update_course_in_cache.retry(args=[course_id], exc=exc)
|
null | null | null | What does this function do? | def _detect_filename(ext):
import inspect
from os.path import isfile, dirname, basename, splitext, join
frame = inspect.currentframe()
while (frame.f_back and (frame.f_globals.get('name') != '__main__')):
frame = frame.f_back
filename = frame.f_globals.get('__file__')
if (filename and isfile(filename)):
(name, _) = splitext(basename(filename))
return join(dirname(filename), ((name + '.') + ext))
| null | null | null | Detect filename from the name of the script being run. Returns
None if the script could not be found (e.g. interactive mode). | pcsd | def detect filename ext import inspect from os path import isfile dirname basename splitext join frame = inspect currentframe while frame f back and frame f globals get 'name' != ' main ' frame = frame f back filename = frame f globals get ' file ' if filename and isfile filename name = splitext basename filename return join dirname filename name + ' ' + ext | 9084 | def _detect_filename(ext):
import inspect
from os.path import isfile, dirname, basename, splitext, join
frame = inspect.currentframe()
while (frame.f_back and (frame.f_globals.get('name') != '__main__')):
frame = frame.f_back
filename = frame.f_globals.get('__file__')
if (filename and isfile(filename)):
(name, _) = splitext(basename(filename))
return join(dirname(filename), ((name + '.') + ext))
| Detect filename from the name of the script being run. Returns
None if the script could not be found (e.g. interactive mode). | detect filename from the name of the script being run . | Question:
What does this function do?
Code:
def _detect_filename(ext):
import inspect
from os.path import isfile, dirname, basename, splitext, join
frame = inspect.currentframe()
while (frame.f_back and (frame.f_globals.get('name') != '__main__')):
frame = frame.f_back
filename = frame.f_globals.get('__file__')
if (filename and isfile(filename)):
(name, _) = splitext(basename(filename))
return join(dirname(filename), ((name + '.') + ext))
|
null | null | null | What does this function do? | def _check_psd_data(inst, tmin, tmax, picks, proj):
from ..io.base import BaseRaw
from ..epochs import BaseEpochs
from ..evoked import Evoked
if (not isinstance(inst, (BaseEpochs, BaseRaw, Evoked))):
raise ValueError('epochs must be an instance of Epochs, Raw, orEvoked. Got type {0}'.format(type(inst)))
time_mask = _time_mask(inst.times, tmin, tmax, sfreq=inst.info['sfreq'])
if (picks is None):
picks = _pick_data_channels(inst.info, with_ref_meg=False)
if proj:
inst = inst.copy().apply_proj()
sfreq = inst.info['sfreq']
if isinstance(inst, BaseRaw):
(start, stop) = np.where(time_mask)[0][[0, (-1)]]
(data, times) = inst[picks, start:(stop + 1)]
elif isinstance(inst, BaseEpochs):
data = inst.get_data()[:, picks][:, :, time_mask]
elif isinstance(inst, Evoked):
data = inst.data[picks][:, time_mask]
return (data, sfreq)
| null | null | null | Helper to do checks on PSD data / pull arrays from inst. | pcsd | def check psd data inst tmin tmax picks proj from io base import Base Raw from epochs import Base Epochs from evoked import Evoked if not isinstance inst Base Epochs Base Raw Evoked raise Value Error 'epochs must be an instance of Epochs Raw or Evoked Got type {0}' format type inst time mask = time mask inst times tmin tmax sfreq=inst info['sfreq'] if picks is None picks = pick data channels inst info with ref meg=False if proj inst = inst copy apply proj sfreq = inst info['sfreq'] if isinstance inst Base Raw start stop = np where time mask [0][[0 -1 ]] data times = inst[picks start stop + 1 ] elif isinstance inst Base Epochs data = inst get data [ picks][ time mask] elif isinstance inst Evoked data = inst data[picks][ time mask] return data sfreq | 9087 | def _check_psd_data(inst, tmin, tmax, picks, proj):
from ..io.base import BaseRaw
from ..epochs import BaseEpochs
from ..evoked import Evoked
if (not isinstance(inst, (BaseEpochs, BaseRaw, Evoked))):
raise ValueError('epochs must be an instance of Epochs, Raw, orEvoked. Got type {0}'.format(type(inst)))
time_mask = _time_mask(inst.times, tmin, tmax, sfreq=inst.info['sfreq'])
if (picks is None):
picks = _pick_data_channels(inst.info, with_ref_meg=False)
if proj:
inst = inst.copy().apply_proj()
sfreq = inst.info['sfreq']
if isinstance(inst, BaseRaw):
(start, stop) = np.where(time_mask)[0][[0, (-1)]]
(data, times) = inst[picks, start:(stop + 1)]
elif isinstance(inst, BaseEpochs):
data = inst.get_data()[:, picks][:, :, time_mask]
elif isinstance(inst, Evoked):
data = inst.data[picks][:, time_mask]
return (data, sfreq)
| Helper to do checks on PSD data / pull arrays from inst. | helper to do checks on psd data / pull arrays from inst . | Question:
What does this function do?
Code:
def _check_psd_data(inst, tmin, tmax, picks, proj):
from ..io.base import BaseRaw
from ..epochs import BaseEpochs
from ..evoked import Evoked
if (not isinstance(inst, (BaseEpochs, BaseRaw, Evoked))):
raise ValueError('epochs must be an instance of Epochs, Raw, orEvoked. Got type {0}'.format(type(inst)))
time_mask = _time_mask(inst.times, tmin, tmax, sfreq=inst.info['sfreq'])
if (picks is None):
picks = _pick_data_channels(inst.info, with_ref_meg=False)
if proj:
inst = inst.copy().apply_proj()
sfreq = inst.info['sfreq']
if isinstance(inst, BaseRaw):
(start, stop) = np.where(time_mask)[0][[0, (-1)]]
(data, times) = inst[picks, start:(stop + 1)]
elif isinstance(inst, BaseEpochs):
data = inst.get_data()[:, picks][:, :, time_mask]
elif isinstance(inst, Evoked):
data = inst.data[picks][:, time_mask]
return (data, sfreq)
|
null | null | null | What does this function do? | def load_user():
config_path = get_user_config_path()
config = {}
with open(config_path) as f:
code = compile(f.read(), config_path, 'exec')
exec code in config
keys = list(six.iterkeys(config))
for k in keys:
if k.startswith('_'):
del config[k]
return config
| null | null | null | Read user config file and return it as a dict. | pcsd | def load user config path = get user config path config = {} with open config path as f code = compile f read config path 'exec' exec code in config keys = list six iterkeys config for k in keys if k startswith ' ' del config[k] return config | 9090 | def load_user():
config_path = get_user_config_path()
config = {}
with open(config_path) as f:
code = compile(f.read(), config_path, 'exec')
exec code in config
keys = list(six.iterkeys(config))
for k in keys:
if k.startswith('_'):
del config[k]
return config
| Read user config file and return it as a dict. | read user config file and return it as a dict . | Question:
What does this function do?
Code:
def load_user():
config_path = get_user_config_path()
config = {}
with open(config_path) as f:
code = compile(f.read(), config_path, 'exec')
exec code in config
keys = list(six.iterkeys(config))
for k in keys:
if k.startswith('_'):
del config[k]
return config
|
null | null | null | What does this function do? | def discretize_linear_1D(model, x_range):
x = np.arange((x_range[0] - 0.5), (x_range[1] + 0.5))
values_intermediate_grid = model(x)
return (0.5 * (values_intermediate_grid[1:] + values_intermediate_grid[:(-1)]))
| null | null | null | Discretize model by performing a linear interpolation. | pcsd | def discretize linear 1D model x range x = np arange x range[0] - 0 5 x range[1] + 0 5 values intermediate grid = model x return 0 5 * values intermediate grid[1 ] + values intermediate grid[ -1 ] | 9095 | def discretize_linear_1D(model, x_range):
x = np.arange((x_range[0] - 0.5), (x_range[1] + 0.5))
values_intermediate_grid = model(x)
return (0.5 * (values_intermediate_grid[1:] + values_intermediate_grid[:(-1)]))
| Discretize model by performing a linear interpolation. | discretize model by performing a linear interpolation . | Question:
What does this function do?
Code:
def discretize_linear_1D(model, x_range):
x = np.arange((x_range[0] - 0.5), (x_range[1] + 0.5))
values_intermediate_grid = model(x)
return (0.5 * (values_intermediate_grid[1:] + values_intermediate_grid[:(-1)]))
|
null | null | null | What does this function do? | def pluralize(word, pos=NOUN, custom={}):
if (word in custom):
return custom[word]
w = word.lower()
if (len(w) < 3):
return w
if (w in plural_irregular):
return plural_irregular[w]
if (w.endswith(('cia', 'gia')) and (len(w) > 4) and (not is_vowel(w[(-4)]))):
return (w[:(-2)] + 'e')
if w.endswith(('ca', 'ga')):
return (w[:(-2)] + 'he')
if w.endswith('a'):
return (w[:(-1)] + 'e')
if w.endswith('e'):
return (w[:(-1)] + 'i')
if w.endswith('io'):
return (w[:(-2)] + 'i')
if (w in plural_co_chi):
return (w[:(-2)] + 'chi')
if (w in plural_co_chi):
return (w[:(-2)] + 'ghi')
if w.endswith('o'):
return (w[:(-1)] + 'i')
return w
| null | null | null | Returns the plural of a given word. | pcsd | def pluralize word pos=NOUN custom={} if word in custom return custom[word] w = word lower if len w < 3 return w if w in plural irregular return plural irregular[w] if w endswith 'cia' 'gia' and len w > 4 and not is vowel w[ -4 ] return w[ -2 ] + 'e' if w endswith 'ca' 'ga' return w[ -2 ] + 'he' if w endswith 'a' return w[ -1 ] + 'e' if w endswith 'e' return w[ -1 ] + 'i' if w endswith 'io' return w[ -2 ] + 'i' if w in plural co chi return w[ -2 ] + 'chi' if w in plural co chi return w[ -2 ] + 'ghi' if w endswith 'o' return w[ -1 ] + 'i' return w | 9098 | def pluralize(word, pos=NOUN, custom={}):
if (word in custom):
return custom[word]
w = word.lower()
if (len(w) < 3):
return w
if (w in plural_irregular):
return plural_irregular[w]
if (w.endswith(('cia', 'gia')) and (len(w) > 4) and (not is_vowel(w[(-4)]))):
return (w[:(-2)] + 'e')
if w.endswith(('ca', 'ga')):
return (w[:(-2)] + 'he')
if w.endswith('a'):
return (w[:(-1)] + 'e')
if w.endswith('e'):
return (w[:(-1)] + 'i')
if w.endswith('io'):
return (w[:(-2)] + 'i')
if (w in plural_co_chi):
return (w[:(-2)] + 'chi')
if (w in plural_co_chi):
return (w[:(-2)] + 'ghi')
if w.endswith('o'):
return (w[:(-1)] + 'i')
return w
| Returns the plural of a given word. | returns the plural of a given word . | Question:
What does this function do?
Code:
def pluralize(word, pos=NOUN, custom={}):
if (word in custom):
return custom[word]
w = word.lower()
if (len(w) < 3):
return w
if (w in plural_irregular):
return plural_irregular[w]
if (w.endswith(('cia', 'gia')) and (len(w) > 4) and (not is_vowel(w[(-4)]))):
return (w[:(-2)] + 'e')
if w.endswith(('ca', 'ga')):
return (w[:(-2)] + 'he')
if w.endswith('a'):
return (w[:(-1)] + 'e')
if w.endswith('e'):
return (w[:(-1)] + 'i')
if w.endswith('io'):
return (w[:(-2)] + 'i')
if (w in plural_co_chi):
return (w[:(-2)] + 'chi')
if (w in plural_co_chi):
return (w[:(-2)] + 'ghi')
if w.endswith('o'):
return (w[:(-1)] + 'i')
return w
|
null | null | null | What does this function do? | def result_headers(cl):
lookup_opts = cl.lookup_opts
for (i, field_name) in enumerate(cl.list_display):
(header, attr) = label_for_field(field_name, cl.model, model_admin=cl.model_admin, return_attr=True)
if attr:
if (field_name == 'action_checkbox'):
(yield {'text': header, 'class_attrib': mark_safe(' class="action-checkbox-column"')})
continue
admin_order_field = getattr(attr, 'admin_order_field', None)
if (not admin_order_field):
(yield {'text': header})
continue
else:
admin_order_field = None
th_classes = []
new_order_type = 'asc'
if ((field_name == cl.order_field) or (admin_order_field == cl.order_field)):
th_classes.append(('sorted %sending' % cl.order_type.lower()))
new_order_type = {'asc': 'desc', 'desc': 'asc'}[cl.order_type.lower()]
(yield {'text': header, 'sortable': True, 'url': cl.get_query_string({ORDER_VAR: i, ORDER_TYPE_VAR: new_order_type}), 'class_attrib': mark_safe(((th_classes and (' class="%s"' % ' '.join(th_classes))) or ''))})
| null | null | null | Generates the list column headers. | pcsd | def result headers cl lookup opts = cl lookup opts for i field name in enumerate cl list display header attr = label for field field name cl model model admin=cl model admin return attr=True if attr if field name == 'action checkbox' yield {'text' header 'class attrib' mark safe ' class="action-checkbox-column"' } continue admin order field = getattr attr 'admin order field' None if not admin order field yield {'text' header} continue else admin order field = None th classes = [] new order type = 'asc' if field name == cl order field or admin order field == cl order field th classes append 'sorted %sending' % cl order type lower new order type = {'asc' 'desc' 'desc' 'asc'}[cl order type lower ] yield {'text' header 'sortable' True 'url' cl get query string {ORDER VAR i ORDER TYPE VAR new order type} 'class attrib' mark safe th classes and ' class="%s"' % ' ' join th classes or '' } | 9106 | def result_headers(cl):
lookup_opts = cl.lookup_opts
for (i, field_name) in enumerate(cl.list_display):
(header, attr) = label_for_field(field_name, cl.model, model_admin=cl.model_admin, return_attr=True)
if attr:
if (field_name == 'action_checkbox'):
(yield {'text': header, 'class_attrib': mark_safe(' class="action-checkbox-column"')})
continue
admin_order_field = getattr(attr, 'admin_order_field', None)
if (not admin_order_field):
(yield {'text': header})
continue
else:
admin_order_field = None
th_classes = []
new_order_type = 'asc'
if ((field_name == cl.order_field) or (admin_order_field == cl.order_field)):
th_classes.append(('sorted %sending' % cl.order_type.lower()))
new_order_type = {'asc': 'desc', 'desc': 'asc'}[cl.order_type.lower()]
(yield {'text': header, 'sortable': True, 'url': cl.get_query_string({ORDER_VAR: i, ORDER_TYPE_VAR: new_order_type}), 'class_attrib': mark_safe(((th_classes and (' class="%s"' % ' '.join(th_classes))) or ''))})
| Generates the list column headers. | generates the list column headers . | Question:
What does this function do?
Code:
def result_headers(cl):
lookup_opts = cl.lookup_opts
for (i, field_name) in enumerate(cl.list_display):
(header, attr) = label_for_field(field_name, cl.model, model_admin=cl.model_admin, return_attr=True)
if attr:
if (field_name == 'action_checkbox'):
(yield {'text': header, 'class_attrib': mark_safe(' class="action-checkbox-column"')})
continue
admin_order_field = getattr(attr, 'admin_order_field', None)
if (not admin_order_field):
(yield {'text': header})
continue
else:
admin_order_field = None
th_classes = []
new_order_type = 'asc'
if ((field_name == cl.order_field) or (admin_order_field == cl.order_field)):
th_classes.append(('sorted %sending' % cl.order_type.lower()))
new_order_type = {'asc': 'desc', 'desc': 'asc'}[cl.order_type.lower()]
(yield {'text': header, 'sortable': True, 'url': cl.get_query_string({ORDER_VAR: i, ORDER_TYPE_VAR: new_order_type}), 'class_attrib': mark_safe(((th_classes and (' class="%s"' % ' '.join(th_classes))) or ''))})
|
null | null | null | What does this function do? | def clean_tags(request, tags, max_tags=None):
target = [slugify(t, spaces=True, lower=True) for t in tags.split(',')]
target = set(filter(None, target))
min_len = mkt.MIN_TAG_LENGTH
max_len = Tag._meta.get_field('tag_text').max_length
max_tags = (max_tags or mkt.MAX_TAGS)
total = len(target)
blocked = Tag.objects.values_list('tag_text', flat=True).filter(tag_text__in=target, blocked=True)
if blocked:
msg = ngettext(u'Invalid tag: {0}', 'Invalid tags: {0}', len(blocked)).format(', '.join(blocked))
raise forms.ValidationError(msg)
restricted = Tag.objects.values_list('tag_text', flat=True).filter(tag_text__in=target, restricted=True)
if (restricted and (not can_edit_restricted_tags(request))):
msg = ngettext(u'"{0}" is a reserved tag and cannot be used.', u'"{0}" are reserved tags and cannot be used.', len(restricted)).format('", "'.join(restricted))
raise forms.ValidationError(msg)
else:
total = len((target - set(restricted)))
if (total > max_tags):
num = (total - max_tags)
msg = ngettext(u'You have {0} too many tags.', u'You have {0} too many tags.', num).format(num)
raise forms.ValidationError(msg)
if any((t for t in target if (len(t) > max_len))):
raise forms.ValidationError(_((u'All tags must be %s characters or less after invalid characters are removed.' % max_len)))
if any((t for t in target if (len(t) < min_len))):
msg = ngettext(u'All tags must be at least {0} character.', u'All tags must be at least {0} characters.', min_len).format(min_len)
raise forms.ValidationError(msg)
return target
| null | null | null | Blocked tags are not allowed.
Restricted tags can only be edited by Reviewers and Curators. | pcsd | def clean tags request tags max tags=None target = [slugify t spaces=True lower=True for t in tags split ' ' ] target = set filter None target min len = mkt MIN TAG LENGTH max len = Tag meta get field 'tag text' max length max tags = max tags or mkt MAX TAGS total = len target blocked = Tag objects values list 'tag text' flat=True filter tag text in=target blocked=True if blocked msg = ngettext u'Invalid tag {0}' 'Invalid tags {0}' len blocked format ' ' join blocked raise forms Validation Error msg restricted = Tag objects values list 'tag text' flat=True filter tag text in=target restricted=True if restricted and not can edit restricted tags request msg = ngettext u'"{0}" is a reserved tag and cannot be used ' u'"{0}" are reserved tags and cannot be used ' len restricted format '" "' join restricted raise forms Validation Error msg else total = len target - set restricted if total > max tags num = total - max tags msg = ngettext u'You have {0} too many tags ' u'You have {0} too many tags ' num format num raise forms Validation Error msg if any t for t in target if len t > max len raise forms Validation Error u'All tags must be %s characters or less after invalid characters are removed ' % max len if any t for t in target if len t < min len msg = ngettext u'All tags must be at least {0} character ' u'All tags must be at least {0} characters ' min len format min len raise forms Validation Error msg return target | 9108 | def clean_tags(request, tags, max_tags=None):
target = [slugify(t, spaces=True, lower=True) for t in tags.split(',')]
target = set(filter(None, target))
min_len = mkt.MIN_TAG_LENGTH
max_len = Tag._meta.get_field('tag_text').max_length
max_tags = (max_tags or mkt.MAX_TAGS)
total = len(target)
blocked = Tag.objects.values_list('tag_text', flat=True).filter(tag_text__in=target, blocked=True)
if blocked:
msg = ngettext(u'Invalid tag: {0}', 'Invalid tags: {0}', len(blocked)).format(', '.join(blocked))
raise forms.ValidationError(msg)
restricted = Tag.objects.values_list('tag_text', flat=True).filter(tag_text__in=target, restricted=True)
if (restricted and (not can_edit_restricted_tags(request))):
msg = ngettext(u'"{0}" is a reserved tag and cannot be used.', u'"{0}" are reserved tags and cannot be used.', len(restricted)).format('", "'.join(restricted))
raise forms.ValidationError(msg)
else:
total = len((target - set(restricted)))
if (total > max_tags):
num = (total - max_tags)
msg = ngettext(u'You have {0} too many tags.', u'You have {0} too many tags.', num).format(num)
raise forms.ValidationError(msg)
if any((t for t in target if (len(t) > max_len))):
raise forms.ValidationError(_((u'All tags must be %s characters or less after invalid characters are removed.' % max_len)))
if any((t for t in target if (len(t) < min_len))):
msg = ngettext(u'All tags must be at least {0} character.', u'All tags must be at least {0} characters.', min_len).format(min_len)
raise forms.ValidationError(msg)
return target
| Blocked tags are not allowed.
Restricted tags can only be edited by Reviewers and Curators. | blocked tags are not allowed . | Question:
What does this function do?
Code:
def clean_tags(request, tags, max_tags=None):
target = [slugify(t, spaces=True, lower=True) for t in tags.split(',')]
target = set(filter(None, target))
min_len = mkt.MIN_TAG_LENGTH
max_len = Tag._meta.get_field('tag_text').max_length
max_tags = (max_tags or mkt.MAX_TAGS)
total = len(target)
blocked = Tag.objects.values_list('tag_text', flat=True).filter(tag_text__in=target, blocked=True)
if blocked:
msg = ngettext(u'Invalid tag: {0}', 'Invalid tags: {0}', len(blocked)).format(', '.join(blocked))
raise forms.ValidationError(msg)
restricted = Tag.objects.values_list('tag_text', flat=True).filter(tag_text__in=target, restricted=True)
if (restricted and (not can_edit_restricted_tags(request))):
msg = ngettext(u'"{0}" is a reserved tag and cannot be used.', u'"{0}" are reserved tags and cannot be used.', len(restricted)).format('", "'.join(restricted))
raise forms.ValidationError(msg)
else:
total = len((target - set(restricted)))
if (total > max_tags):
num = (total - max_tags)
msg = ngettext(u'You have {0} too many tags.', u'You have {0} too many tags.', num).format(num)
raise forms.ValidationError(msg)
if any((t for t in target if (len(t) > max_len))):
raise forms.ValidationError(_((u'All tags must be %s characters or less after invalid characters are removed.' % max_len)))
if any((t for t in target if (len(t) < min_len))):
msg = ngettext(u'All tags must be at least {0} character.', u'All tags must be at least {0} characters.', min_len).format(min_len)
raise forms.ValidationError(msg)
return target
|
null | null | null | What does this function do? | @utils.arg('network', metavar='<network>', help=_('UUID of network.'))
@deprecated_network
def do_network_associate_project(cs, args):
cs.networks.associate_project(args.network)
| null | null | null | Associate project with network. | pcsd | @utils arg 'network' metavar='<network>' help= 'UUID of network ' @deprecated network def do network associate project cs args cs networks associate project args network | 9111 | @utils.arg('network', metavar='<network>', help=_('UUID of network.'))
@deprecated_network
def do_network_associate_project(cs, args):
cs.networks.associate_project(args.network)
| Associate project with network. | associate project with network . | Question:
What does this function do?
Code:
@utils.arg('network', metavar='<network>', help=_('UUID of network.'))
@deprecated_network
def do_network_associate_project(cs, args):
cs.networks.associate_project(args.network)
|
null | null | null | What does this function do? | def remove_server():
global _BONJOUR_OBJECT
if _BONJOUR_OBJECT:
_BONJOUR_OBJECT.close()
_BONJOUR_OBJECT = None
| null | null | null | Remove Bonjour registration | pcsd | def remove server global BONJOUR OBJECT if BONJOUR OBJECT BONJOUR OBJECT close BONJOUR OBJECT = None | 9131 | def remove_server():
global _BONJOUR_OBJECT
if _BONJOUR_OBJECT:
_BONJOUR_OBJECT.close()
_BONJOUR_OBJECT = None
| Remove Bonjour registration | remove bonjour registration | Question:
What does this function do?
Code:
def remove_server():
global _BONJOUR_OBJECT
if _BONJOUR_OBJECT:
_BONJOUR_OBJECT.close()
_BONJOUR_OBJECT = None
|
null | null | null | What does this function do? | def getCarvingFromParser(xmlParser):
booleanGeometryElement = xmlParser.getRoot()
booleanGeometryElement.object = boolean_geometry.BooleanGeometry()
root = xmlParser.getRoot()
root.xmlProcessor = XMLBooleanGeometryProcessor()
root.xmlProcessor.processChildren(booleanGeometryElement)
return booleanGeometryElement.object
| null | null | null | Get the carving for the parser. | pcsd | def get Carving From Parser xml Parser boolean Geometry Element = xml Parser get Root boolean Geometry Element object = boolean geometry Boolean Geometry root = xml Parser get Root root xml Processor = XML Boolean Geometry Processor root xml Processor process Children boolean Geometry Element return boolean Geometry Element object | 9133 | def getCarvingFromParser(xmlParser):
booleanGeometryElement = xmlParser.getRoot()
booleanGeometryElement.object = boolean_geometry.BooleanGeometry()
root = xmlParser.getRoot()
root.xmlProcessor = XMLBooleanGeometryProcessor()
root.xmlProcessor.processChildren(booleanGeometryElement)
return booleanGeometryElement.object
| Get the carving for the parser. | get the carving for the parser . | Question:
What does this function do?
Code:
def getCarvingFromParser(xmlParser):
booleanGeometryElement = xmlParser.getRoot()
booleanGeometryElement.object = boolean_geometry.BooleanGeometry()
root = xmlParser.getRoot()
root.xmlProcessor = XMLBooleanGeometryProcessor()
root.xmlProcessor.processChildren(booleanGeometryElement)
return booleanGeometryElement.object
|
null | null | null | What does this function do? | def get_cert_and_update_domain(zappa_instance, lambda_name, api_stage, domain=None, clean_up=True):
try:
create_domain_key()
create_domain_csr(domain)
get_cert(zappa_instance)
create_chained_certificate()
with open('/tmp/signed.crt') as f:
certificate_body = f.read()
with open('/tmp/domain.key') as f:
certificate_private_key = f.read()
with open('/tmp/intermediate.pem') as f:
certificate_chain = f.read()
if domain:
if (not zappa_instance.get_domain_name(domain)):
zappa_instance.create_domain_name(domain, (domain + '-Zappa-LE-Cert'), certificate_body, certificate_private_key, certificate_chain, lambda_name, api_stage)
print 'Created a new domain name. Please note that it can take up to 40 minutes for this domain to be created and propagated through AWS, but it requires no further work on your part.'
else:
zappa_instance.update_domain_name(domain, (domain + '-Zappa-LE-Cert'), certificate_body, certificate_private_key, certificate_chain)
except Exception as e:
print e
return False
if clean_up:
cleanup()
return True
| null | null | null | Main cert installer path. | pcsd | def get cert and update domain zappa instance lambda name api stage domain=None clean up=True try create domain key create domain csr domain get cert zappa instance create chained certificate with open '/tmp/signed crt' as f certificate body = f read with open '/tmp/domain key' as f certificate private key = f read with open '/tmp/intermediate pem' as f certificate chain = f read if domain if not zappa instance get domain name domain zappa instance create domain name domain domain + '-Zappa-LE-Cert' certificate body certificate private key certificate chain lambda name api stage print 'Created a new domain name Please note that it can take up to 40 minutes for this domain to be created and propagated through AWS but it requires no further work on your part ' else zappa instance update domain name domain domain + '-Zappa-LE-Cert' certificate body certificate private key certificate chain except Exception as e print e return False if clean up cleanup return True | 9141 | def get_cert_and_update_domain(zappa_instance, lambda_name, api_stage, domain=None, clean_up=True):
try:
create_domain_key()
create_domain_csr(domain)
get_cert(zappa_instance)
create_chained_certificate()
with open('/tmp/signed.crt') as f:
certificate_body = f.read()
with open('/tmp/domain.key') as f:
certificate_private_key = f.read()
with open('/tmp/intermediate.pem') as f:
certificate_chain = f.read()
if domain:
if (not zappa_instance.get_domain_name(domain)):
zappa_instance.create_domain_name(domain, (domain + '-Zappa-LE-Cert'), certificate_body, certificate_private_key, certificate_chain, lambda_name, api_stage)
print 'Created a new domain name. Please note that it can take up to 40 minutes for this domain to be created and propagated through AWS, but it requires no further work on your part.'
else:
zappa_instance.update_domain_name(domain, (domain + '-Zappa-LE-Cert'), certificate_body, certificate_private_key, certificate_chain)
except Exception as e:
print e
return False
if clean_up:
cleanup()
return True
| Main cert installer path. | main cert installer path . | Question:
What does this function do?
Code:
def get_cert_and_update_domain(zappa_instance, lambda_name, api_stage, domain=None, clean_up=True):
try:
create_domain_key()
create_domain_csr(domain)
get_cert(zappa_instance)
create_chained_certificate()
with open('/tmp/signed.crt') as f:
certificate_body = f.read()
with open('/tmp/domain.key') as f:
certificate_private_key = f.read()
with open('/tmp/intermediate.pem') as f:
certificate_chain = f.read()
if domain:
if (not zappa_instance.get_domain_name(domain)):
zappa_instance.create_domain_name(domain, (domain + '-Zappa-LE-Cert'), certificate_body, certificate_private_key, certificate_chain, lambda_name, api_stage)
print 'Created a new domain name. Please note that it can take up to 40 minutes for this domain to be created and propagated through AWS, but it requires no further work on your part.'
else:
zappa_instance.update_domain_name(domain, (domain + '-Zappa-LE-Cert'), certificate_body, certificate_private_key, certificate_chain)
except Exception as e:
print e
return False
if clean_up:
cleanup()
return True
|
null | null | null | What does this function do? | @dispatch(Expr, object)
def post_compute(expr, result, scope=None):
return result
| null | null | null | Effects after the computation is complete | pcsd | @dispatch Expr object def post compute expr result scope=None return result | 9153 | @dispatch(Expr, object)
def post_compute(expr, result, scope=None):
return result
| Effects after the computation is complete | effects after the computation is complete | Question:
What does this function do?
Code:
@dispatch(Expr, object)
def post_compute(expr, result, scope=None):
return result
|
null | null | null | What does this function do? | @shared_task
def print_unicode(log_message=u'h\xe5\xe5\xae\u0192 valmuefr\xf8', print_message=u'hi\xf6\xe4\xfc\xdf'):
logger.warning(log_message)
print print_message
| null | null | null | Task that both logs and print strings containing funny characters. | pcsd | @shared task def print unicode log message=u'h\xe5\xe5\xae\u0192 valmuefr\xf8' print message=u'hi\xf6\xe4\xfc\xdf' logger warning log message print print message | 9154 | @shared_task
def print_unicode(log_message=u'h\xe5\xe5\xae\u0192 valmuefr\xf8', print_message=u'hi\xf6\xe4\xfc\xdf'):
logger.warning(log_message)
print print_message
| Task that both logs and print strings containing funny characters. | task that both logs and print strings containing funny characters . | Question:
What does this function do?
Code:
@shared_task
def print_unicode(log_message=u'h\xe5\xe5\xae\u0192 valmuefr\xf8', print_message=u'hi\xf6\xe4\xfc\xdf'):
logger.warning(log_message)
print print_message
|
null | null | null | What does this function do? | def decode_addr(v):
if (len(v) not in [0, 20]):
raise Exception('Serialized addresses must be empty or 20 bytes long!')
return encode_hex(v)
| null | null | null | decodes an address from serialization | pcsd | def decode addr v if len v not in [0 20] raise Exception 'Serialized addresses must be empty or 20 bytes long!' return encode hex v | 9159 | def decode_addr(v):
if (len(v) not in [0, 20]):
raise Exception('Serialized addresses must be empty or 20 bytes long!')
return encode_hex(v)
| decodes an address from serialization | decodes an address from serialization | Question:
What does this function do?
Code:
def decode_addr(v):
if (len(v) not in [0, 20]):
raise Exception('Serialized addresses must be empty or 20 bytes long!')
return encode_hex(v)
|
null | null | null | What does this function do? | @pytest.mark.network
def test_wheel_package_with_latin1_setup(script, data):
script.pip('install', 'wheel')
pkg_to_wheel = data.packages.join('SetupPyLatin1')
result = script.pip('wheel', pkg_to_wheel)
assert ('Successfully built SetupPyUTF8' in result.stdout)
| null | null | null | Create a wheel from a package with latin-1 encoded setup.py. | pcsd | @pytest mark network def test wheel package with latin1 setup script data script pip 'install' 'wheel' pkg to wheel = data packages join 'Setup Py Latin1' result = script pip 'wheel' pkg to wheel assert 'Successfully built Setup Py UTF8' in result stdout | 9174 | @pytest.mark.network
def test_wheel_package_with_latin1_setup(script, data):
script.pip('install', 'wheel')
pkg_to_wheel = data.packages.join('SetupPyLatin1')
result = script.pip('wheel', pkg_to_wheel)
assert ('Successfully built SetupPyUTF8' in result.stdout)
| Create a wheel from a package with latin-1 encoded setup.py. | create a wheel from a package with latin - 1 encoded setup . py . | Question:
What does this function do?
Code:
@pytest.mark.network
def test_wheel_package_with_latin1_setup(script, data):
script.pip('install', 'wheel')
pkg_to_wheel = data.packages.join('SetupPyLatin1')
result = script.pip('wheel', pkg_to_wheel)
assert ('Successfully built SetupPyUTF8' in result.stdout)
|
null | null | null | What does this function do? | def get_tenant(keystone, name):
tenants = [x for x in keystone.tenants.list() if (x.name == name)]
count = len(tenants)
if (count == 0):
raise KeyError(('No keystone tenants with name %s' % name))
elif (count > 1):
raise ValueError(('%d tenants with name %s' % (count, name)))
else:
return tenants[0]
| null | null | null | Retrieve a tenant by name | pcsd | def get tenant keystone name tenants = [x for x in keystone tenants list if x name == name ] count = len tenants if count == 0 raise Key Error 'No keystone tenants with name %s' % name elif count > 1 raise Value Error '%d tenants with name %s' % count name else return tenants[0] | 9176 | def get_tenant(keystone, name):
tenants = [x for x in keystone.tenants.list() if (x.name == name)]
count = len(tenants)
if (count == 0):
raise KeyError(('No keystone tenants with name %s' % name))
elif (count > 1):
raise ValueError(('%d tenants with name %s' % (count, name)))
else:
return tenants[0]
| Retrieve a tenant by name | retrieve a tenant by name | Question:
What does this function do?
Code:
def get_tenant(keystone, name):
tenants = [x for x in keystone.tenants.list() if (x.name == name)]
count = len(tenants)
if (count == 0):
raise KeyError(('No keystone tenants with name %s' % name))
elif (count > 1):
raise ValueError(('%d tenants with name %s' % (count, name)))
else:
return tenants[0]
|
null | null | null | What does this function do? | @never_cache
def show(request, url, alias_model, template):
group_alias = get_object_or_404(alias_model, url=url)
if (group_alias.alias.url != url):
return redirect('groups:show_group', url=group_alias.alias.url)
is_curator = False
is_manager = request.user.userprofile.is_manager
is_pending = False
show_delete_group_button = False
membership_filter_form = forms.MembershipFilterForm(request.GET)
group = group_alias.alias
profile = request.user.userprofile
in_group = group.has_member(profile)
memberships = group.members.all()
data = {}
if isinstance(group, Group):
if group.terms:
membership = get_object_or_none(GroupMembership, group=group, userprofile=profile, status=GroupMembership.PENDING_TERMS)
if membership:
return redirect(reverse('groups:review_terms', args=[group.url]))
is_pending = group.has_pending_member(profile)
is_curator = (is_manager or (request.user.userprofile in group.curators.all()))
if (is_curator and (group.accepting_new_members == 'by_request')):
membership_filter_form = forms.MembershipFilterForm(request.GET)
else:
membership_filter_form = None
if is_curator:
statuses = [GroupMembership.MEMBER, GroupMembership.PENDING]
if (membership_filter_form and membership_filter_form.is_valid()):
filtr = membership_filter_form.cleaned_data['filtr']
if (filtr == 'members'):
statuses = [GroupMembership.MEMBER]
elif (filtr == 'pending_members'):
statuses = [GroupMembership.PENDING]
memberships = group.groupmembership_set.filter(status__in=statuses)
show_delete_group_button = (is_curator and (group.members.all().count() == 1))
else:
memberships = group.groupmembership_set.filter((Q(status=GroupMembership.MEMBER) | Q(userprofile=profile)))
invitation = get_object_or_none(Invite, redeemer=profile, group=group, accepted=False)
data.update(invitation=invitation)
memberships = memberships.order_by('userprofile')
shared_skill_ids = group.members.filter(groupmembership__status=GroupMembership.MEMBER).values_list('skills', flat=True)
count_skills = defaultdict(int)
for skill_id in shared_skill_ids:
count_skills[skill_id] += 1
common_skills_ids = [k for (k, v) in sorted(count_skills.items(), key=(lambda x: x[1]), reverse=True) if (count_skills[k] > 1)]
skills = [Skill.objects.get(id=skill_id) for skill_id in common_skills_ids if skill_id]
data.update(skills=skills, membership_filter_form=membership_filter_form)
page = request.GET.get('page', 1)
paginator = Paginator(memberships, settings.ITEMS_PER_PAGE)
try:
people = paginator.page(page)
except PageNotAnInteger:
people = paginator.page(1)
except EmptyPage:
people = paginator.page(paginator.num_pages)
show_pagination = (paginator.count > settings.ITEMS_PER_PAGE)
extra_data = dict(people=people, group=group, in_group=in_group, is_curator=is_curator, is_pending=is_pending, show_pagination=show_pagination, show_delete_group_button=show_delete_group_button, show_join_button=group.user_can_join(request.user.userprofile), show_leave_button=group.user_can_leave(request.user.userprofile), members=group.member_count)
data.update(extra_data)
return render(request, template, data)
| null | null | null | List all members in this group. | pcsd | @never cache def show request url alias model template group alias = get object or 404 alias model url=url if group alias alias url != url return redirect 'groups show group' url=group alias alias url is curator = False is manager = request user userprofile is manager is pending = False show delete group button = False membership filter form = forms Membership Filter Form request GET group = group alias alias profile = request user userprofile in group = group has member profile memberships = group members all data = {} if isinstance group Group if group terms membership = get object or none Group Membership group=group userprofile=profile status=Group Membership PENDING TERMS if membership return redirect reverse 'groups review terms' args=[group url] is pending = group has pending member profile is curator = is manager or request user userprofile in group curators all if is curator and group accepting new members == 'by request' membership filter form = forms Membership Filter Form request GET else membership filter form = None if is curator statuses = [Group Membership MEMBER Group Membership PENDING] if membership filter form and membership filter form is valid filtr = membership filter form cleaned data['filtr'] if filtr == 'members' statuses = [Group Membership MEMBER] elif filtr == 'pending members' statuses = [Group Membership PENDING] memberships = group groupmembership set filter status in=statuses show delete group button = is curator and group members all count == 1 else memberships = group groupmembership set filter Q status=Group Membership MEMBER | Q userprofile=profile invitation = get object or none Invite redeemer=profile group=group accepted=False data update invitation=invitation memberships = memberships order by 'userprofile' shared skill ids = group members filter groupmembership status=Group Membership MEMBER values list 'skills' flat=True count skills = defaultdict int for skill id in shared skill ids count skills[skill id] += 1 common skills ids = [k for k v in sorted count skills items key= lambda x x[1] reverse=True if count skills[k] > 1 ] skills = [Skill objects get id=skill id for skill id in common skills ids if skill id] data update skills=skills membership filter form=membership filter form page = request GET get 'page' 1 paginator = Paginator memberships settings ITEMS PER PAGE try people = paginator page page except Page Not An Integer people = paginator page 1 except Empty Page people = paginator page paginator num pages show pagination = paginator count > settings ITEMS PER PAGE extra data = dict people=people group=group in group=in group is curator=is curator is pending=is pending show pagination=show pagination show delete group button=show delete group button show join button=group user can join request user userprofile show leave button=group user can leave request user userprofile members=group member count data update extra data return render request template data | 9179 | @never_cache
def show(request, url, alias_model, template):
group_alias = get_object_or_404(alias_model, url=url)
if (group_alias.alias.url != url):
return redirect('groups:show_group', url=group_alias.alias.url)
is_curator = False
is_manager = request.user.userprofile.is_manager
is_pending = False
show_delete_group_button = False
membership_filter_form = forms.MembershipFilterForm(request.GET)
group = group_alias.alias
profile = request.user.userprofile
in_group = group.has_member(profile)
memberships = group.members.all()
data = {}
if isinstance(group, Group):
if group.terms:
membership = get_object_or_none(GroupMembership, group=group, userprofile=profile, status=GroupMembership.PENDING_TERMS)
if membership:
return redirect(reverse('groups:review_terms', args=[group.url]))
is_pending = group.has_pending_member(profile)
is_curator = (is_manager or (request.user.userprofile in group.curators.all()))
if (is_curator and (group.accepting_new_members == 'by_request')):
membership_filter_form = forms.MembershipFilterForm(request.GET)
else:
membership_filter_form = None
if is_curator:
statuses = [GroupMembership.MEMBER, GroupMembership.PENDING]
if (membership_filter_form and membership_filter_form.is_valid()):
filtr = membership_filter_form.cleaned_data['filtr']
if (filtr == 'members'):
statuses = [GroupMembership.MEMBER]
elif (filtr == 'pending_members'):
statuses = [GroupMembership.PENDING]
memberships = group.groupmembership_set.filter(status__in=statuses)
show_delete_group_button = (is_curator and (group.members.all().count() == 1))
else:
memberships = group.groupmembership_set.filter((Q(status=GroupMembership.MEMBER) | Q(userprofile=profile)))
invitation = get_object_or_none(Invite, redeemer=profile, group=group, accepted=False)
data.update(invitation=invitation)
memberships = memberships.order_by('userprofile')
shared_skill_ids = group.members.filter(groupmembership__status=GroupMembership.MEMBER).values_list('skills', flat=True)
count_skills = defaultdict(int)
for skill_id in shared_skill_ids:
count_skills[skill_id] += 1
common_skills_ids = [k for (k, v) in sorted(count_skills.items(), key=(lambda x: x[1]), reverse=True) if (count_skills[k] > 1)]
skills = [Skill.objects.get(id=skill_id) for skill_id in common_skills_ids if skill_id]
data.update(skills=skills, membership_filter_form=membership_filter_form)
page = request.GET.get('page', 1)
paginator = Paginator(memberships, settings.ITEMS_PER_PAGE)
try:
people = paginator.page(page)
except PageNotAnInteger:
people = paginator.page(1)
except EmptyPage:
people = paginator.page(paginator.num_pages)
show_pagination = (paginator.count > settings.ITEMS_PER_PAGE)
extra_data = dict(people=people, group=group, in_group=in_group, is_curator=is_curator, is_pending=is_pending, show_pagination=show_pagination, show_delete_group_button=show_delete_group_button, show_join_button=group.user_can_join(request.user.userprofile), show_leave_button=group.user_can_leave(request.user.userprofile), members=group.member_count)
data.update(extra_data)
return render(request, template, data)
| List all members in this group. | list all members in this group . | Question:
What does this function do?
Code:
@never_cache
def show(request, url, alias_model, template):
group_alias = get_object_or_404(alias_model, url=url)
if (group_alias.alias.url != url):
return redirect('groups:show_group', url=group_alias.alias.url)
is_curator = False
is_manager = request.user.userprofile.is_manager
is_pending = False
show_delete_group_button = False
membership_filter_form = forms.MembershipFilterForm(request.GET)
group = group_alias.alias
profile = request.user.userprofile
in_group = group.has_member(profile)
memberships = group.members.all()
data = {}
if isinstance(group, Group):
if group.terms:
membership = get_object_or_none(GroupMembership, group=group, userprofile=profile, status=GroupMembership.PENDING_TERMS)
if membership:
return redirect(reverse('groups:review_terms', args=[group.url]))
is_pending = group.has_pending_member(profile)
is_curator = (is_manager or (request.user.userprofile in group.curators.all()))
if (is_curator and (group.accepting_new_members == 'by_request')):
membership_filter_form = forms.MembershipFilterForm(request.GET)
else:
membership_filter_form = None
if is_curator:
statuses = [GroupMembership.MEMBER, GroupMembership.PENDING]
if (membership_filter_form and membership_filter_form.is_valid()):
filtr = membership_filter_form.cleaned_data['filtr']
if (filtr == 'members'):
statuses = [GroupMembership.MEMBER]
elif (filtr == 'pending_members'):
statuses = [GroupMembership.PENDING]
memberships = group.groupmembership_set.filter(status__in=statuses)
show_delete_group_button = (is_curator and (group.members.all().count() == 1))
else:
memberships = group.groupmembership_set.filter((Q(status=GroupMembership.MEMBER) | Q(userprofile=profile)))
invitation = get_object_or_none(Invite, redeemer=profile, group=group, accepted=False)
data.update(invitation=invitation)
memberships = memberships.order_by('userprofile')
shared_skill_ids = group.members.filter(groupmembership__status=GroupMembership.MEMBER).values_list('skills', flat=True)
count_skills = defaultdict(int)
for skill_id in shared_skill_ids:
count_skills[skill_id] += 1
common_skills_ids = [k for (k, v) in sorted(count_skills.items(), key=(lambda x: x[1]), reverse=True) if (count_skills[k] > 1)]
skills = [Skill.objects.get(id=skill_id) for skill_id in common_skills_ids if skill_id]
data.update(skills=skills, membership_filter_form=membership_filter_form)
page = request.GET.get('page', 1)
paginator = Paginator(memberships, settings.ITEMS_PER_PAGE)
try:
people = paginator.page(page)
except PageNotAnInteger:
people = paginator.page(1)
except EmptyPage:
people = paginator.page(paginator.num_pages)
show_pagination = (paginator.count > settings.ITEMS_PER_PAGE)
extra_data = dict(people=people, group=group, in_group=in_group, is_curator=is_curator, is_pending=is_pending, show_pagination=show_pagination, show_delete_group_button=show_delete_group_button, show_join_button=group.user_can_join(request.user.userprofile), show_leave_button=group.user_can_leave(request.user.userprofile), members=group.member_count)
data.update(extra_data)
return render(request, template, data)
|
null | null | null | What does this function do? | def find_distributions(path_item, only=False):
importer = get_importer(path_item)
finder = _find_adapter(_distribution_finders, importer)
return finder(importer, path_item, only)
| null | null | null | Yield distributions accessible via `path_item` | pcsd | def find distributions path item only=False importer = get importer path item finder = find adapter distribution finders importer return finder importer path item only | 9183 | def find_distributions(path_item, only=False):
importer = get_importer(path_item)
finder = _find_adapter(_distribution_finders, importer)
return finder(importer, path_item, only)
| Yield distributions accessible via `path_item` | yield distributions accessible via path _ item | Question:
What does this function do?
Code:
def find_distributions(path_item, only=False):
importer = get_importer(path_item)
finder = _find_adapter(_distribution_finders, importer)
return finder(importer, path_item, only)
|
null | null | null | What does this function do? | def infer_name(self, context=None):
(frame, stmts) = self.lookup(self.name)
if (not stmts):
parent_function = _higher_function_scope(self.scope())
if parent_function:
(_, stmts) = parent_function.lookup(self.name)
if (not stmts):
raise UnresolvableName(self.name)
context = context.clone()
context.lookupname = self.name
return _infer_stmts(stmts, context, frame)
| null | null | null | infer a Name: use name lookup rules | pcsd | def infer name self context=None frame stmts = self lookup self name if not stmts parent function = higher function scope self scope if parent function stmts = parent function lookup self name if not stmts raise Unresolvable Name self name context = context clone context lookupname = self name return infer stmts stmts context frame | 9193 | def infer_name(self, context=None):
(frame, stmts) = self.lookup(self.name)
if (not stmts):
parent_function = _higher_function_scope(self.scope())
if parent_function:
(_, stmts) = parent_function.lookup(self.name)
if (not stmts):
raise UnresolvableName(self.name)
context = context.clone()
context.lookupname = self.name
return _infer_stmts(stmts, context, frame)
| infer a Name: use name lookup rules | infer a name : use name lookup rules | Question:
What does this function do?
Code:
def infer_name(self, context=None):
(frame, stmts) = self.lookup(self.name)
if (not stmts):
parent_function = _higher_function_scope(self.scope())
if parent_function:
(_, stmts) = parent_function.lookup(self.name)
if (not stmts):
raise UnresolvableName(self.name)
context = context.clone()
context.lookupname = self.name
return _infer_stmts(stmts, context, frame)
|
null | null | null | What does this function do? | @hook.command('rottentomatoes', 'rt')
def rotten_tomatoes(text, bot):
api_key = bot.config.get('api_keys', {}).get('rottentomatoes', None)
if (not api_key):
return 'No Rotten Tomatoes API key set.'
title = text.strip()
params = {'q': title, 'apikey': api_key}
request = requests.get(movie_search_url, params=params)
if (request.status_code != requests.codes.ok):
return 'Error searching: {}'.format(request.status_code)
results = request.json()
if (results['total'] == 0):
return 'No results.'
movie = results['movies'][0]
title = movie['title']
movie_id = movie['id']
critics_score = movie['ratings']['critics_score']
audience_score = movie['ratings']['audience_score']
url = web.try_shorten(movie['links']['alternate'])
if (critics_score == (-1)):
return '\x02{}\x02 - Critics Rating: \x02No Reviews\x02, Audience Rating: \x02{}%\x02 - {}'.format(title, audience_score, url)
review_params = {'review_type': 'all', 'apikey': api_key}
review_request = requests.get(movie_reviews_url.format(movie_id), params=review_params)
if (review_request.status_code != requests.codes.ok):
return 'Error searching: {}'.format(review_request.status_code)
reviews = review_request.json()
review_count = reviews['total']
fresh = int(((critics_score * review_count) / 100))
rotten = (review_count - fresh)
return '\x02{}\x02 - Critics Rating: \x02{}%\x02 ({} liked, {} disliked), Audience Rating: \x02{}%\x02 - {}'.format(title, critics_score, fresh, rotten, audience_score, url)
| null | null | null | rt <title> -- gets ratings for <title> from Rotten Tomatoes | pcsd | @hook command 'rottentomatoes' 'rt' def rotten tomatoes text bot api key = bot config get 'api keys' {} get 'rottentomatoes' None if not api key return 'No Rotten Tomatoes API key set ' title = text strip params = {'q' title 'apikey' api key} request = requests get movie search url params=params if request status code != requests codes ok return 'Error searching {}' format request status code results = request json if results['total'] == 0 return 'No results ' movie = results['movies'][0] title = movie['title'] movie id = movie['id'] critics score = movie['ratings']['critics score'] audience score = movie['ratings']['audience score'] url = web try shorten movie['links']['alternate'] if critics score == -1 return '\x02{}\x02 - Critics Rating \x02No Reviews\x02 Audience Rating \x02{}%\x02 - {}' format title audience score url review params = {'review type' 'all' 'apikey' api key} review request = requests get movie reviews url format movie id params=review params if review request status code != requests codes ok return 'Error searching {}' format review request status code reviews = review request json review count = reviews['total'] fresh = int critics score * review count / 100 rotten = review count - fresh return '\x02{}\x02 - Critics Rating \x02{}%\x02 {} liked {} disliked Audience Rating \x02{}%\x02 - {}' format title critics score fresh rotten audience score url | 9221 | @hook.command('rottentomatoes', 'rt')
def rotten_tomatoes(text, bot):
api_key = bot.config.get('api_keys', {}).get('rottentomatoes', None)
if (not api_key):
return 'No Rotten Tomatoes API key set.'
title = text.strip()
params = {'q': title, 'apikey': api_key}
request = requests.get(movie_search_url, params=params)
if (request.status_code != requests.codes.ok):
return 'Error searching: {}'.format(request.status_code)
results = request.json()
if (results['total'] == 0):
return 'No results.'
movie = results['movies'][0]
title = movie['title']
movie_id = movie['id']
critics_score = movie['ratings']['critics_score']
audience_score = movie['ratings']['audience_score']
url = web.try_shorten(movie['links']['alternate'])
if (critics_score == (-1)):
return '\x02{}\x02 - Critics Rating: \x02No Reviews\x02, Audience Rating: \x02{}%\x02 - {}'.format(title, audience_score, url)
review_params = {'review_type': 'all', 'apikey': api_key}
review_request = requests.get(movie_reviews_url.format(movie_id), params=review_params)
if (review_request.status_code != requests.codes.ok):
return 'Error searching: {}'.format(review_request.status_code)
reviews = review_request.json()
review_count = reviews['total']
fresh = int(((critics_score * review_count) / 100))
rotten = (review_count - fresh)
return '\x02{}\x02 - Critics Rating: \x02{}%\x02 ({} liked, {} disliked), Audience Rating: \x02{}%\x02 - {}'.format(title, critics_score, fresh, rotten, audience_score, url)
| rt <title> -- gets ratings for <title> from Rotten Tomatoes | rt - - gets ratings for from rotten tomatoes | Question:
What does this function do?
Code:
@hook.command('rottentomatoes', 'rt')
def rotten_tomatoes(text, bot):
api_key = bot.config.get('api_keys', {}).get('rottentomatoes', None)
if (not api_key):
return 'No Rotten Tomatoes API key set.'
title = text.strip()
params = {'q': title, 'apikey': api_key}
request = requests.get(movie_search_url, params=params)
if (request.status_code != requests.codes.ok):
return 'Error searching: {}'.format(request.status_code)
results = request.json()
if (results['total'] == 0):
return 'No results.'
movie = results['movies'][0]
title = movie['title']
movie_id = movie['id']
critics_score = movie['ratings']['critics_score']
audience_score = movie['ratings']['audience_score']
url = web.try_shorten(movie['links']['alternate'])
if (critics_score == (-1)):
return '\x02{}\x02 - Critics Rating: \x02No Reviews\x02, Audience Rating: \x02{}%\x02 - {}'.format(title, audience_score, url)
review_params = {'review_type': 'all', 'apikey': api_key}
review_request = requests.get(movie_reviews_url.format(movie_id), params=review_params)
if (review_request.status_code != requests.codes.ok):
return 'Error searching: {}'.format(review_request.status_code)
reviews = review_request.json()
review_count = reviews['total']
fresh = int(((critics_score * review_count) / 100))
rotten = (review_count - fresh)
return '\x02{}\x02 - Critics Rating: \x02{}%\x02 ({} liked, {} disliked), Audience Rating: \x02{}%\x02 - {}'.format(title, critics_score, fresh, rotten, audience_score, url)
|
null | null | null | What does this function do? | def attachment_specs_get(context, attachment_id):
return IMPL.attachment_specs_get(context, attachment_id)
| null | null | null | Get all specs for an attachment. | pcsd | def attachment specs get context attachment id return IMPL attachment specs get context attachment id | 9222 | def attachment_specs_get(context, attachment_id):
return IMPL.attachment_specs_get(context, attachment_id)
| Get all specs for an attachment. | get all specs for an attachment . | Question:
What does this function do?
Code:
def attachment_specs_get(context, attachment_id):
return IMPL.attachment_specs_get(context, attachment_id)
|
null | null | null | What does this function do? | def _bsd_cpudata(osdata):
sysctl = salt.utils.which('sysctl')
arch = salt.utils.which('arch')
cmds = {}
if sysctl:
cmds.update({'num_cpus': '{0} -n hw.ncpu'.format(sysctl), 'cpuarch': '{0} -n hw.machine'.format(sysctl), 'cpu_model': '{0} -n hw.model'.format(sysctl)})
if (arch and (osdata['kernel'] == 'OpenBSD')):
cmds['cpuarch'] = '{0} -s'.format(arch)
if (osdata['kernel'] == 'Darwin'):
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for (k, v) in six.iteritems(cmds)])
if (('cpu_flags' in grains) and isinstance(grains['cpu_flags'], six.string_types)):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if (osdata['kernel'] == 'NetBSD'):
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match('cpu[0-9]:\\ features[0-9]?\\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if ((osdata['kernel'] == 'FreeBSD') and os.path.isfile('/var/run/dmesg.boot')):
grains['cpu_flags'] = []
with salt.utils.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True
continue
if cpu_here:
if (not line.startswith(' ')):
break
if ('Features' in line):
start = line.find('<')
end = line.find('>')
if ((start > 0) and (end > 0)):
flag = line[(start + 1):end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
| null | null | null | Return CPU information for BSD-like systems | pcsd | def bsd cpudata osdata sysctl = salt utils which 'sysctl' arch = salt utils which 'arch' cmds = {} if sysctl cmds update {'num cpus' '{0} -n hw ncpu' format sysctl 'cpuarch' '{0} -n hw machine' format sysctl 'cpu model' '{0} -n hw model' format sysctl } if arch and osdata['kernel'] == 'Open BSD' cmds['cpuarch'] = '{0} -s' format arch if osdata['kernel'] == 'Darwin' cmds['cpu model'] = '{0} -n machdep cpu brand string' format sysctl cmds['cpu flags'] = '{0} -n machdep cpu features' format sysctl grains = dict [ k salt ['cmd run'] v for k v in six iteritems cmds ] if 'cpu flags' in grains and isinstance grains['cpu flags'] six string types grains['cpu flags'] = grains['cpu flags'] split ' ' if osdata['kernel'] == 'Net BSD' grains['cpu flags'] = [] for line in salt ['cmd run'] 'cpuctl identify 0' splitlines cpu match = re match 'cpu[0-9] \\ features[0-9]?\\ +< + >' line if cpu match flag = cpu match group 1 split ' ' grains['cpu flags'] extend flag if osdata['kernel'] == 'Free BSD' and os path isfile '/var/run/dmesg boot' grains['cpu flags'] = [] with salt utils fopen '/var/run/dmesg boot' 'r' as fp cpu here = False for line in fp if line startswith 'CPU ' cpu here = True continue if cpu here if not line startswith ' ' break if 'Features' in line start = line find '<' end = line find '>' if start > 0 and end > 0 flag = line[ start + 1 end] split ' ' grains['cpu flags'] extend flag try grains['num cpus'] = int grains['num cpus'] except Value Error grains['num cpus'] = 1 return grains | 9225 | def _bsd_cpudata(osdata):
sysctl = salt.utils.which('sysctl')
arch = salt.utils.which('arch')
cmds = {}
if sysctl:
cmds.update({'num_cpus': '{0} -n hw.ncpu'.format(sysctl), 'cpuarch': '{0} -n hw.machine'.format(sysctl), 'cpu_model': '{0} -n hw.model'.format(sysctl)})
if (arch and (osdata['kernel'] == 'OpenBSD')):
cmds['cpuarch'] = '{0} -s'.format(arch)
if (osdata['kernel'] == 'Darwin'):
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for (k, v) in six.iteritems(cmds)])
if (('cpu_flags' in grains) and isinstance(grains['cpu_flags'], six.string_types)):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if (osdata['kernel'] == 'NetBSD'):
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match('cpu[0-9]:\\ features[0-9]?\\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if ((osdata['kernel'] == 'FreeBSD') and os.path.isfile('/var/run/dmesg.boot')):
grains['cpu_flags'] = []
with salt.utils.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True
continue
if cpu_here:
if (not line.startswith(' ')):
break
if ('Features' in line):
start = line.find('<')
end = line.find('>')
if ((start > 0) and (end > 0)):
flag = line[(start + 1):end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
| Return CPU information for BSD-like systems | return cpu information for bsd - like systems | Question:
What does this function do?
Code:
def _bsd_cpudata(osdata):
sysctl = salt.utils.which('sysctl')
arch = salt.utils.which('arch')
cmds = {}
if sysctl:
cmds.update({'num_cpus': '{0} -n hw.ncpu'.format(sysctl), 'cpuarch': '{0} -n hw.machine'.format(sysctl), 'cpu_model': '{0} -n hw.model'.format(sysctl)})
if (arch and (osdata['kernel'] == 'OpenBSD')):
cmds['cpuarch'] = '{0} -s'.format(arch)
if (osdata['kernel'] == 'Darwin'):
cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)
grains = dict([(k, __salt__['cmd.run'](v)) for (k, v) in six.iteritems(cmds)])
if (('cpu_flags' in grains) and isinstance(grains['cpu_flags'], six.string_types)):
grains['cpu_flags'] = grains['cpu_flags'].split(' ')
if (osdata['kernel'] == 'NetBSD'):
grains['cpu_flags'] = []
for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
cpu_match = re.match('cpu[0-9]:\\ features[0-9]?\\ .+<(.+)>', line)
if cpu_match:
flag = cpu_match.group(1).split(',')
grains['cpu_flags'].extend(flag)
if ((osdata['kernel'] == 'FreeBSD') and os.path.isfile('/var/run/dmesg.boot')):
grains['cpu_flags'] = []
with salt.utils.fopen('/var/run/dmesg.boot', 'r') as _fp:
cpu_here = False
for line in _fp:
if line.startswith('CPU: '):
cpu_here = True
continue
if cpu_here:
if (not line.startswith(' ')):
break
if ('Features' in line):
start = line.find('<')
end = line.find('>')
if ((start > 0) and (end > 0)):
flag = line[(start + 1):end].split(',')
grains['cpu_flags'].extend(flag)
try:
grains['num_cpus'] = int(grains['num_cpus'])
except ValueError:
grains['num_cpus'] = 1
return grains
|
null | null | null | What does this function do? | def getGNUTranslatorFilesUnmodified():
return archive.getFilesWithFileTypesWithoutWords(getImportPluginFileNames())
| null | null | null | Get the file types from the translators in the import plugins folder. | pcsd | def get GNU Translator Files Unmodified return archive get Files With File Types Without Words get Import Plugin File Names | 9228 | def getGNUTranslatorFilesUnmodified():
return archive.getFilesWithFileTypesWithoutWords(getImportPluginFileNames())
| Get the file types from the translators in the import plugins folder. | get the file types from the translators in the import plugins folder . | Question:
What does this function do?
Code:
def getGNUTranslatorFilesUnmodified():
return archive.getFilesWithFileTypesWithoutWords(getImportPluginFileNames())
|
null | null | null | What does this function do? | def compare(name, first, second, bfr):
return (bfr[first.begin:first.end] == bfr[second.begin:second.end])
| null | null | null | Pair the appropriate open bracket with its close. | pcsd | def compare name first second bfr return bfr[first begin first end] == bfr[second begin second end] | 9230 | def compare(name, first, second, bfr):
return (bfr[first.begin:first.end] == bfr[second.begin:second.end])
| Pair the appropriate open bracket with its close. | pair the appropriate open bracket with its close . | Question:
What does this function do?
Code:
def compare(name, first, second, bfr):
return (bfr[first.begin:first.end] == bfr[second.begin:second.end])
|
null | null | null | What does this function do? | def fix(value):
return ((value + (2 ** 32)) if (value < 0) else value)
| null | null | null | Turn negative 32-bit numbers into positive numbers. | pcsd | def fix value return value + 2 ** 32 if value < 0 else value | 9232 | def fix(value):
return ((value + (2 ** 32)) if (value < 0) else value)
| Turn negative 32-bit numbers into positive numbers. | turn negative 32 - bit numbers into positive numbers . | Question:
What does this function do?
Code:
def fix(value):
return ((value + (2 ** 32)) if (value < 0) else value)
|
null | null | null | What does this function do? | def register(**kwargs):
def decorator(func):
_CALL_REGISTRY[kwargs.get(API_SYM, func.__name__)] = func
return func
return decorator
| null | null | null | Decorator for registering API function.
Does not do any check or validation. | pcsd | def register **kwargs def decorator func CALL REGISTRY[kwargs get API SYM func name ] = func return func return decorator | 9238 | def register(**kwargs):
def decorator(func):
_CALL_REGISTRY[kwargs.get(API_SYM, func.__name__)] = func
return func
return decorator
| Decorator for registering API function.
Does not do any check or validation. | decorator for registering api function . | Question:
What does this function do?
Code:
def register(**kwargs):
def decorator(func):
_CALL_REGISTRY[kwargs.get(API_SYM, func.__name__)] = func
return func
return decorator
|
null | null | null | What does this function do? | def register(linter):
linter.register_checker(FormatChecker(linter))
| null | null | null | required method to auto register this checker | pcsd | def register linter linter register checker Format Checker linter | 9240 | def register(linter):
linter.register_checker(FormatChecker(linter))
| required method to auto register this checker | required method to auto register this checker | Question:
What does this function do?
Code:
def register(linter):
linter.register_checker(FormatChecker(linter))
|
null | null | null | What does this function do? | def sendOutputTo(outputTo, text):
if outputTo.endswith('stderr'):
sys.stderr.write(text)
sys.stderr.write('\n')
sys.stderr.flush()
return
if outputTo.endswith('stdout'):
sys.stdout.write(text)
sys.stdout.write('\n')
sys.stdout.flush()
return
archive.writeFileText(outputTo, text)
| null | null | null | Send output to a file or a standard output. | pcsd | def send Output To output To text if output To endswith 'stderr' sys stderr write text sys stderr write ' ' sys stderr flush return if output To endswith 'stdout' sys stdout write text sys stdout write ' ' sys stdout flush return archive write File Text output To text | 9241 | def sendOutputTo(outputTo, text):
if outputTo.endswith('stderr'):
sys.stderr.write(text)
sys.stderr.write('\n')
sys.stderr.flush()
return
if outputTo.endswith('stdout'):
sys.stdout.write(text)
sys.stdout.write('\n')
sys.stdout.flush()
return
archive.writeFileText(outputTo, text)
| Send output to a file or a standard output. | send output to a file or a standard output . | Question:
What does this function do?
Code:
def sendOutputTo(outputTo, text):
if outputTo.endswith('stderr'):
sys.stderr.write(text)
sys.stderr.write('\n')
sys.stderr.flush()
return
if outputTo.endswith('stdout'):
sys.stdout.write(text)
sys.stdout.write('\n')
sys.stdout.flush()
return
archive.writeFileText(outputTo, text)
|
null | null | null | What does this function do? | def to_string_from_fields(item_dict, fields, interface_fields=None):
buf = ''
keys = []
for elem in fields:
keys.append((elem[0], elem[3], elem[4]))
keys.sort()
buf += ('%-30s : %s\n' % ('Name', item_dict['name']))
for (k, nicename, editable) in keys:
if (not editable):
continue
if (k != 'name'):
buf += ('%-30s : %s\n' % (nicename, item_dict[k]))
if (('interfaces' in item_dict) and (interface_fields is not None)):
keys = []
for elem in interface_fields:
keys.append((elem[0], elem[3], elem[4]))
keys.sort()
for iname in item_dict['interfaces'].keys():
buf += ('%-30s : %s\n' % ('Interface ===== ', iname))
for (k, nicename, editable) in keys:
if editable:
buf += ('%-30s : %s\n' % (nicename, item_dict['interfaces'][iname].get(k, '')))
return buf
| null | null | null | item_dict is a dictionary, fields is something like item_distro.FIELDS | pcsd | def to string from fields item dict fields interface fields=None buf = '' keys = [] for elem in fields keys append elem[0] elem[3] elem[4] keys sort buf += '%-30s %s ' % 'Name' item dict['name'] for k nicename editable in keys if not editable continue if k != 'name' buf += '%-30s %s ' % nicename item dict[k] if 'interfaces' in item dict and interface fields is not None keys = [] for elem in interface fields keys append elem[0] elem[3] elem[4] keys sort for iname in item dict['interfaces'] keys buf += '%-30s %s ' % 'Interface ===== ' iname for k nicename editable in keys if editable buf += '%-30s %s ' % nicename item dict['interfaces'][iname] get k '' return buf | 9242 | def to_string_from_fields(item_dict, fields, interface_fields=None):
buf = ''
keys = []
for elem in fields:
keys.append((elem[0], elem[3], elem[4]))
keys.sort()
buf += ('%-30s : %s\n' % ('Name', item_dict['name']))
for (k, nicename, editable) in keys:
if (not editable):
continue
if (k != 'name'):
buf += ('%-30s : %s\n' % (nicename, item_dict[k]))
if (('interfaces' in item_dict) and (interface_fields is not None)):
keys = []
for elem in interface_fields:
keys.append((elem[0], elem[3], elem[4]))
keys.sort()
for iname in item_dict['interfaces'].keys():
buf += ('%-30s : %s\n' % ('Interface ===== ', iname))
for (k, nicename, editable) in keys:
if editable:
buf += ('%-30s : %s\n' % (nicename, item_dict['interfaces'][iname].get(k, '')))
return buf
| item_dict is a dictionary, fields is something like item_distro.FIELDS | item _ dict is a dictionary , fields is something like item _ distro . fields | Question:
What does this function do?
Code:
def to_string_from_fields(item_dict, fields, interface_fields=None):
buf = ''
keys = []
for elem in fields:
keys.append((elem[0], elem[3], elem[4]))
keys.sort()
buf += ('%-30s : %s\n' % ('Name', item_dict['name']))
for (k, nicename, editable) in keys:
if (not editable):
continue
if (k != 'name'):
buf += ('%-30s : %s\n' % (nicename, item_dict[k]))
if (('interfaces' in item_dict) and (interface_fields is not None)):
keys = []
for elem in interface_fields:
keys.append((elem[0], elem[3], elem[4]))
keys.sort()
for iname in item_dict['interfaces'].keys():
buf += ('%-30s : %s\n' % ('Interface ===== ', iname))
for (k, nicename, editable) in keys:
if editable:
buf += ('%-30s : %s\n' % (nicename, item_dict['interfaces'][iname].get(k, '')))
return buf
|
null | null | null | What does this function do? | def check_replica_primary(con, host, warning, critical, perf_data, replicaset, mongo_version):
if ((warning is None) and (critical is None)):
warning = 1
warning = (warning or 2)
critical = (critical or 2)
primary_status = 0
message = 'Primary server has not changed'
db = con['nagios']
data = get_server_status(con)
if (replicaset != data['repl'].get('setName')):
message = ('Replica set requested: %s differs from the one found: %s' % (replicaset, data['repl'].get('setName')))
primary_status = 2
return check_levels(primary_status, warning, critical, message)
current_primary = data['repl'].get('primary')
saved_primary = get_stored_primary_server_name(db)
if (current_primary is None):
current_primary = 'None'
if (saved_primary is None):
saved_primary = 'None'
if (current_primary != saved_primary):
last_primary_server_record = {'server': current_primary}
if (mongo_version == 2):
db.last_primary_server.update({'_id': 'last_primary'}, {'$set': last_primary_server_record}, upsert=True)
else:
db.last_primary_server.update_one({'_id': 'last_primary'}, {'$set': last_primary_server_record}, upsert=True)
message = ('Primary server has changed from %s to %s' % (saved_primary, current_primary))
primary_status = 1
return check_levels(primary_status, warning, critical, message)
| null | null | null | A function to check if the primary server of a replica set has changed | pcsd | def check replica primary con host warning critical perf data replicaset mongo version if warning is None and critical is None warning = 1 warning = warning or 2 critical = critical or 2 primary status = 0 message = 'Primary server has not changed' db = con['nagios'] data = get server status con if replicaset != data['repl'] get 'set Name' message = 'Replica set requested %s differs from the one found %s' % replicaset data['repl'] get 'set Name' primary status = 2 return check levels primary status warning critical message current primary = data['repl'] get 'primary' saved primary = get stored primary server name db if current primary is None current primary = 'None' if saved primary is None saved primary = 'None' if current primary != saved primary last primary server record = {'server' current primary} if mongo version == 2 db last primary server update {' id' 'last primary'} {'$set' last primary server record} upsert=True else db last primary server update one {' id' 'last primary'} {'$set' last primary server record} upsert=True message = 'Primary server has changed from %s to %s' % saved primary current primary primary status = 1 return check levels primary status warning critical message | 9246 | def check_replica_primary(con, host, warning, critical, perf_data, replicaset, mongo_version):
if ((warning is None) and (critical is None)):
warning = 1
warning = (warning or 2)
critical = (critical or 2)
primary_status = 0
message = 'Primary server has not changed'
db = con['nagios']
data = get_server_status(con)
if (replicaset != data['repl'].get('setName')):
message = ('Replica set requested: %s differs from the one found: %s' % (replicaset, data['repl'].get('setName')))
primary_status = 2
return check_levels(primary_status, warning, critical, message)
current_primary = data['repl'].get('primary')
saved_primary = get_stored_primary_server_name(db)
if (current_primary is None):
current_primary = 'None'
if (saved_primary is None):
saved_primary = 'None'
if (current_primary != saved_primary):
last_primary_server_record = {'server': current_primary}
if (mongo_version == 2):
db.last_primary_server.update({'_id': 'last_primary'}, {'$set': last_primary_server_record}, upsert=True)
else:
db.last_primary_server.update_one({'_id': 'last_primary'}, {'$set': last_primary_server_record}, upsert=True)
message = ('Primary server has changed from %s to %s' % (saved_primary, current_primary))
primary_status = 1
return check_levels(primary_status, warning, critical, message)
| A function to check if the primary server of a replica set has changed | a function to check if the primary server of a replica set has changed | Question:
What does this function do?
Code:
def check_replica_primary(con, host, warning, critical, perf_data, replicaset, mongo_version):
if ((warning is None) and (critical is None)):
warning = 1
warning = (warning or 2)
critical = (critical or 2)
primary_status = 0
message = 'Primary server has not changed'
db = con['nagios']
data = get_server_status(con)
if (replicaset != data['repl'].get('setName')):
message = ('Replica set requested: %s differs from the one found: %s' % (replicaset, data['repl'].get('setName')))
primary_status = 2
return check_levels(primary_status, warning, critical, message)
current_primary = data['repl'].get('primary')
saved_primary = get_stored_primary_server_name(db)
if (current_primary is None):
current_primary = 'None'
if (saved_primary is None):
saved_primary = 'None'
if (current_primary != saved_primary):
last_primary_server_record = {'server': current_primary}
if (mongo_version == 2):
db.last_primary_server.update({'_id': 'last_primary'}, {'$set': last_primary_server_record}, upsert=True)
else:
db.last_primary_server.update_one({'_id': 'last_primary'}, {'$set': last_primary_server_record}, upsert=True)
message = ('Primary server has changed from %s to %s' % (saved_primary, current_primary))
primary_status = 1
return check_levels(primary_status, warning, critical, message)
|
null | null | null | What does this function do? | @register.filter(is_safe=True)
@stringfilter
def wordwrap(value, arg):
return wrap(value, int(arg))
| null | null | null | Wraps words at specified line length.
Argument: number of characters to wrap the text at. | pcsd | @register filter is safe=True @stringfilter def wordwrap value arg return wrap value int arg | 9249 | @register.filter(is_safe=True)
@stringfilter
def wordwrap(value, arg):
return wrap(value, int(arg))
| Wraps words at specified line length.
Argument: number of characters to wrap the text at. | wraps words at specified line length . | Question:
What does this function do?
Code:
@register.filter(is_safe=True)
@stringfilter
def wordwrap(value, arg):
return wrap(value, int(arg))
|
null | null | null | What does this function do? | def data_profiling_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if (current_app.config['LOGIN_DISABLED'] or ((not current_user.is_anonymous()) and current_user.data_profiling())):
return f(*args, **kwargs)
else:
flash('This page requires data profiling privileges', 'error')
return redirect(url_for('admin.index'))
return decorated_function
| null | null | null | Decorator for views requiring data profiling access | pcsd | def data profiling required f @wraps f def decorated function *args **kwargs if current app config['LOGIN DISABLED'] or not current user is anonymous and current user data profiling return f *args **kwargs else flash 'This page requires data profiling privileges' 'error' return redirect url for 'admin index' return decorated function | 9254 | def data_profiling_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if (current_app.config['LOGIN_DISABLED'] or ((not current_user.is_anonymous()) and current_user.data_profiling())):
return f(*args, **kwargs)
else:
flash('This page requires data profiling privileges', 'error')
return redirect(url_for('admin.index'))
return decorated_function
| Decorator for views requiring data profiling access | decorator for views requiring data profiling access | Question:
What does this function do?
Code:
def data_profiling_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if (current_app.config['LOGIN_DISABLED'] or ((not current_user.is_anonymous()) and current_user.data_profiling())):
return f(*args, **kwargs)
else:
flash('This page requires data profiling privileges', 'error')
return redirect(url_for('admin.index'))
return decorated_function
|
null | null | null | What does this function do? | def _url(data=None):
data = (data or {})
data = '&'.join(['{}={}'.format(name, value) for (name, value) in data.items()])
return '{}{}locative?{}'.format(HTTP_BASE_URL, const.URL_API, data)
| null | null | null | Helper method to generate URLs. | pcsd | def url data=None data = data or {} data = '&' join ['{}={}' format name value for name value in data items ] return '{}{}locative?{}' format HTTP BASE URL const URL API data | 9257 | def _url(data=None):
data = (data or {})
data = '&'.join(['{}={}'.format(name, value) for (name, value) in data.items()])
return '{}{}locative?{}'.format(HTTP_BASE_URL, const.URL_API, data)
| Helper method to generate URLs. | helper method to generate urls . | Question:
What does this function do?
Code:
def _url(data=None):
data = (data or {})
data = '&'.join(['{}={}'.format(name, value) for (name, value) in data.items()])
return '{}{}locative?{}'.format(HTTP_BASE_URL, const.URL_API, data)
|
null | null | null | What does this function do? | def sca(ax):
managers = _pylab_helpers.Gcf.get_all_fig_managers()
for m in managers:
if (ax in m.canvas.figure.axes):
_pylab_helpers.Gcf.set_active(m)
m.canvas.figure.sca(ax)
return
raise ValueError(u'Axes instance argument was not found in a figure.')
| null | null | null | Set the current Axes instance to *ax*.
The current Figure is updated to the parent of *ax*. | pcsd | def sca ax managers = pylab helpers Gcf get all fig managers for m in managers if ax in m canvas figure axes pylab helpers Gcf set active m m canvas figure sca ax return raise Value Error u'Axes instance argument was not found in a figure ' | 9263 | def sca(ax):
managers = _pylab_helpers.Gcf.get_all_fig_managers()
for m in managers:
if (ax in m.canvas.figure.axes):
_pylab_helpers.Gcf.set_active(m)
m.canvas.figure.sca(ax)
return
raise ValueError(u'Axes instance argument was not found in a figure.')
| Set the current Axes instance to *ax*.
The current Figure is updated to the parent of *ax*. | set the current axes instance to * ax * . | Question:
What does this function do?
Code:
def sca(ax):
managers = _pylab_helpers.Gcf.get_all_fig_managers()
for m in managers:
if (ax in m.canvas.figure.axes):
_pylab_helpers.Gcf.set_active(m)
m.canvas.figure.sca(ax)
return
raise ValueError(u'Axes instance argument was not found in a figure.')
|
null | null | null | What does this function do? | def create_file(path):
with open(path, u'w') as f:
f.write(u'Just a sentinel.')
| null | null | null | Creates a file at the given path. Actually, leaves evidence that the
job ran. | pcsd | def create file path with open path u'w' as f f write u'Just a sentinel ' | 9265 | def create_file(path):
with open(path, u'w') as f:
f.write(u'Just a sentinel.')
| Creates a file at the given path. Actually, leaves evidence that the
job ran. | creates a file at the given path . | Question:
What does this function do?
Code:
def create_file(path):
with open(path, u'w') as f:
f.write(u'Just a sentinel.')
|
null | null | null | What does this function do? | def foreign_keys(model):
return [column.name for column in foreign_key_columns(model)]
| null | null | null | Returns a list of the names of columns that contain foreign keys for
relationships in the specified model class. | pcsd | def foreign keys model return [column name for column in foreign key columns model ] | 9272 | def foreign_keys(model):
return [column.name for column in foreign_key_columns(model)]
| Returns a list of the names of columns that contain foreign keys for
relationships in the specified model class. | returns a list of the names of columns that contain foreign keys for relationships in the specified model class . | Question:
What does this function do?
Code:
def foreign_keys(model):
return [column.name for column in foreign_key_columns(model)]
|
null | null | null | What does this function do? | def demo_update_two(filename):
f = get_contents(filename)
if (not len(f.strip())):
return ''
f = (f + '\n')
return f
| null | null | null | repostion division statement | pcsd | def demo update two filename f = get contents filename if not len f strip return '' f = f + ' ' return f | 9278 | def demo_update_two(filename):
f = get_contents(filename)
if (not len(f.strip())):
return ''
f = (f + '\n')
return f
| repostion division statement | repostion division statement | Question:
What does this function do?
Code:
def demo_update_two(filename):
f = get_contents(filename)
if (not len(f.strip())):
return ''
f = (f + '\n')
return f
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.