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 check_space_for_graph(outfile_name, hash_size, force, _testhook_free_space=None): dir_path = os.path.dirname(os.path.realpath(outfile_name)) target = os.statvfs(dir_path) if (_testhook_free_space is None): free_space = (target.f_frsize * target.f_bavail) else: free_space = _testhook_free_space size_diff = ...
null
null
null
Check that we have enough size to write the specified graph. The "hash_size" parameter should equal the total bytes required for the entire data structure.
pcsd
def check space for graph outfile name hash size force testhook free space=None dir path = os path dirname os path realpath outfile name target = os statvfs dir path if testhook free space is None free space = target f frsize * target f bavail else free space = testhook free space size diff = hash size - free space if ...
3611
def check_space_for_graph(outfile_name, hash_size, force, _testhook_free_space=None): dir_path = os.path.dirname(os.path.realpath(outfile_name)) target = os.statvfs(dir_path) if (_testhook_free_space is None): free_space = (target.f_frsize * target.f_bavail) else: free_space = _testhook_free_space size_diff = ...
Check that we have enough size to write the specified graph. The "hash_size" parameter should equal the total bytes required for the entire data structure.
check that we have enough size to write the specified graph .
Question: What does this function do? Code: def check_space_for_graph(outfile_name, hash_size, force, _testhook_free_space=None): dir_path = os.path.dirname(os.path.realpath(outfile_name)) target = os.statvfs(dir_path) if (_testhook_free_space is None): free_space = (target.f_frsize * target.f_bavail) else: ...
null
null
null
What does this function do?
def inet_pton(af, addr): if (af == socket.AF_INET): return socket.inet_aton(addr) elif (af == socket.AF_INET6): try: return socket.inet_pton(af, addr) except AttributeError: pass JOKER = '*' while ('::' in addr): addr = addr.replace('::', ((':' + JOKER) + ':')) joker_pos = None ipv4_addr = None...
null
null
null
Convert an IP address from text representation into binary form
pcsd
def inet pton af addr if af == socket AF INET return socket inet aton addr elif af == socket AF INET6 try return socket inet pton af addr except Attribute Error pass JOKER = '*' while ' ' in addr addr = addr replace ' ' ' ' + JOKER + ' ' joker pos = None ipv4 addr = None if ' ' in addr ipv4 addr = addr split ' ' [ -1 ]...
3617
def inet_pton(af, addr): if (af == socket.AF_INET): return socket.inet_aton(addr) elif (af == socket.AF_INET6): try: return socket.inet_pton(af, addr) except AttributeError: pass JOKER = '*' while ('::' in addr): addr = addr.replace('::', ((':' + JOKER) + ':')) joker_pos = None ipv4_addr = None...
Convert an IP address from text representation into binary form
convert an ip address from text representation into binary form
Question: What does this function do? Code: def inet_pton(af, addr): if (af == socket.AF_INET): return socket.inet_aton(addr) elif (af == socket.AF_INET6): try: return socket.inet_pton(af, addr) except AttributeError: pass JOKER = '*' while ('::' in addr): addr = addr.replace('::', ((':' + JOKER...
null
null
null
What does this function do?
def pyimplementation(): if hasattr(_platform, u'python_implementation'): return _platform.python_implementation() elif sys.platform.startswith(u'java'): return (u'Jython ' + sys.platform) elif hasattr(sys, u'pypy_version_info'): v = u'.'.join((str(p) for p in sys.pypy_version_info[:3])) if sys.pypy_version_i...
null
null
null
Return string identifying the current Python implementation.
pcsd
def pyimplementation if hasattr platform u'python implementation' return platform python implementation elif sys platform startswith u'java' return u'Jython ' + sys platform elif hasattr sys u'pypy version info' v = u' ' join str p for p in sys pypy version info[ 3] if sys pypy version info[3 ] v += u'-' + u'' join str...
3618
def pyimplementation(): if hasattr(_platform, u'python_implementation'): return _platform.python_implementation() elif sys.platform.startswith(u'java'): return (u'Jython ' + sys.platform) elif hasattr(sys, u'pypy_version_info'): v = u'.'.join((str(p) for p in sys.pypy_version_info[:3])) if sys.pypy_version_i...
Return string identifying the current Python implementation.
return string identifying the current python implementation .
Question: What does this function do? Code: def pyimplementation(): if hasattr(_platform, u'python_implementation'): return _platform.python_implementation() elif sys.platform.startswith(u'java'): return (u'Jython ' + sys.platform) elif hasattr(sys, u'pypy_version_info'): v = u'.'.join((str(p) for p in sys....
null
null
null
What does this function do?
@login_required def order_history(request, template=u'shop/order_history.html', extra_context=None): all_orders = Order.objects.filter(user_id=request.user.id).annotate(quantity_total=Sum(u'items__quantity')) orders = paginate(all_orders.order_by(u'-time'), request.GET.get(u'page', 1), settings.SHOP_PER_PAGE_CATEGORY...
null
null
null
Display a list of the currently logged-in user\'s past orders.
pcsd
@login required def order history request template=u'shop/order history html' extra context=None all orders = Order objects filter user id=request user id annotate quantity total=Sum u'items quantity' orders = paginate all orders order by u'-time' request GET get u'page' 1 settings SHOP PER PAGE CATEGORY settings MAX P...
3620
@login_required def order_history(request, template=u'shop/order_history.html', extra_context=None): all_orders = Order.objects.filter(user_id=request.user.id).annotate(quantity_total=Sum(u'items__quantity')) orders = paginate(all_orders.order_by(u'-time'), request.GET.get(u'page', 1), settings.SHOP_PER_PAGE_CATEGORY...
Display a list of the currently logged-in user\'s past orders.
display a list of the currently logged - in users past orders .
Question: What does this function do? Code: @login_required def order_history(request, template=u'shop/order_history.html', extra_context=None): all_orders = Order.objects.filter(user_id=request.user.id).annotate(quantity_total=Sum(u'items__quantity')) orders = paginate(all_orders.order_by(u'-time'), request.GET.g...
null
null
null
What does this function do?
def updatecache(filename, module_globals=None): if (filename in cache): del cache[filename] if ((not filename) or ((filename[0] + filename[(-1)]) == '<>')): return [] fullname = filename try: stat = os.stat(fullname) except os.error as msg: basename = os.path.split(filename)[1] if (module_globals and ('_...
null
null
null
Update a cache entry and return its list of lines. If something\'s wrong, print a message, discard the cache entry, and return an empty list.
pcsd
def updatecache filename module globals=None if filename in cache del cache[filename] if not filename or filename[0] + filename[ -1 ] == '<>' return [] fullname = filename try stat = os stat fullname except os error as msg basename = os path split filename [1] if module globals and ' loader ' in module globals name = m...
3629
def updatecache(filename, module_globals=None): if (filename in cache): del cache[filename] if ((not filename) or ((filename[0] + filename[(-1)]) == '<>')): return [] fullname = filename try: stat = os.stat(fullname) except os.error as msg: basename = os.path.split(filename)[1] if (module_globals and ('_...
Update a cache entry and return its list of lines. If something\'s wrong, print a message, discard the cache entry, and return an empty list.
update a cache entry and return its list of lines .
Question: What does this function do? Code: def updatecache(filename, module_globals=None): if (filename in cache): del cache[filename] if ((not filename) or ((filename[0] + filename[(-1)]) == '<>')): return [] fullname = filename try: stat = os.stat(fullname) except os.error as msg: basename = os.path....
null
null
null
What does this function do?
def _blade_action_postfunc(closing_message): console.info(closing_message) SCons.SConsign.write()
null
null
null
To do post jobs if blade\'s own actions failed to build.
pcsd
def blade action postfunc closing message console info closing message S Cons S Consign write
3631
def _blade_action_postfunc(closing_message): console.info(closing_message) SCons.SConsign.write()
To do post jobs if blade\'s own actions failed to build.
to do post jobs if blades own actions failed to build .
Question: What does this function do? Code: def _blade_action_postfunc(closing_message): console.info(closing_message) SCons.SConsign.write()
null
null
null
What does this function do?
def request_server_info(server): if (not server.request): server.request = True Thread(target=_retrieve_info, args=(server,)).start()
null
null
null
Launch async request to resolve server address
pcsd
def request server info server if not server request server request = True Thread target= retrieve info args= server start
3640
def request_server_info(server): if (not server.request): server.request = True Thread(target=_retrieve_info, args=(server,)).start()
Launch async request to resolve server address
launch async request to resolve server address
Question: What does this function do? Code: def request_server_info(server): if (not server.request): server.request = True Thread(target=_retrieve_info, args=(server,)).start()
null
null
null
What does this function do?
def response_namespace(k, v): if (k[:8] == 'headers.'): cherrypy.serving.response.headers[k.split('.', 1)[1]] = v else: setattr(cherrypy.serving.response, k, v)
null
null
null
Attach response attributes declared in config.
pcsd
def response namespace k v if k[ 8] == 'headers ' cherrypy serving response headers[k split ' ' 1 [1]] = v else setattr cherrypy serving response k v
3662
def response_namespace(k, v): if (k[:8] == 'headers.'): cherrypy.serving.response.headers[k.split('.', 1)[1]] = v else: setattr(cherrypy.serving.response, k, v)
Attach response attributes declared in config.
attach response attributes declared in config .
Question: What does this function do? Code: def response_namespace(k, v): if (k[:8] == 'headers.'): cherrypy.serving.response.headers[k.split('.', 1)[1]] = v else: setattr(cherrypy.serving.response, k, v)
null
null
null
What does this function do?
@task @needs('pavelib.prereqs.install_prereqs') @cmdopts([('settings=', 's', 'Django settings')]) def celery(options): settings = getattr(options, 'settings', 'dev_with_worker') run_process(django_cmd('lms', settings, 'celery', 'worker', '--beat', '--loglevel=INFO', '--pythonpath=.'))
null
null
null
Runs Celery workers.
pcsd
@task @needs 'pavelib prereqs install prereqs' @cmdopts [ 'settings=' 's' 'Django settings' ] def celery options settings = getattr options 'settings' 'dev with worker' run process django cmd 'lms' settings 'celery' 'worker' '--beat' '--loglevel=INFO' '--pythonpath= '
3674
@task @needs('pavelib.prereqs.install_prereqs') @cmdopts([('settings=', 's', 'Django settings')]) def celery(options): settings = getattr(options, 'settings', 'dev_with_worker') run_process(django_cmd('lms', settings, 'celery', 'worker', '--beat', '--loglevel=INFO', '--pythonpath=.'))
Runs Celery workers.
runs celery workers .
Question: What does this function do? Code: @task @needs('pavelib.prereqs.install_prereqs') @cmdopts([('settings=', 's', 'Django settings')]) def celery(options): settings = getattr(options, 'settings', 'dev_with_worker') run_process(django_cmd('lms', settings, 'celery', 'worker', '--beat', '--loglevel=INFO', '--p...
null
null
null
What does this function do?
def command_map(args): if (multiprocessing.current_process().name != 'MainProcess'): logger.initMultiprocessing() try: return command(*args) except Exception: logger.exception('Encoder raised an exception.') return False
null
null
null
Wrapper for the \'[multiprocessing.]map()\' method, to unpack the arguments and wrap exceptions.
pcsd
def command map args if multiprocessing current process name != 'Main Process' logger init Multiprocessing try return command *args except Exception logger exception 'Encoder raised an exception ' return False
3675
def command_map(args): if (multiprocessing.current_process().name != 'MainProcess'): logger.initMultiprocessing() try: return command(*args) except Exception: logger.exception('Encoder raised an exception.') return False
Wrapper for the \'[multiprocessing.]map()\' method, to unpack the arguments and wrap exceptions.
wrapper for the [ multiprocessing . ] map ( ) method , to unpack the arguments and wrap exceptions .
Question: What does this function do? Code: def command_map(args): if (multiprocessing.current_process().name != 'MainProcess'): logger.initMultiprocessing() try: return command(*args) except Exception: logger.exception('Encoder raised an exception.') return False
null
null
null
What does this function do?
def resolve(thing, forceload=0): if isinstance(thing, str): object = locate(thing, forceload) if (not object): raise ImportError, ('no Python documentation found for %r' % thing) return (object, thing) else: return (thing, getattr(thing, '__name__', None))
null
null
null
Given an object or a path to an object, get the object and its name.
pcsd
def resolve thing forceload=0 if isinstance thing str object = locate thing forceload if not object raise Import Error 'no Python documentation found for %r' % thing return object thing else return thing getattr thing ' name ' None
3681
def resolve(thing, forceload=0): if isinstance(thing, str): object = locate(thing, forceload) if (not object): raise ImportError, ('no Python documentation found for %r' % thing) return (object, thing) else: return (thing, getattr(thing, '__name__', None))
Given an object or a path to an object, get the object and its name.
given an object or a path to an object , get the object and its name .
Question: What does this function do? Code: def resolve(thing, forceload=0): if isinstance(thing, str): object = locate(thing, forceload) if (not object): raise ImportError, ('no Python documentation found for %r' % thing) return (object, thing) else: return (thing, getattr(thing, '__name__', None))
null
null
null
What does this function do?
@_get_client def image_property_delete(client, prop_ref, image_ref, session=None): return client.image_property_delete(prop_ref=prop_ref, image_ref=image_ref)
null
null
null
Used internally by _image_property_create and image_property_update
pcsd
@ get client def image property delete client prop ref image ref session=None return client image property delete prop ref=prop ref image ref=image ref
3682
@_get_client def image_property_delete(client, prop_ref, image_ref, session=None): return client.image_property_delete(prop_ref=prop_ref, image_ref=image_ref)
Used internally by _image_property_create and image_property_update
used internally by _ image _ property _ create and image _ property _ update
Question: What does this function do? Code: @_get_client def image_property_delete(client, prop_ref, image_ref, session=None): return client.image_property_delete(prop_ref=prop_ref, image_ref=image_ref)
null
null
null
What does this function do?
def _read_buckets_cache_file(cache_file): log.debug('Reading buckets cache file') with salt.utils.fopen(cache_file, 'rb') as fp_: data = pickle.load(fp_) return data
null
null
null
Return the contents of the buckets cache file
pcsd
def read buckets cache file cache file log debug 'Reading buckets cache file' with salt utils fopen cache file 'rb' as fp data = pickle load fp return data
3686
def _read_buckets_cache_file(cache_file): log.debug('Reading buckets cache file') with salt.utils.fopen(cache_file, 'rb') as fp_: data = pickle.load(fp_) return data
Return the contents of the buckets cache file
return the contents of the buckets cache file
Question: What does this function do? Code: def _read_buckets_cache_file(cache_file): log.debug('Reading buckets cache file') with salt.utils.fopen(cache_file, 'rb') as fp_: data = pickle.load(fp_) return data
null
null
null
What does this function do?
def getouterframes(frame, context=1): framelist = [] while frame: framelist.append(((frame,) + getframeinfo(frame, context))) frame = frame.f_back return framelist
null
null
null
Get a list of records for a frame and all higher (calling) frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context.
pcsd
def getouterframes frame context=1 framelist = [] while frame framelist append frame + getframeinfo frame context frame = frame f back return framelist
3693
def getouterframes(frame, context=1): framelist = [] while frame: framelist.append(((frame,) + getframeinfo(frame, context))) frame = frame.f_back return framelist
Get a list of records for a frame and all higher (calling) frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context.
get a list of records for a frame and all higher frames .
Question: What does this function do? Code: def getouterframes(frame, context=1): framelist = [] while frame: framelist.append(((frame,) + getframeinfo(frame, context))) frame = frame.f_back return framelist
null
null
null
What does this function do?
@conf.commands.register def fuzz(p, _inplace=0): if (not _inplace): p = p.copy() q = p while (not isinstance(q, NoPayload)): for f in q.fields_desc: if isinstance(f, PacketListField): for r in getattr(q, f.name): print 'fuzzing', repr(r) fuzz(r, _inplace=1) elif (f.default is not None): r...
null
null
null
Transform a layer into a fuzzy layer by replacing some default values by random objects
pcsd
@conf commands register def fuzz p inplace=0 if not inplace p = p copy q = p while not isinstance q No Payload for f in q fields desc if isinstance f Packet List Field for r in getattr q f name print 'fuzzing' repr r fuzz r inplace=1 elif f default is not None rnd = f randval if rnd is not None q default fields[f name]...
3698
@conf.commands.register def fuzz(p, _inplace=0): if (not _inplace): p = p.copy() q = p while (not isinstance(q, NoPayload)): for f in q.fields_desc: if isinstance(f, PacketListField): for r in getattr(q, f.name): print 'fuzzing', repr(r) fuzz(r, _inplace=1) elif (f.default is not None): r...
Transform a layer into a fuzzy layer by replacing some default values by random objects
transform a layer into a fuzzy layer by replacing some default values by random objects
Question: What does this function do? Code: @conf.commands.register def fuzz(p, _inplace=0): if (not _inplace): p = p.copy() q = p while (not isinstance(q, NoPayload)): for f in q.fields_desc: if isinstance(f, PacketListField): for r in getattr(q, f.name): print 'fuzzing', repr(r) fuzz(r, _in...
null
null
null
What does this function do?
def synchronize(): _lazy_init() return torch._C._cuda_synchronize()
null
null
null
Waits for all kernels in all streams on current device to complete.
pcsd
def synchronize lazy init return torch C cuda synchronize
3699
def synchronize(): _lazy_init() return torch._C._cuda_synchronize()
Waits for all kernels in all streams on current device to complete.
waits for all kernels in all streams on current device to complete .
Question: What does this function do? Code: def synchronize(): _lazy_init() return torch._C._cuda_synchronize()
null
null
null
What does this function do?
def run_pre_commit_script(component, translation, filename): run_hook(component, translation, component.pre_commit_script, None, filename)
null
null
null
Pre commit hook
pcsd
def run pre commit script component translation filename run hook component translation component pre commit script None filename
3705
def run_pre_commit_script(component, translation, filename): run_hook(component, translation, component.pre_commit_script, None, filename)
Pre commit hook
pre commit hook
Question: What does this function do? Code: def run_pre_commit_script(component, translation, filename): run_hook(component, translation, component.pre_commit_script, None, filename)
null
null
null
What does this function do?
def _translate_attachment_summary_view(_context, vol): d = {} volume_id = vol['id'] d['id'] = volume_id d['volume_id'] = volume_id d['server_id'] = vol['instance_uuid'] if vol.get('mountpoint'): d['device'] = vol['mountpoint'] return d
null
null
null
Maps keys for attachment summary view.
pcsd
def translate attachment summary view context vol d = {} volume id = vol['id'] d['id'] = volume id d['volume id'] = volume id d['server id'] = vol['instance uuid'] if vol get 'mountpoint' d['device'] = vol['mountpoint'] return d
3706
def _translate_attachment_summary_view(_context, vol): d = {} volume_id = vol['id'] d['id'] = volume_id d['volume_id'] = volume_id d['server_id'] = vol['instance_uuid'] if vol.get('mountpoint'): d['device'] = vol['mountpoint'] return d
Maps keys for attachment summary view.
maps keys for attachment summary view .
Question: What does this function do? Code: def _translate_attachment_summary_view(_context, vol): d = {} volume_id = vol['id'] d['id'] = volume_id d['volume_id'] = volume_id d['server_id'] = vol['instance_uuid'] if vol.get('mountpoint'): d['device'] = vol['mountpoint'] return d
null
null
null
What does this function do?
def category_structure(category, site): return {'description': category.title, 'htmlUrl': ('%s://%s%s' % (PROTOCOL, site.domain, category.get_absolute_url())), 'rssUrl': ('%s://%s%s' % (PROTOCOL, site.domain, reverse('zinnia:category_feed', args=[category.tree_path]))), 'categoryId': category.pk, 'parentId': ((categor...
null
null
null
A category structure.
pcsd
def category structure category site return {'description' category title 'html Url' '%s //%s%s' % PROTOCOL site domain category get absolute url 'rss Url' '%s //%s%s' % PROTOCOL site domain reverse 'zinnia category feed' args=[category tree path] 'category Id' category pk 'parent Id' category parent and category paren...
3709
def category_structure(category, site): return {'description': category.title, 'htmlUrl': ('%s://%s%s' % (PROTOCOL, site.domain, category.get_absolute_url())), 'rssUrl': ('%s://%s%s' % (PROTOCOL, site.domain, reverse('zinnia:category_feed', args=[category.tree_path]))), 'categoryId': category.pk, 'parentId': ((categor...
A category structure.
a category structure .
Question: What does this function do? Code: def category_structure(category, site): return {'description': category.title, 'htmlUrl': ('%s://%s%s' % (PROTOCOL, site.domain, category.get_absolute_url())), 'rssUrl': ('%s://%s%s' % (PROTOCOL, site.domain, reverse('zinnia:category_feed', args=[category.tree_path]))), '...
null
null
null
What does this function do?
def plugin_unloaded(): bh_thread.kill() bh_regions.clear_all_regions()
null
null
null
Tear down plugin.
pcsd
def plugin unloaded bh thread kill bh regions clear all regions
3718
def plugin_unloaded(): bh_thread.kill() bh_regions.clear_all_regions()
Tear down plugin.
tear down plugin .
Question: What does this function do? Code: def plugin_unloaded(): bh_thread.kill() bh_regions.clear_all_regions()
null
null
null
What does this function do?
def getText(node, recursive=False): L = [u''] for n in node.childNodes: if (n.nodeType in (node.TEXT_NODE, node.CDATA_SECTION_NODE)): L.append(n.data) elif (not recursive): return None L.append(getText(n)) return u''.join(L)
null
null
null
Get all the text associated with this node. With recursive == True, all text from child nodes is retrieved.
pcsd
def get Text node recursive=False L = [u''] for n in node child Nodes if n node Type in node TEXT NODE node CDATA SECTION NODE L append n data elif not recursive return None L append get Text n return u'' join L
3719
def getText(node, recursive=False): L = [u''] for n in node.childNodes: if (n.nodeType in (node.TEXT_NODE, node.CDATA_SECTION_NODE)): L.append(n.data) elif (not recursive): return None L.append(getText(n)) return u''.join(L)
Get all the text associated with this node. With recursive == True, all text from child nodes is retrieved.
get all the text associated with this node .
Question: What does this function do? Code: def getText(node, recursive=False): L = [u''] for n in node.childNodes: if (n.nodeType in (node.TEXT_NODE, node.CDATA_SECTION_NODE)): L.append(n.data) elif (not recursive): return None L.append(getText(n)) return u''.join(L)
null
null
null
What does this function do?
def get(name): filename = find(name) if (filename is None): raise RuntimeError(('Could not find %s' % name)) with open(filename) as fid: return fid.read()
null
null
null
Retrieve code from the given filename.
pcsd
def get name filename = find name if filename is None raise Runtime Error 'Could not find %s' % name with open filename as fid return fid read
3728
def get(name): filename = find(name) if (filename is None): raise RuntimeError(('Could not find %s' % name)) with open(filename) as fid: return fid.read()
Retrieve code from the given filename.
retrieve code from the given filename .
Question: What does this function do? Code: def get(name): filename = find(name) if (filename is None): raise RuntimeError(('Could not find %s' % name)) with open(filename) as fid: return fid.read()
null
null
null
What does this function do?
def reset(git_path, module, dest): cmd = ('%s reset --hard HEAD' % (git_path,)) return module.run_command(cmd, check_rc=True, cwd=dest)
null
null
null
Resets the index and working tree to HEAD. Discards any changes to tracked files in working tree since that commit.
pcsd
def reset git path module dest cmd = '%s reset --hard HEAD' % git path return module run command cmd check rc=True cwd=dest
3736
def reset(git_path, module, dest): cmd = ('%s reset --hard HEAD' % (git_path,)) return module.run_command(cmd, check_rc=True, cwd=dest)
Resets the index and working tree to HEAD. Discards any changes to tracked files in working tree since that commit.
resets the index and working tree to head .
Question: What does this function do? Code: def reset(git_path, module, dest): cmd = ('%s reset --hard HEAD' % (git_path,)) return module.run_command(cmd, check_rc=True, cwd=dest)
null
null
null
What does this function do?
def dipole_potential(x, y): r_sq = ((x ** 2) + (y ** 2)) theta = np.arctan2(y, x) z = (np.cos(theta) / r_sq) return ((np.max(z) - z) / (np.max(z) - np.min(z)))
null
null
null
The electric dipole potential V
pcsd
def dipole potential x y r sq = x ** 2 + y ** 2 theta = np arctan2 y x z = np cos theta / r sq return np max z - z / np max z - np min z
3739
def dipole_potential(x, y): r_sq = ((x ** 2) + (y ** 2)) theta = np.arctan2(y, x) z = (np.cos(theta) / r_sq) return ((np.max(z) - z) / (np.max(z) - np.min(z)))
The electric dipole potential V
the electric dipole potential v
Question: What does this function do? Code: def dipole_potential(x, y): r_sq = ((x ** 2) + (y ** 2)) theta = np.arctan2(y, x) z = (np.cos(theta) / r_sq) return ((np.max(z) - z) / (np.max(z) - np.min(z)))
null
null
null
What does this function do?
@register.as_tag def blog_categories(*args): posts = BlogPost.objects.published() categories = BlogCategory.objects.filter(blogposts__in=posts) return list(categories.annotate(post_count=Count(u'blogposts')))
null
null
null
Put a list of categories for blog posts into the template context.
pcsd
@register as tag def blog categories *args posts = Blog Post objects published categories = Blog Category objects filter blogposts in=posts return list categories annotate post count=Count u'blogposts'
3747
@register.as_tag def blog_categories(*args): posts = BlogPost.objects.published() categories = BlogCategory.objects.filter(blogposts__in=posts) return list(categories.annotate(post_count=Count(u'blogposts')))
Put a list of categories for blog posts into the template context.
put a list of categories for blog posts into the template context .
Question: What does this function do? Code: @register.as_tag def blog_categories(*args): posts = BlogPost.objects.published() categories = BlogCategory.objects.filter(blogposts__in=posts) return list(categories.annotate(post_count=Count(u'blogposts')))
null
null
null
What does this function do?
def init(cnf): CONFIG['host'] = cnf.get('proxy', {}).get('host') if (not CONFIG['host']): raise MinionError(message="Cannot find 'host' parameter in the proxy configuration") CONFIG['user'] = cnf.get('proxy', {}).get('user') if (not CONFIG['user']): raise MinionError(message="Cannot find 'user' parameter in the...
null
null
null
Initialize the module.
pcsd
def init cnf CONFIG['host'] = cnf get 'proxy' {} get 'host' if not CONFIG['host'] raise Minion Error message="Cannot find 'host' parameter in the proxy configuration" CONFIG['user'] = cnf get 'proxy' {} get 'user' if not CONFIG['user'] raise Minion Error message="Cannot find 'user' parameter in the proxy configuration"...
3750
def init(cnf): CONFIG['host'] = cnf.get('proxy', {}).get('host') if (not CONFIG['host']): raise MinionError(message="Cannot find 'host' parameter in the proxy configuration") CONFIG['user'] = cnf.get('proxy', {}).get('user') if (not CONFIG['user']): raise MinionError(message="Cannot find 'user' parameter in the...
Initialize the module.
initialize the module .
Question: What does this function do? Code: def init(cnf): CONFIG['host'] = cnf.get('proxy', {}).get('host') if (not CONFIG['host']): raise MinionError(message="Cannot find 'host' parameter in the proxy configuration") CONFIG['user'] = cnf.get('proxy', {}).get('user') if (not CONFIG['user']): raise MinionErr...
null
null
null
What does this function do?
def as_one_hot(input_, n_indices): shape = input_.get_shape().as_list() n_elem = numpy.prod(shape) indices = tf.range(n_elem) indices = tf.cast(indices, tf.int64) indices_input = tf.concat(0, [indices, tf.reshape(input_, [(-1)])]) indices_input = tf.reshape(indices_input, [2, (-1)]) indices_input = tf.transpose(...
null
null
null
Convert indices to one-hot.
pcsd
def as one hot input n indices shape = input get shape as list n elem = numpy prod shape indices = tf range n elem indices = tf cast indices tf int64 indices input = tf concat 0 [indices tf reshape input [ -1 ] ] indices input = tf reshape indices input [2 -1 ] indices input = tf transpose indices input res = tf sparse...
3751
def as_one_hot(input_, n_indices): shape = input_.get_shape().as_list() n_elem = numpy.prod(shape) indices = tf.range(n_elem) indices = tf.cast(indices, tf.int64) indices_input = tf.concat(0, [indices, tf.reshape(input_, [(-1)])]) indices_input = tf.reshape(indices_input, [2, (-1)]) indices_input = tf.transpose(...
Convert indices to one-hot.
convert indices to one - hot .
Question: What does this function do? Code: def as_one_hot(input_, n_indices): shape = input_.get_shape().as_list() n_elem = numpy.prod(shape) indices = tf.range(n_elem) indices = tf.cast(indices, tf.int64) indices_input = tf.concat(0, [indices, tf.reshape(input_, [(-1)])]) indices_input = tf.reshape(indices_i...
null
null
null
What does this function do?
def __gen_rtag(): return os.path.join(__opts__['cachedir'], 'pkg_refresh')
null
null
null
Return the location of the refresh tag
pcsd
def gen rtag return os path join opts ['cachedir'] 'pkg refresh'
3758
def __gen_rtag(): return os.path.join(__opts__['cachedir'], 'pkg_refresh')
Return the location of the refresh tag
return the location of the refresh tag
Question: What does this function do? Code: def __gen_rtag(): return os.path.join(__opts__['cachedir'], 'pkg_refresh')
null
null
null
What does this function do?
def downcaseTokens(s, l, t): return map(str.lower, t)
null
null
null
Helper parse action to convert tokens to lower case.
pcsd
def downcase Tokens s l t return map str lower t
3769
def downcaseTokens(s, l, t): return map(str.lower, t)
Helper parse action to convert tokens to lower case.
helper parse action to convert tokens to lower case .
Question: What does this function do? Code: def downcaseTokens(s, l, t): return map(str.lower, t)
null
null
null
What does this function do?
def Deserializer(object_list, **options): db = options.pop('using', DEFAULT_DB_ALIAS) src_version = options.pop('src_version') dest_version = options.pop('dest_version') assert dest_version, 'For KA Lite, we should always set the dest version to the current device.' models.get_apps() for d in object_list: Model...
null
null
null
Deserialize simple Python objects back into Django ORM instances. It\'s expected that you pass the Python objects themselves (instead of a stream or a string) to the constructor
pcsd
def Deserializer object list **options db = options pop 'using' DEFAULT DB ALIAS src version = options pop 'src version' dest version = options pop 'dest version' assert dest version 'For KA Lite we should always set the dest version to the current device ' models get apps for d in object list Model = get model d['mode...
3774
def Deserializer(object_list, **options): db = options.pop('using', DEFAULT_DB_ALIAS) src_version = options.pop('src_version') dest_version = options.pop('dest_version') assert dest_version, 'For KA Lite, we should always set the dest version to the current device.' models.get_apps() for d in object_list: Model...
Deserialize simple Python objects back into Django ORM instances. It\'s expected that you pass the Python objects themselves (instead of a stream or a string) to the constructor
deserialize simple python objects back into django orm instances .
Question: What does this function do? Code: def Deserializer(object_list, **options): db = options.pop('using', DEFAULT_DB_ALIAS) src_version = options.pop('src_version') dest_version = options.pop('dest_version') assert dest_version, 'For KA Lite, we should always set the dest version to the current device.' m...
null
null
null
What does this function do?
def parse_upgrade(rule): parser = argparse.ArgumentParser() rules = shlex.split(rule) rules.pop(0) parser.add_argument('--root-device', dest='root-device', action='store') args = clean_args(vars(parser.parse_args(rules))) parser = None if args: return args return True
null
null
null
Parse the upgrade line
pcsd
def parse upgrade rule parser = argparse Argument Parser rules = shlex split rule rules pop 0 parser add argument '--root-device' dest='root-device' action='store' args = clean args vars parser parse args rules parser = None if args return args return True
3775
def parse_upgrade(rule): parser = argparse.ArgumentParser() rules = shlex.split(rule) rules.pop(0) parser.add_argument('--root-device', dest='root-device', action='store') args = clean_args(vars(parser.parse_args(rules))) parser = None if args: return args return True
Parse the upgrade line
parse the upgrade line
Question: What does this function do? Code: def parse_upgrade(rule): parser = argparse.ArgumentParser() rules = shlex.split(rule) rules.pop(0) parser.add_argument('--root-device', dest='root-device', action='store') args = clean_args(vars(parser.parse_args(rules))) parser = None if args: return args return...
null
null
null
What does this function do?
def is_windows(): return sys.platform.startswith(u'win')
null
null
null
True when we are using Windows.
pcsd
def is windows return sys platform startswith u'win'
3779
def is_windows(): return sys.platform.startswith(u'win')
True when we are using Windows.
true when we are using windows .
Question: What does this function do? Code: def is_windows(): return sys.platform.startswith(u'win')
null
null
null
What does this function do?
@handle_response_format @treeio_login_required @_process_mass_form def milestone_view(request, milestone_id, response_format='html'): milestone = get_object_or_404(Milestone, pk=milestone_id) project = milestone.project if (not request.user.profile.has_permission(milestone)): return user_denied(request, message="Y...
null
null
null
Single milestone view page
pcsd
@handle response format @treeio login required @ process mass form def milestone view request milestone id response format='html' milestone = get object or 404 Milestone pk=milestone id project = milestone project if not request user profile has permission milestone return user denied request message="You don't have ac...
3781
@handle_response_format @treeio_login_required @_process_mass_form def milestone_view(request, milestone_id, response_format='html'): milestone = get_object_or_404(Milestone, pk=milestone_id) project = milestone.project if (not request.user.profile.has_permission(milestone)): return user_denied(request, message="Y...
Single milestone view page
single milestone view page
Question: What does this function do? Code: @handle_response_format @treeio_login_required @_process_mass_form def milestone_view(request, milestone_id, response_format='html'): milestone = get_object_or_404(Milestone, pk=milestone_id) project = milestone.project if (not request.user.profile.has_permission(milest...
null
null
null
What does this function do?
def getNewRepository(): return LashRepository()
null
null
null
Get new repository.
pcsd
def get New Repository return Lash Repository
3782
def getNewRepository(): return LashRepository()
Get new repository.
get new repository .
Question: What does this function do? Code: def getNewRepository(): return LashRepository()
null
null
null
What does this function do?
def generate(node, environment, name, filename, stream=None): if (not isinstance(node, nodes.Template)): raise TypeError("Can't compile non template nodes") generator = CodeGenerator(environment, name, filename, stream) generator.visit(node) if (stream is None): return generator.stream.getvalue()
null
null
null
Generate the python source for a node tree.
pcsd
def generate node environment name filename stream=None if not isinstance node nodes Template raise Type Error "Can't compile non template nodes" generator = Code Generator environment name filename stream generator visit node if stream is None return generator stream getvalue
3786
def generate(node, environment, name, filename, stream=None): if (not isinstance(node, nodes.Template)): raise TypeError("Can't compile non template nodes") generator = CodeGenerator(environment, name, filename, stream) generator.visit(node) if (stream is None): return generator.stream.getvalue()
Generate the python source for a node tree.
generate the python source for a node tree .
Question: What does this function do? Code: def generate(node, environment, name, filename, stream=None): if (not isinstance(node, nodes.Template)): raise TypeError("Can't compile non template nodes") generator = CodeGenerator(environment, name, filename, stream) generator.visit(node) if (stream is None): re...
null
null
null
What does this function do?
def linked_data(prefix, ignore_channels=False): recs = linked_data_.get(prefix) if (recs is None): recs = linked_data_[prefix] = odict() meta_dir = join(prefix, u'conda-meta') if isdir(meta_dir): for fn in listdir(meta_dir): if fn.endswith(u'.json'): dist_name = fn[:(-5)] load_linked_data(prefi...
null
null
null
Return a dictionary of the linked packages in prefix.
pcsd
def linked data prefix ignore channels=False recs = linked data get prefix if recs is None recs = linked data [prefix] = odict meta dir = join prefix u'conda-meta' if isdir meta dir for fn in listdir meta dir if fn endswith u' json' dist name = fn[ -5 ] load linked data prefix dist name ignore channels=ignore channels ...
3796
def linked_data(prefix, ignore_channels=False): recs = linked_data_.get(prefix) if (recs is None): recs = linked_data_[prefix] = odict() meta_dir = join(prefix, u'conda-meta') if isdir(meta_dir): for fn in listdir(meta_dir): if fn.endswith(u'.json'): dist_name = fn[:(-5)] load_linked_data(prefi...
Return a dictionary of the linked packages in prefix.
return a dictionary of the linked packages in prefix .
Question: What does this function do? Code: def linked_data(prefix, ignore_channels=False): recs = linked_data_.get(prefix) if (recs is None): recs = linked_data_[prefix] = odict() meta_dir = join(prefix, u'conda-meta') if isdir(meta_dir): for fn in listdir(meta_dir): if fn.endswith(u'.json'): di...
null
null
null
What does this function do?
def cxSet(ind1, ind2): temp = set(ind1) ind1 &= ind2 ind2 ^= temp return (ind1, ind2)
null
null
null
Apply a crossover operation on input sets. The first child is the intersection of the two sets, the second child is the difference of the two sets.
pcsd
def cx Set ind1 ind2 temp = set ind1 ind1 &= ind2 ind2 ^= temp return ind1 ind2
3798
def cxSet(ind1, ind2): temp = set(ind1) ind1 &= ind2 ind2 ^= temp return (ind1, ind2)
Apply a crossover operation on input sets. The first child is the intersection of the two sets, the second child is the difference of the two sets.
apply a crossover operation on input sets .
Question: What does this function do? Code: def cxSet(ind1, ind2): temp = set(ind1) ind1 &= ind2 ind2 ^= temp return (ind1, ind2)
null
null
null
What does this function do?
def read_plain_byte_array(file_obj, count): return [file_obj.read(struct.unpack('<i', file_obj.read(4))[0]) for i in range(count)]
null
null
null
Read `count` byte arrays using the plain encoding.
pcsd
def read plain byte array file obj count return [file obj read struct unpack '<i' file obj read 4 [0] for i in range count ]
3800
def read_plain_byte_array(file_obj, count): return [file_obj.read(struct.unpack('<i', file_obj.read(4))[0]) for i in range(count)]
Read `count` byte arrays using the plain encoding.
read count byte arrays using the plain encoding .
Question: What does this function do? Code: def read_plain_byte_array(file_obj, count): return [file_obj.read(struct.unpack('<i', file_obj.read(4))[0]) for i in range(count)]
null
null
null
What does this function do?
def knownPlaintext(known_key, random_plaintext): stallion = AES.new(known_key) encrypted_string = EncodeAES(stallion, random_plaintext) return encrypted_string
null
null
null
Uses key passed in to encrypt a random string which is used in a known plaintext attack to brute force its own key
pcsd
def known Plaintext known key random plaintext stallion = AES new known key encrypted string = Encode AES stallion random plaintext return encrypted string
3801
def knownPlaintext(known_key, random_plaintext): stallion = AES.new(known_key) encrypted_string = EncodeAES(stallion, random_plaintext) return encrypted_string
Uses key passed in to encrypt a random string which is used in a known plaintext attack to brute force its own key
uses key passed in to encrypt a random string which is used in a known plaintext attack to brute force its own key
Question: What does this function do? Code: def knownPlaintext(known_key, random_plaintext): stallion = AES.new(known_key) encrypted_string = EncodeAES(stallion, random_plaintext) return encrypted_string
null
null
null
What does this function do?
def truncatewords_html(value, arg): from google.appengine._internal.django.utils.text import truncate_html_words try: length = int(arg) except ValueError: return value return truncate_html_words(value, length)
null
null
null
Truncates HTML after a certain number of words. Argument: Number of words to truncate after. Newlines in the HTML are preserved.
pcsd
def truncatewords html value arg from google appengine internal django utils text import truncate html words try length = int arg except Value Error return value return truncate html words value length
3814
def truncatewords_html(value, arg): from google.appengine._internal.django.utils.text import truncate_html_words try: length = int(arg) except ValueError: return value return truncate_html_words(value, length)
Truncates HTML after a certain number of words. Argument: Number of words to truncate after. Newlines in the HTML are preserved.
truncates html after a certain number of words .
Question: What does this function do? Code: def truncatewords_html(value, arg): from google.appengine._internal.django.utils.text import truncate_html_words try: length = int(arg) except ValueError: return value return truncate_html_words(value, length)
null
null
null
What does this function do?
def functest_builder(method, func): def do_test(self): method(self, func) return do_test
null
null
null
Generate a test method that tests the given function.
pcsd
def functest builder method func def do test self method self func return do test
3826
def functest_builder(method, func): def do_test(self): method(self, func) return do_test
Generate a test method that tests the given function.
generate a test method that tests the given function .
Question: What does this function do? Code: def functest_builder(method, func): def do_test(self): method(self, func) return do_test
null
null
null
What does this function do?
def rotate_l(L, k): ll = list(L) if (ll == []): return [] for i in range(k): el = ll.pop(0) ll.insert((len(ll) - 1), el) return (ll if (type(L) is list) else Matrix([ll]))
null
null
null
Rotates left by k. L is a row of a matrix or a list.
pcsd
def rotate l L k ll = list L if ll == [] return [] for i in range k el = ll pop 0 ll insert len ll - 1 el return ll if type L is list else Matrix [ll]
3836
def rotate_l(L, k): ll = list(L) if (ll == []): return [] for i in range(k): el = ll.pop(0) ll.insert((len(ll) - 1), el) return (ll if (type(L) is list) else Matrix([ll]))
Rotates left by k. L is a row of a matrix or a list.
rotates left by k .
Question: What does this function do? Code: def rotate_l(L, k): ll = list(L) if (ll == []): return [] for i in range(k): el = ll.pop(0) ll.insert((len(ll) - 1), el) return (ll if (type(L) is list) else Matrix([ll]))
null
null
null
What does this function do?
@pytest.mark.parametrize(units_attr_args, [x for x in units_attr_sets if (x[0] != u'unitspherical')]) def test_galactic_three_components(repr_name, unit1, unit2, unit3, cls2, attr1, attr2, attr3, representation, c1, c2, c3): sc = Galactic(((1000 * c1) * u.Unit((unit1 / 1000))), cls2(c2, unit=unit2), ((1000 * c3) * u.U...
null
null
null
Tests positional inputs using components (COMP1, COMP2, COMP3) and various representations. Use weird units and Galactic frame.
pcsd
@pytest mark parametrize units attr args [x for x in units attr sets if x[0] != u'unitspherical' ] def test galactic three components repr name unit1 unit2 unit3 cls2 attr1 attr2 attr3 representation c1 c2 c3 sc = Galactic 1000 * c1 * u Unit unit1 / 1000 cls2 c2 unit=unit2 1000 * c3 * u Unit unit3 / 1000 representation...
3837
@pytest.mark.parametrize(units_attr_args, [x for x in units_attr_sets if (x[0] != u'unitspherical')]) def test_galactic_three_components(repr_name, unit1, unit2, unit3, cls2, attr1, attr2, attr3, representation, c1, c2, c3): sc = Galactic(((1000 * c1) * u.Unit((unit1 / 1000))), cls2(c2, unit=unit2), ((1000 * c3) * u.U...
Tests positional inputs using components (COMP1, COMP2, COMP3) and various representations. Use weird units and Galactic frame.
tests positional inputs using components and various representations .
Question: What does this function do? Code: @pytest.mark.parametrize(units_attr_args, [x for x in units_attr_sets if (x[0] != u'unitspherical')]) def test_galactic_three_components(repr_name, unit1, unit2, unit3, cls2, attr1, attr2, attr3, representation, c1, c2, c3): sc = Galactic(((1000 * c1) * u.Unit((unit1 / 10...
null
null
null
What does this function do?
def user_can_edit_setting_type(user, model): return user.has_perm(u'{}.change_{}'.format(model._meta.app_label, model._meta.model_name))
null
null
null
Check if a user has permission to edit this setting type
pcsd
def user can edit setting type user model return user has perm u'{} change {}' format model meta app label model meta model name
3844
def user_can_edit_setting_type(user, model): return user.has_perm(u'{}.change_{}'.format(model._meta.app_label, model._meta.model_name))
Check if a user has permission to edit this setting type
check if a user has permission to edit this setting type
Question: What does this function do? Code: def user_can_edit_setting_type(user, model): return user.has_perm(u'{}.change_{}'.format(model._meta.app_label, model._meta.model_name))
null
null
null
What does this function do?
def bzr_wc_target_exists_local_mods_force(): test = 'bzr_wc_target_exists_local_mods_force' wt = ('%s-test-%s' % (DIR, test)) puts(magenta(('Executing test: %s' % test))) from fabric.api import cd, run from fabtools.files import is_dir from fabtools import require require.bazaar.working_copy(REMOTE_URL, wt) ass...
null
null
null
Test working copy when a target already exists and has local modifications and force was specified.
pcsd
def bzr wc target exists local mods force test = 'bzr wc target exists local mods force' wt = '%s-test-%s' % DIR test puts magenta 'Executing test %s' % test from fabric api import cd run from fabtools files import is dir from fabtools import require require bazaar working copy REMOTE URL wt assert is dir wt with cd wt...
3858
def bzr_wc_target_exists_local_mods_force(): test = 'bzr_wc_target_exists_local_mods_force' wt = ('%s-test-%s' % (DIR, test)) puts(magenta(('Executing test: %s' % test))) from fabric.api import cd, run from fabtools.files import is_dir from fabtools import require require.bazaar.working_copy(REMOTE_URL, wt) ass...
Test working copy when a target already exists and has local modifications and force was specified.
test working copy when a target already exists and has local modifications and force was specified .
Question: What does this function do? Code: def bzr_wc_target_exists_local_mods_force(): test = 'bzr_wc_target_exists_local_mods_force' wt = ('%s-test-%s' % (DIR, test)) puts(magenta(('Executing test: %s' % test))) from fabric.api import cd, run from fabtools.files import is_dir from fabtools import require r...
null
null
null
What does this function do?
def holdAcknowledge(): a = TpPd(pd=3) b = MessageType(mesType=25) packet = (a / b) return packet
null
null
null
HOLD ACKNOWLEDGE Section 9.3.11
pcsd
def hold Acknowledge a = Tp Pd pd=3 b = Message Type mes Type=25 packet = a / b return packet
3859
def holdAcknowledge(): a = TpPd(pd=3) b = MessageType(mesType=25) packet = (a / b) return packet
HOLD ACKNOWLEDGE Section 9.3.11
hold acknowledge section 9 . 3 . 11
Question: What does this function do? Code: def holdAcknowledge(): a = TpPd(pd=3) b = MessageType(mesType=25) packet = (a / b) return packet
null
null
null
What does this function do?
def OpenDocumentChart(): doc = OpenDocument('application/vnd.oasis.opendocument.chart') doc.chart = Chart() doc.body.addElement(doc.chart) return doc
null
null
null
Creates a chart document
pcsd
def Open Document Chart doc = Open Document 'application/vnd oasis opendocument chart' doc chart = Chart doc body add Element doc chart return doc
3867
def OpenDocumentChart(): doc = OpenDocument('application/vnd.oasis.opendocument.chart') doc.chart = Chart() doc.body.addElement(doc.chart) return doc
Creates a chart document
creates a chart document
Question: What does this function do? Code: def OpenDocumentChart(): doc = OpenDocument('application/vnd.oasis.opendocument.chart') doc.chart = Chart() doc.body.addElement(doc.chart) return doc
null
null
null
What does this function do?
def get_themes(root): static_path = os.path.join(root, 'static') templates_path = os.path.join(root, 'templates') themes = os.listdir(os.path.join(static_path, 'themes')) if ('__common__' in themes): themes.remove('__common__') return (static_path, templates_path, themes)
null
null
null
Returns available themes list.
pcsd
def get themes root static path = os path join root 'static' templates path = os path join root 'templates' themes = os listdir os path join static path 'themes' if ' common ' in themes themes remove ' common ' return static path templates path themes
3868
def get_themes(root): static_path = os.path.join(root, 'static') templates_path = os.path.join(root, 'templates') themes = os.listdir(os.path.join(static_path, 'themes')) if ('__common__' in themes): themes.remove('__common__') return (static_path, templates_path, themes)
Returns available themes list.
returns available themes list .
Question: What does this function do? Code: def get_themes(root): static_path = os.path.join(root, 'static') templates_path = os.path.join(root, 'templates') themes = os.listdir(os.path.join(static_path, 'themes')) if ('__common__' in themes): themes.remove('__common__') return (static_path, templates_path, t...
null
null
null
What does this function do?
def string_concat(*strings): return ''.join([str(el) for el in strings])
null
null
null
lazy variant of string concatenation, needed for translations that are constructed from multiple parts. Handles lazy strings and non-strings by first turning all arguments to strings, before joining them.
pcsd
def string concat *strings return '' join [str el for el in strings]
3874
def string_concat(*strings): return ''.join([str(el) for el in strings])
lazy variant of string concatenation, needed for translations that are constructed from multiple parts. Handles lazy strings and non-strings by first turning all arguments to strings, before joining them.
lazy variant of string concatenation , needed for translations that are constructed from multiple parts .
Question: What does this function do? Code: def string_concat(*strings): return ''.join([str(el) for el in strings])
null
null
null
What does this function do?
def api_call(target_version, target_api_url, session, debug=False, authenticate=True): resource_url = (('/api/' + target_version) + target_api_url) try: if (authenticate and session.REQUEST_TOKEN and session.ACCESS_TOKEN): client = TestOAuthClient(session.SERVER_URL, CONSUMER_KEY, CONSUMER_SECRET) response = ...
null
null
null
Generic API call function, that will try to use an authenticated request if available, otherwise will fall back to non-authenticated request.
pcsd
def api call target version target api url session debug=False authenticate=True resource url = '/api/' + target version + target api url try if authenticate and session REQUEST TOKEN and session ACCESS TOKEN client = Test O Auth Client session SERVER URL CONSUMER KEY CONSUMER SECRET response = client access resource r...
3878
def api_call(target_version, target_api_url, session, debug=False, authenticate=True): resource_url = (('/api/' + target_version) + target_api_url) try: if (authenticate and session.REQUEST_TOKEN and session.ACCESS_TOKEN): client = TestOAuthClient(session.SERVER_URL, CONSUMER_KEY, CONSUMER_SECRET) response = ...
Generic API call function, that will try to use an authenticated request if available, otherwise will fall back to non-authenticated request.
generic api call function , that will try to use an authenticated request if available , otherwise will fall back to non - authenticated request .
Question: What does this function do? Code: def api_call(target_version, target_api_url, session, debug=False, authenticate=True): resource_url = (('/api/' + target_version) + target_api_url) try: if (authenticate and session.REQUEST_TOKEN and session.ACCESS_TOKEN): client = TestOAuthClient(session.SERVER_URL...
null
null
null
What does this function do?
def system(commandline): logging.info(commandline) return os.system(commandline)
null
null
null
Same as os.system(commandline) but logs the command first.
pcsd
def system commandline logging info commandline return os system commandline
3879
def system(commandline): logging.info(commandline) return os.system(commandline)
Same as os.system(commandline) but logs the command first.
same as os . system but logs the command first .
Question: What does this function do? Code: def system(commandline): logging.info(commandline) return os.system(commandline)
null
null
null
What does this function do?
def _parse_tokens(tokens): index = 0 parsed_tokens = [] num_tokens = len(tokens) while (index < num_tokens): tok = Token(*tokens[index]) assert (tok.token_type != token.INDENT) if (tok.token_type == tokenize.NEWLINE): break if (tok.token_string in u'([{'): (container, index) = _parse_container(tokens,...
null
null
null
Parse the tokens. This converts the tokens into a form where we can manipulate them more easily.
pcsd
def parse tokens tokens index = 0 parsed tokens = [] num tokens = len tokens while index < num tokens tok = Token *tokens[index] assert tok token type != token INDENT if tok token type == tokenize NEWLINE break if tok token string in u' [{' container index = parse container tokens index if not container return None par...
3882
def _parse_tokens(tokens): index = 0 parsed_tokens = [] num_tokens = len(tokens) while (index < num_tokens): tok = Token(*tokens[index]) assert (tok.token_type != token.INDENT) if (tok.token_type == tokenize.NEWLINE): break if (tok.token_string in u'([{'): (container, index) = _parse_container(tokens,...
Parse the tokens. This converts the tokens into a form where we can manipulate them more easily.
parse the tokens .
Question: What does this function do? Code: def _parse_tokens(tokens): index = 0 parsed_tokens = [] num_tokens = len(tokens) while (index < num_tokens): tok = Token(*tokens[index]) assert (tok.token_type != token.INDENT) if (tok.token_type == tokenize.NEWLINE): break if (tok.token_string in u'([{'): ...
null
null
null
What does this function do?
def get_view(request): t = Template('This is a test. {{ var }} is the value.', name='GET Template') c = Context({'var': request.GET.get('var', 42)}) return HttpResponse(t.render(c))
null
null
null
A simple view that expects a GET request, and returns a rendered template
pcsd
def get view request t = Template 'This is a test {{ var }} is the value ' name='GET Template' c = Context {'var' request GET get 'var' 42 } return Http Response t render c
3887
def get_view(request): t = Template('This is a test. {{ var }} is the value.', name='GET Template') c = Context({'var': request.GET.get('var', 42)}) return HttpResponse(t.render(c))
A simple view that expects a GET request, and returns a rendered template
a simple view that expects a get request , and returns a rendered template
Question: What does this function do? Code: def get_view(request): t = Template('This is a test. {{ var }} is the value.', name='GET Template') c = Context({'var': request.GET.get('var', 42)}) return HttpResponse(t.render(c))
null
null
null
What does this function do?
def episode_by_id(episode_id, session=None): return session.query(Episode).filter((Episode.id == episode_id)).one()
null
null
null
Return an instance of an episode by querying its ID
pcsd
def episode by id episode id session=None return session query Episode filter Episode id == episode id one
3901
def episode_by_id(episode_id, session=None): return session.query(Episode).filter((Episode.id == episode_id)).one()
Return an instance of an episode by querying its ID
return an instance of an episode by querying its id
Question: What does this function do? Code: def episode_by_id(episode_id, session=None): return session.query(Episode).filter((Episode.id == episode_id)).one()
null
null
null
What does this function do?
def _move_to_next(fid, byte=8): now = fid.tell() if ((now % byte) != 0): now = ((now - (now % byte)) + byte) fid.seek(now, 0)
null
null
null
Move to next byte boundary.
pcsd
def move to next fid byte=8 now = fid tell if now % byte != 0 now = now - now % byte + byte fid seek now 0
3905
def _move_to_next(fid, byte=8): now = fid.tell() if ((now % byte) != 0): now = ((now - (now % byte)) + byte) fid.seek(now, 0)
Move to next byte boundary.
move to next byte boundary .
Question: What does this function do? Code: def _move_to_next(fid, byte=8): now = fid.tell() if ((now % byte) != 0): now = ((now - (now % byte)) + byte) fid.seek(now, 0)
null
null
null
What does this function do?
def _align(terms): try: terms = list(com.flatten(terms)) except TypeError: if isinstance(terms.value, pd.core.generic.NDFrame): typ = type(terms.value) return (typ, _zip_axes_from_type(typ, terms.value.axes)) return (np.result_type(terms.type), None) if all((term.isscalar for term in terms)): return (_...
null
null
null
Align a set of terms
pcsd
def align terms try terms = list com flatten terms except Type Error if isinstance terms value pd core generic ND Frame typ = type terms value return typ zip axes from type typ terms value axes return np result type terms type None if all term isscalar for term in terms return result type many * term value for term in ...
3906
def _align(terms): try: terms = list(com.flatten(terms)) except TypeError: if isinstance(terms.value, pd.core.generic.NDFrame): typ = type(terms.value) return (typ, _zip_axes_from_type(typ, terms.value.axes)) return (np.result_type(terms.type), None) if all((term.isscalar for term in terms)): return (_...
Align a set of terms
align a set of terms
Question: What does this function do? Code: def _align(terms): try: terms = list(com.flatten(terms)) except TypeError: if isinstance(terms.value, pd.core.generic.NDFrame): typ = type(terms.value) return (typ, _zip_axes_from_type(typ, terms.value.axes)) return (np.result_type(terms.type), None) if all(...
null
null
null
What does this function do?
def a_product(x, y, z=1): return ((x * y) * z)
null
null
null
Simple function that returns the product of three numbers
pcsd
def a product x y z=1 return x * y * z
3908
def a_product(x, y, z=1): return ((x * y) * z)
Simple function that returns the product of three numbers
simple function that returns the product of three numbers
Question: What does this function do? Code: def a_product(x, y, z=1): return ((x * y) * z)
null
null
null
What does this function do?
def remove_logical_volumes(*paths): for path in paths: clear_logical_volume(path) if paths: lvremove = (('lvremove', '-f') + paths) execute(attempts=3, run_as_root=True, *lvremove)
null
null
null
Remove one or more logical volume.
pcsd
def remove logical volumes *paths for path in paths clear logical volume path if paths lvremove = 'lvremove' '-f' + paths execute attempts=3 run as root=True *lvremove
3909
def remove_logical_volumes(*paths): for path in paths: clear_logical_volume(path) if paths: lvremove = (('lvremove', '-f') + paths) execute(attempts=3, run_as_root=True, *lvremove)
Remove one or more logical volume.
remove one or more logical volume .
Question: What does this function do? Code: def remove_logical_volumes(*paths): for path in paths: clear_logical_volume(path) if paths: lvremove = (('lvremove', '-f') + paths) execute(attempts=3, run_as_root=True, *lvremove)
null
null
null
What does this function do?
def i16le(c, o=0): return unpack('<H', c[o:(o + 2)])[0]
null
null
null
Converts a 2-bytes (16 bits) string to an unsigned integer. c: string containing bytes to convert o: offset of bytes to convert in string
pcsd
def i16le c o=0 return unpack '<H' c[o o + 2 ] [0]
3910
def i16le(c, o=0): return unpack('<H', c[o:(o + 2)])[0]
Converts a 2-bytes (16 bits) string to an unsigned integer. c: string containing bytes to convert o: offset of bytes to convert in string
converts a 2 - bytes string to an unsigned integer .
Question: What does this function do? Code: def i16le(c, o=0): return unpack('<H', c[o:(o + 2)])[0]
null
null
null
What does this function do?
def eventlog(request, event=0): if (not test_user_authenticated(request)): return login(request, next=('/cobbler_web/eventlog/%s' % str(event)), expired=True) event_info = remote.get_events() if (event not in event_info): return HttpResponse('event not found') data = event_info[event] eventname = data[0] even...
null
null
null
Shows the log for a given event.
pcsd
def eventlog request event=0 if not test user authenticated request return login request next= '/cobbler web/eventlog/%s' % str event expired=True event info = remote get events if event not in event info return Http Response 'event not found' data = event info[event] eventname = data[0] eventtime = data[1] eventstate ...
3920
def eventlog(request, event=0): if (not test_user_authenticated(request)): return login(request, next=('/cobbler_web/eventlog/%s' % str(event)), expired=True) event_info = remote.get_events() if (event not in event_info): return HttpResponse('event not found') data = event_info[event] eventname = data[0] even...
Shows the log for a given event.
shows the log for a given event .
Question: What does this function do? Code: def eventlog(request, event=0): if (not test_user_authenticated(request)): return login(request, next=('/cobbler_web/eventlog/%s' % str(event)), expired=True) event_info = remote.get_events() if (event not in event_info): return HttpResponse('event not found') data...
null
null
null
What does this function do?
def int_to_bin(i): i1 = (i % 256) i2 = int((i / 256)) return (chr(i1) + chr(i2))
null
null
null
Integer to two bytes
pcsd
def int to bin i i1 = i % 256 i2 = int i / 256 return chr i1 + chr i2
3928
def int_to_bin(i): i1 = (i % 256) i2 = int((i / 256)) return (chr(i1) + chr(i2))
Integer to two bytes
integer to two bytes
Question: What does this function do? Code: def int_to_bin(i): i1 = (i % 256) i2 = int((i / 256)) return (chr(i1) + chr(i2))
null
null
null
What does this function do?
@pytest.mark.parametrize('parallel', [True, False]) def test_quoted_empty_values(parallel, read_basic): if parallel: pytest.xfail('Multiprocessing can fail with quoted fields') text = 'a b c\n1 2 " \n "' table = read_basic(text, parallel=parallel) assert (table['c'][0] is ma.masked)
null
null
null
Quoted empty values spanning multiple lines should be treated correctly.
pcsd
@pytest mark parametrize 'parallel' [True False] def test quoted empty values parallel read basic if parallel pytest xfail 'Multiprocessing can fail with quoted fields' text = 'a b c 1 2 " "' table = read basic text parallel=parallel assert table['c'][0] is ma masked
3931
@pytest.mark.parametrize('parallel', [True, False]) def test_quoted_empty_values(parallel, read_basic): if parallel: pytest.xfail('Multiprocessing can fail with quoted fields') text = 'a b c\n1 2 " \n "' table = read_basic(text, parallel=parallel) assert (table['c'][0] is ma.masked)
Quoted empty values spanning multiple lines should be treated correctly.
quoted empty values spanning multiple lines should be treated correctly .
Question: What does this function do? Code: @pytest.mark.parametrize('parallel', [True, False]) def test_quoted_empty_values(parallel, read_basic): if parallel: pytest.xfail('Multiprocessing can fail with quoted fields') text = 'a b c\n1 2 " \n "' table = read_basic(text, parallel=parallel) assert (table['c'][...
null
null
null
What does this function do?
def parse_count(source): return source.get_while(DIGITS)
null
null
null
Parses a quantifier\'s count, which can be empty.
pcsd
def parse count source return source get while DIGITS
3935
def parse_count(source): return source.get_while(DIGITS)
Parses a quantifier\'s count, which can be empty.
parses a quantifiers count , which can be empty .
Question: What does this function do? Code: def parse_count(source): return source.get_while(DIGITS)
null
null
null
What does this function do?
def _get_filename(filename): if os.path.isabs(filename): basedir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) common_path = os.path.commonprefix([basedir, filename]) if common_path: filename = filename[len(common_path):].lstrip('/') return filename
null
null
null
Transform the absolute test filenames to relative ones.
pcsd
def get filename filename if os path isabs filename basedir = os path abspath os path join os path dirname file ' ' ' ' common path = os path commonprefix [basedir filename] if common path filename = filename[len common path ] lstrip '/' return filename
3939
def _get_filename(filename): if os.path.isabs(filename): basedir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) common_path = os.path.commonprefix([basedir, filename]) if common_path: filename = filename[len(common_path):].lstrip('/') return filename
Transform the absolute test filenames to relative ones.
transform the absolute test filenames to relative ones .
Question: What does this function do? Code: def _get_filename(filename): if os.path.isabs(filename): basedir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) common_path = os.path.commonprefix([basedir, filename]) if common_path: filename = filename[len(common_path):].lstrip('/') ret...
null
null
null
What does this function do?
def details(request, slug): response_timestamp = now() if (get_cms_setting('PAGE_CACHE') and ((not hasattr(request, 'toolbar')) or ((not request.toolbar.edit_mode) and (not request.toolbar.show_toolbar) and (not request.user.is_authenticated())))): cache_content = get_page_cache(request) if (cache_content is not ...
null
null
null
The main view of the Django-CMS! Takes a request and a slug, renders the page.
pcsd
def details request slug response timestamp = now if get cms setting 'PAGE CACHE' and not hasattr request 'toolbar' or not request toolbar edit mode and not request toolbar show toolbar and not request user is authenticated cache content = get page cache request if cache content is not None content headers expires date...
3957
def details(request, slug): response_timestamp = now() if (get_cms_setting('PAGE_CACHE') and ((not hasattr(request, 'toolbar')) or ((not request.toolbar.edit_mode) and (not request.toolbar.show_toolbar) and (not request.user.is_authenticated())))): cache_content = get_page_cache(request) if (cache_content is not ...
The main view of the Django-CMS! Takes a request and a slug, renders the page.
the main view of the django - cms ! takes a request and a slug , renders the page .
Question: What does this function do? Code: def details(request, slug): response_timestamp = now() if (get_cms_setting('PAGE_CACHE') and ((not hasattr(request, 'toolbar')) or ((not request.toolbar.edit_mode) and (not request.toolbar.show_toolbar) and (not request.user.is_authenticated())))): cache_content = get_...
null
null
null
What does this function do?
@lower_constant(types.UniTuple) @lower_constant(types.NamedUniTuple) def unituple_constant(context, builder, ty, pyval): consts = [context.get_constant_generic(builder, ty.dtype, v) for v in pyval] return ir.ArrayType(consts[0].type, len(consts))(consts)
null
null
null
Create a homogenous tuple constant.
pcsd
@lower constant types Uni Tuple @lower constant types Named Uni Tuple def unituple constant context builder ty pyval consts = [context get constant generic builder ty dtype v for v in pyval] return ir Array Type consts[0] type len consts consts
3960
@lower_constant(types.UniTuple) @lower_constant(types.NamedUniTuple) def unituple_constant(context, builder, ty, pyval): consts = [context.get_constant_generic(builder, ty.dtype, v) for v in pyval] return ir.ArrayType(consts[0].type, len(consts))(consts)
Create a homogenous tuple constant.
create a homogenous tuple constant .
Question: What does this function do? Code: @lower_constant(types.UniTuple) @lower_constant(types.NamedUniTuple) def unituple_constant(context, builder, ty, pyval): consts = [context.get_constant_generic(builder, ty.dtype, v) for v in pyval] return ir.ArrayType(consts[0].type, len(consts))(consts)
null
null
null
What does this function do?
def get_cache_dir(subdir=None): cache_dir = os.environ.get('NEON_CACHE_DIR') if (cache_dir is None): cache_dir = appdirs.user_cache_dir('neon', 'neon') if subdir: subdir = (subdir if isinstance(subdir, list) else [subdir]) cache_dir = os.path.join(cache_dir, *subdir) if (not os.path.exists(cache_dir)): os.m...
null
null
null
Function for getting cache directory to store reused files like kernels, or scratch space for autotuning, etc.
pcsd
def get cache dir subdir=None cache dir = os environ get 'NEON CACHE DIR' if cache dir is None cache dir = appdirs user cache dir 'neon' 'neon' if subdir subdir = subdir if isinstance subdir list else [subdir] cache dir = os path join cache dir *subdir if not os path exists cache dir os makedirs cache dir return cache ...
3967
def get_cache_dir(subdir=None): cache_dir = os.environ.get('NEON_CACHE_DIR') if (cache_dir is None): cache_dir = appdirs.user_cache_dir('neon', 'neon') if subdir: subdir = (subdir if isinstance(subdir, list) else [subdir]) cache_dir = os.path.join(cache_dir, *subdir) if (not os.path.exists(cache_dir)): os.m...
Function for getting cache directory to store reused files like kernels, or scratch space for autotuning, etc.
function for getting cache directory to store reused files like kernels , or scratch space for autotuning , etc .
Question: What does this function do? Code: def get_cache_dir(subdir=None): cache_dir = os.environ.get('NEON_CACHE_DIR') if (cache_dir is None): cache_dir = appdirs.user_cache_dir('neon', 'neon') if subdir: subdir = (subdir if isinstance(subdir, list) else [subdir]) cache_dir = os.path.join(cache_dir, *subd...
null
null
null
What does this function do?
def responder(url, function): zsock = zcontext.socket(zmq.REP) zsock.bind(url) while True: word = zsock.recv() zsock.send(function(word))
null
null
null
Performs a string operation on each word received.
pcsd
def responder url function zsock = zcontext socket zmq REP zsock bind url while True word = zsock recv zsock send function word
3968
def responder(url, function): zsock = zcontext.socket(zmq.REP) zsock.bind(url) while True: word = zsock.recv() zsock.send(function(word))
Performs a string operation on each word received.
performs a string operation on each word received .
Question: What does this function do? Code: def responder(url, function): zsock = zcontext.socket(zmq.REP) zsock.bind(url) while True: word = zsock.recv() zsock.send(function(word))
null
null
null
What does this function do?
def p_field_type(p): p[0] = p[1]
null
null
null
field_type : ref_type | definition_type
pcsd
def p field type p p[0] = p[1]
3970
def p_field_type(p): p[0] = p[1]
field_type : ref_type | definition_type
field _ type : ref _ type | definition _ type
Question: What does this function do? Code: def p_field_type(p): p[0] = p[1]
null
null
null
What does this function do?
@require_GET @doc_page_cache @mobile_template('wiki/{mobile/}') def document(request, document_slug, template=None, document=None): fallback_reason = None full_locale_name = None try: doc = Document.objects.get(locale=request.LANGUAGE_CODE, slug=document_slug) if ((not doc.current_revision) and doc.parent and do...
null
null
null
View a wiki document.
pcsd
@require GET @doc page cache @mobile template 'wiki/{mobile/}' def document request document slug template=None document=None fallback reason = None full locale name = None try doc = Document objects get locale=request LANGUAGE CODE slug=document slug if not doc current revision and doc parent and doc parent current re...
3971
@require_GET @doc_page_cache @mobile_template('wiki/{mobile/}') def document(request, document_slug, template=None, document=None): fallback_reason = None full_locale_name = None try: doc = Document.objects.get(locale=request.LANGUAGE_CODE, slug=document_slug) if ((not doc.current_revision) and doc.parent and do...
View a wiki document.
view a wiki document .
Question: What does this function do? Code: @require_GET @doc_page_cache @mobile_template('wiki/{mobile/}') def document(request, document_slug, template=None, document=None): fallback_reason = None full_locale_name = None try: doc = Document.objects.get(locale=request.LANGUAGE_CODE, slug=document_slug) if ((...
null
null
null
What does this function do?
@receiver(project_import) def handle_project_import(sender, **kwargs): project = sender request = kwargs.get('request') attach_webhook(project=project, request=request)
null
null
null
Add post-commit hook on project import
pcsd
@receiver project import def handle project import sender **kwargs project = sender request = kwargs get 'request' attach webhook project=project request=request
3984
@receiver(project_import) def handle_project_import(sender, **kwargs): project = sender request = kwargs.get('request') attach_webhook(project=project, request=request)
Add post-commit hook on project import
add post - commit hook on project import
Question: What does this function do? Code: @receiver(project_import) def handle_project_import(sender, **kwargs): project = sender request = kwargs.get('request') attach_webhook(project=project, request=request)
null
null
null
What does this function do?
def add(module): check = parse_check(module) service = parse_service(module) if ((not service) and (not check)): module.fail_json(msg='a name and port are required to register a service') if service: if check: service.add_check(check) add_service(module, service) elif check: add_check(module, check)
null
null
null
adds a service or a check depending on supplied configuration
pcsd
def add module check = parse check module service = parse service module if not service and not check module fail json msg='a name and port are required to register a service' if service if check service add check check add service module service elif check add check module check
3991
def add(module): check = parse_check(module) service = parse_service(module) if ((not service) and (not check)): module.fail_json(msg='a name and port are required to register a service') if service: if check: service.add_check(check) add_service(module, service) elif check: add_check(module, check)
adds a service or a check depending on supplied configuration
adds a service or a check depending on supplied configuration
Question: What does this function do? Code: def add(module): check = parse_check(module) service = parse_service(module) if ((not service) and (not check)): module.fail_json(msg='a name and port are required to register a service') if service: if check: service.add_check(check) add_service(module, servi...
null
null
null
What does this function do?
def getNewDerivation(elementNode): return GridDerivation(elementNode)
null
null
null
Get new derivation.
pcsd
def get New Derivation element Node return Grid Derivation element Node
4000
def getNewDerivation(elementNode): return GridDerivation(elementNode)
Get new derivation.
get new derivation .
Question: What does this function do? Code: def getNewDerivation(elementNode): return GridDerivation(elementNode)
null
null
null
What does this function do?
def inv_recv_rheader(r): if ((r.representation == 'html') and (r.name == 'recv')): record = r.record if record: T = current.T s3db = current.s3db tabs = [(T('Edit Details'), None), (T('Items'), 'track_item')] rheader_tabs = s3_rheader_tabs(r, tabs) table = r.table tracktable = s3db.inv_track_item...
null
null
null
Resource Header for Receiving
pcsd
def inv recv rheader r if r representation == 'html' and r name == 'recv' record = r record if record T = current T s3db = current s3db tabs = [ T 'Edit Details' None T 'Items' 'track item' ] rheader tabs = s3 rheader tabs r tabs table = r table tracktable = s3db inv track item recv id = record id site id = record site...
4005
def inv_recv_rheader(r): if ((r.representation == 'html') and (r.name == 'recv')): record = r.record if record: T = current.T s3db = current.s3db tabs = [(T('Edit Details'), None), (T('Items'), 'track_item')] rheader_tabs = s3_rheader_tabs(r, tabs) table = r.table tracktable = s3db.inv_track_item...
Resource Header for Receiving
resource header for receiving
Question: What does this function do? Code: def inv_recv_rheader(r): if ((r.representation == 'html') and (r.name == 'recv')): record = r.record if record: T = current.T s3db = current.s3db tabs = [(T('Edit Details'), None), (T('Items'), 'track_item')] rheader_tabs = s3_rheader_tabs(r, tabs) tabl...
null
null
null
What does this function do?
def _topo_to_sphere(theta, radius): sph_phi = ((0.5 - radius) * 180) sph_theta = (- theta) return (sph_phi, sph_theta)
null
null
null
Convert using old function.
pcsd
def topo to sphere theta radius sph phi = 0 5 - radius * 180 sph theta = - theta return sph phi sph theta
4017
def _topo_to_sphere(theta, radius): sph_phi = ((0.5 - radius) * 180) sph_theta = (- theta) return (sph_phi, sph_theta)
Convert using old function.
convert using old function .
Question: What does this function do? Code: def _topo_to_sphere(theta, radius): sph_phi = ((0.5 - radius) * 180) sph_theta = (- theta) return (sph_phi, sph_theta)
null
null
null
What does this function do?
def get_uid(item): return (hasattr(item, 'uid') and item.uid.value)
null
null
null
UID value of an item if defined.
pcsd
def get uid item return hasattr item 'uid' and item uid value
4021
def get_uid(item): return (hasattr(item, 'uid') and item.uid.value)
UID value of an item if defined.
uid value of an item if defined .
Question: What does this function do? Code: def get_uid(item): return (hasattr(item, 'uid') and item.uid.value)
null
null
null
What does this function do?
@requires_application() def test_reactive_draw(): with TestingCanvas() as c: ellipse = visuals.Ellipse(center=[75, 35, 0.0], radius=[20, 15], color='yellow', parent=c.scene) ellipse.center = [70, 40, 0.0] assert_image_approved(c.render(), 'visuals/reactive_ellipse1.png') ellipse.radius = 25 assert_image_appr...
null
null
null
Test reactive ellipse attributes
pcsd
@requires application def test reactive draw with Testing Canvas as c ellipse = visuals Ellipse center=[75 35 0 0] radius=[20 15] color='yellow' parent=c scene ellipse center = [70 40 0 0] assert image approved c render 'visuals/reactive ellipse1 png' ellipse radius = 25 assert image approved c render 'visuals/reactive...
4038
@requires_application() def test_reactive_draw(): with TestingCanvas() as c: ellipse = visuals.Ellipse(center=[75, 35, 0.0], radius=[20, 15], color='yellow', parent=c.scene) ellipse.center = [70, 40, 0.0] assert_image_approved(c.render(), 'visuals/reactive_ellipse1.png') ellipse.radius = 25 assert_image_appr...
Test reactive ellipse attributes
test reactive ellipse attributes
Question: What does this function do? Code: @requires_application() def test_reactive_draw(): with TestingCanvas() as c: ellipse = visuals.Ellipse(center=[75, 35, 0.0], radius=[20, 15], color='yellow', parent=c.scene) ellipse.center = [70, 40, 0.0] assert_image_approved(c.render(), 'visuals/reactive_ellipse1....
null
null
null
What does this function do?
def decode_base64(text, encoding='utf-8'): text = to_bytes(text, encoding) return to_unicode(base64.b64decode(text), encoding)
null
null
null
Decode base64 string.
pcsd
def decode base64 text encoding='utf-8' text = to bytes text encoding return to unicode base64 b64decode text encoding
4045
def decode_base64(text, encoding='utf-8'): text = to_bytes(text, encoding) return to_unicode(base64.b64decode(text), encoding)
Decode base64 string.
decode base64 string .
Question: What does this function do? Code: def decode_base64(text, encoding='utf-8'): text = to_bytes(text, encoding) return to_unicode(base64.b64decode(text), encoding)
null
null
null
What does this function do?
def _tag_added(sender, question_id, tag_name, **kwargs): if (tag_name == config.ESCALATE_TAG_NAME): escalate_question.delay(question_id)
null
null
null
Signal handler for new tag on question.
pcsd
def tag added sender question id tag name **kwargs if tag name == config ESCALATE TAG NAME escalate question delay question id
4046
def _tag_added(sender, question_id, tag_name, **kwargs): if (tag_name == config.ESCALATE_TAG_NAME): escalate_question.delay(question_id)
Signal handler for new tag on question.
signal handler for new tag on question .
Question: What does this function do? Code: def _tag_added(sender, question_id, tag_name, **kwargs): if (tag_name == config.ESCALATE_TAG_NAME): escalate_question.delay(question_id)
null
null
null
What does this function do?
def child_fd_list_add(fd): global child_fd_list child_fd_list.append(fd)
null
null
null
add a file descriptor to list to be closed in child processes
pcsd
def child fd list add fd global child fd list child fd list append fd
4061
def child_fd_list_add(fd): global child_fd_list child_fd_list.append(fd)
add a file descriptor to list to be closed in child processes
add a file descriptor to list to be closed in child processes
Question: What does this function do? Code: def child_fd_list_add(fd): global child_fd_list child_fd_list.append(fd)
null
null
null
What does this function do?
def ion(): matplotlib.interactive(True) install_repl_displayhook()
null
null
null
Turn interactive mode on.
pcsd
def ion matplotlib interactive True install repl displayhook
4065
def ion(): matplotlib.interactive(True) install_repl_displayhook()
Turn interactive mode on.
turn interactive mode on .
Question: What does this function do? Code: def ion(): matplotlib.interactive(True) install_repl_displayhook()
null
null
null
What does this function do?
def _RetainVerticalSpacingBeforeComments(uwline): prev_token = None for tok in uwline.tokens: if (tok.is_comment and prev_token): if (((tok.lineno - tok.value.count(u'\n')) - prev_token.lineno) > 1): tok.AdjustNewlinesBefore(ONE_BLANK_LINE) prev_token = tok
null
null
null
Retain vertical spacing before comments.
pcsd
def Retain Vertical Spacing Before Comments uwline prev token = None for tok in uwline tokens if tok is comment and prev token if tok lineno - tok value count u' ' - prev token lineno > 1 tok Adjust Newlines Before ONE BLANK LINE prev token = tok
4070
def _RetainVerticalSpacingBeforeComments(uwline): prev_token = None for tok in uwline.tokens: if (tok.is_comment and prev_token): if (((tok.lineno - tok.value.count(u'\n')) - prev_token.lineno) > 1): tok.AdjustNewlinesBefore(ONE_BLANK_LINE) prev_token = tok
Retain vertical spacing before comments.
retain vertical spacing before comments .
Question: What does this function do? Code: def _RetainVerticalSpacingBeforeComments(uwline): prev_token = None for tok in uwline.tokens: if (tok.is_comment and prev_token): if (((tok.lineno - tok.value.count(u'\n')) - prev_token.lineno) > 1): tok.AdjustNewlinesBefore(ONE_BLANK_LINE) prev_token = tok
null
null
null
What does this function do?
def _cleanup(): es = elasticsearch.Elasticsearch(connection_class=Urllib3HttpConnection, host=HOST, port=PORT, http_auth=HTTP_AUTH) if es.indices.exists(MARKER_INDEX): es.indices.delete(MARKER_INDEX) if es.indices.exists(INDEX): es.indices.delete(INDEX)
null
null
null
Delete both the test marker index and the content index.
pcsd
def cleanup es = elasticsearch Elasticsearch connection class=Urllib3Http Connection host=HOST port=PORT http auth=HTTP AUTH if es indices exists MARKER INDEX es indices delete MARKER INDEX if es indices exists INDEX es indices delete INDEX
4087
def _cleanup(): es = elasticsearch.Elasticsearch(connection_class=Urllib3HttpConnection, host=HOST, port=PORT, http_auth=HTTP_AUTH) if es.indices.exists(MARKER_INDEX): es.indices.delete(MARKER_INDEX) if es.indices.exists(INDEX): es.indices.delete(INDEX)
Delete both the test marker index and the content index.
delete both the test marker index and the content index .
Question: What does this function do? Code: def _cleanup(): es = elasticsearch.Elasticsearch(connection_class=Urllib3HttpConnection, host=HOST, port=PORT, http_auth=HTTP_AUTH) if es.indices.exists(MARKER_INDEX): es.indices.delete(MARKER_INDEX) if es.indices.exists(INDEX): es.indices.delete(INDEX)
null
null
null
What does this function do?
def slugify(text, entities=True, decimal=True, hexadecimal=True, max_length=0, word_boundary=False, separator='-'): if (not isinstance(text, types.UnicodeType)): text = unicode(text, 'utf-8', 'ignore') text = unidecode(text) if (not isinstance(text, types.UnicodeType)): text = unicode(text, 'utf-8', 'ignore') i...
null
null
null
Make a slug from the given text
pcsd
def slugify text entities=True decimal=True hexadecimal=True max length=0 word boundary=False separator='-' if not isinstance text types Unicode Type text = unicode text 'utf-8' 'ignore' text = unidecode text if not isinstance text types Unicode Type text = unicode text 'utf-8' 'ignore' if entities text = CHAR ENTITY R...
4092
def slugify(text, entities=True, decimal=True, hexadecimal=True, max_length=0, word_boundary=False, separator='-'): if (not isinstance(text, types.UnicodeType)): text = unicode(text, 'utf-8', 'ignore') text = unidecode(text) if (not isinstance(text, types.UnicodeType)): text = unicode(text, 'utf-8', 'ignore') i...
Make a slug from the given text
make a slug from the given text
Question: What does this function do? Code: def slugify(text, entities=True, decimal=True, hexadecimal=True, max_length=0, word_boundary=False, separator='-'): if (not isinstance(text, types.UnicodeType)): text = unicode(text, 'utf-8', 'ignore') text = unidecode(text) if (not isinstance(text, types.UnicodeType)...
null
null
null
What does this function do?
def short_token(): hash = hashlib.sha1(shortuuid.uuid()) hash.update(settings.SECRET_KEY) return hash.hexdigest()[::2]
null
null
null
Generate a hash that can be used as an application identifier
pcsd
def short token hash = hashlib sha1 shortuuid uuid hash update settings SECRET KEY return hash hexdigest [ 2]
4095
def short_token(): hash = hashlib.sha1(shortuuid.uuid()) hash.update(settings.SECRET_KEY) return hash.hexdigest()[::2]
Generate a hash that can be used as an application identifier
generate a hash that can be used as an application identifier
Question: What does this function do? Code: def short_token(): hash = hashlib.sha1(shortuuid.uuid()) hash.update(settings.SECRET_KEY) return hash.hexdigest()[::2]
null
null
null
What does this function do?
def merge_adjacent(gen): gen = iter(gen) last = next(gen) for this in gen: if (this.merge_key == last.merge_key): last.merge(this) elif (last < this): (yield last) last = this else: raise AssertionError(('Bad order, %s > %s' % (last, this))) (yield last)
null
null
null
Merge adjacent messages that compare equal
pcsd
def merge adjacent gen gen = iter gen last = next gen for this in gen if this merge key == last merge key last merge this elif last < this yield last last = this else raise Assertion Error 'Bad order %s > %s' % last this yield last
4096
def merge_adjacent(gen): gen = iter(gen) last = next(gen) for this in gen: if (this.merge_key == last.merge_key): last.merge(this) elif (last < this): (yield last) last = this else: raise AssertionError(('Bad order, %s > %s' % (last, this))) (yield last)
Merge adjacent messages that compare equal
merge adjacent messages that compare equal
Question: What does this function do? Code: def merge_adjacent(gen): gen = iter(gen) last = next(gen) for this in gen: if (this.merge_key == last.merge_key): last.merge(this) elif (last < this): (yield last) last = this else: raise AssertionError(('Bad order, %s > %s' % (last, this))) (yield la...
null
null
null
What does this function do?
def _default_ret(name): return {'name': name, 'result': False, 'comment': '', 'changes': {}}
null
null
null
Default dictionary returned.
pcsd
def default ret name return {'name' name 'result' False 'comment' '' 'changes' {}}
4100
def _default_ret(name): return {'name': name, 'result': False, 'comment': '', 'changes': {}}
Default dictionary returned.
default dictionary returned .
Question: What does this function do? Code: def _default_ret(name): return {'name': name, 'result': False, 'comment': '', 'changes': {}}
null
null
null
What does this function do?
def _ordereddict2dict(input_ordered_dict): return json.loads(json.dumps(input_ordered_dict))
null
null
null
Convert ordered dictionary to a dictionary
pcsd
def ordereddict2dict input ordered dict return json loads json dumps input ordered dict
4115
def _ordereddict2dict(input_ordered_dict): return json.loads(json.dumps(input_ordered_dict))
Convert ordered dictionary to a dictionary
convert ordered dictionary to a dictionary
Question: What does this function do? Code: def _ordereddict2dict(input_ordered_dict): return json.loads(json.dumps(input_ordered_dict))
null
null
null
What does this function do?
def discretize_bilinear_2D(model, x_range, y_range): x = np.arange((x_range[0] - 0.5), (x_range[1] + 0.5)) y = np.arange((y_range[0] - 0.5), (y_range[1] + 0.5)) (x, y) = np.meshgrid(x, y) values_intermediate_grid = model(x, y) values = (0.5 * (values_intermediate_grid[1:, :] + values_intermediate_grid[:(-1), :])) ...
null
null
null
Discretize model by performing a bilinear interpolation.
pcsd
def discretize bilinear 2D model x range y range x = np arange x range[0] - 0 5 x range[1] + 0 5 y = np arange y range[0] - 0 5 y range[1] + 0 5 x y = np meshgrid x y values intermediate grid = model x y values = 0 5 * values intermediate grid[1 ] + values intermediate grid[ -1 ] values = 0 5 * values[ 1 ] + values[ -1...
4122
def discretize_bilinear_2D(model, x_range, y_range): x = np.arange((x_range[0] - 0.5), (x_range[1] + 0.5)) y = np.arange((y_range[0] - 0.5), (y_range[1] + 0.5)) (x, y) = np.meshgrid(x, y) values_intermediate_grid = model(x, y) values = (0.5 * (values_intermediate_grid[1:, :] + values_intermediate_grid[:(-1), :])) ...
Discretize model by performing a bilinear interpolation.
discretize model by performing a bilinear interpolation .
Question: What does this function do? Code: def discretize_bilinear_2D(model, x_range, y_range): x = np.arange((x_range[0] - 0.5), (x_range[1] + 0.5)) y = np.arange((y_range[0] - 0.5), (y_range[1] + 0.5)) (x, y) = np.meshgrid(x, y) values_intermediate_grid = model(x, y) values = (0.5 * (values_intermediate_grid...
null
null
null
What does this function do?
def re_meta(line, match=None): if match: reStr = re.compile(u'^\\.\\. {0}: (.*)'.format(re.escape(match))) else: reStr = re.compile(u'^\\.\\. (.*?): (.*)') result = reStr.findall(line.strip()) if (match and result): return (match, result[0]) elif ((not match) and result): return (result[0][0], result[0][1]...
null
null
null
Find metadata using regular expressions.
pcsd
def re meta line match=None if match re Str = re compile u'^\\ \\ {0} * ' format re escape match else re Str = re compile u'^\\ \\ *? * ' result = re Str findall line strip if match and result return match result[0] elif not match and result return result[0][0] result[0][1] strip else return None
4126
def re_meta(line, match=None): if match: reStr = re.compile(u'^\\.\\. {0}: (.*)'.format(re.escape(match))) else: reStr = re.compile(u'^\\.\\. (.*?): (.*)') result = reStr.findall(line.strip()) if (match and result): return (match, result[0]) elif ((not match) and result): return (result[0][0], result[0][1]...
Find metadata using regular expressions.
find metadata using regular expressions .
Question: What does this function do? Code: def re_meta(line, match=None): if match: reStr = re.compile(u'^\\.\\. {0}: (.*)'.format(re.escape(match))) else: reStr = re.compile(u'^\\.\\. (.*?): (.*)') result = reStr.findall(line.strip()) if (match and result): return (match, result[0]) elif ((not match) an...
null
null
null
What does this function do?
def parseApplication(app): return Direction(app[0], app[1:])
null
null
null
Parse an application operator
pcsd
def parse Application app return Direction app[0] app[1 ]
4131
def parseApplication(app): return Direction(app[0], app[1:])
Parse an application operator
parse an application operator
Question: What does this function do? Code: def parseApplication(app): return Direction(app[0], app[1:])
null
null
null
What does this function do?
@pytest.mark.skipif('sys.version_info < (3,3)') def test_find_module_py33(): assert (find_module_py33('_io') == (None, '_io', False))
null
null
null
Needs to work like the old find_module.
pcsd
@pytest mark skipif 'sys version info < 3 3 ' def test find module py33 assert find module py33 ' io' == None ' io' False
4138
@pytest.mark.skipif('sys.version_info < (3,3)') def test_find_module_py33(): assert (find_module_py33('_io') == (None, '_io', False))
Needs to work like the old find_module.
needs to work like the old find _ module .
Question: What does this function do? Code: @pytest.mark.skipif('sys.version_info < (3,3)') def test_find_module_py33(): assert (find_module_py33('_io') == (None, '_io', False))
null
null
null
What does this function do?
def list_bucket(bucket): service = create_service() fields_to_return = 'nextPageToken,items(name,size,contentType,metadata(my-key))' req = service.objects().list(bucket=bucket, fields=fields_to_return) all_objects = [] while req: resp = req.execute() all_objects.extend(resp.get('items', [])) req = service.ob...
null
null
null
Returns a list of metadata of the objects within the given bucket.
pcsd
def list bucket bucket service = create service fields to return = 'next Page Token items name size content Type metadata my-key ' req = service objects list bucket=bucket fields=fields to return all objects = [] while req resp = req execute all objects extend resp get 'items' [] req = service objects list next req res...
4145
def list_bucket(bucket): service = create_service() fields_to_return = 'nextPageToken,items(name,size,contentType,metadata(my-key))' req = service.objects().list(bucket=bucket, fields=fields_to_return) all_objects = [] while req: resp = req.execute() all_objects.extend(resp.get('items', [])) req = service.ob...
Returns a list of metadata of the objects within the given bucket.
returns a list of metadata of the objects within the given bucket .
Question: What does this function do? Code: def list_bucket(bucket): service = create_service() fields_to_return = 'nextPageToken,items(name,size,contentType,metadata(my-key))' req = service.objects().list(bucket=bucket, fields=fields_to_return) all_objects = [] while req: resp = req.execute() all_objects.e...
null
null
null
What does this function do?
def binop(x, op, y, lineno=None, col=None): lineno = (x.lineno if (lineno is None) else lineno) col = (x.col_offset if (col is None) else col) return ast.BinOp(left=x, op=op, right=y, lineno=lineno, col_offset=col)
null
null
null
Creates the AST node for a binary operation.
pcsd
def binop x op y lineno=None col=None lineno = x lineno if lineno is None else lineno col = x col offset if col is None else col return ast Bin Op left=x op=op right=y lineno=lineno col offset=col
4148
def binop(x, op, y, lineno=None, col=None): lineno = (x.lineno if (lineno is None) else lineno) col = (x.col_offset if (col is None) else col) return ast.BinOp(left=x, op=op, right=y, lineno=lineno, col_offset=col)
Creates the AST node for a binary operation.
creates the ast node for a binary operation .
Question: What does this function do? Code: def binop(x, op, y, lineno=None, col=None): lineno = (x.lineno if (lineno is None) else lineno) col = (x.col_offset if (col is None) else col) return ast.BinOp(left=x, op=op, right=y, lineno=lineno, col_offset=col)
null
null
null
What does this function do?
def encodestring(s): pieces = [] for i in range(0, len(s), MAXBINSIZE): chunk = s[i:(i + MAXBINSIZE)] pieces.append(binascii.b2a_base64(chunk)) return ''.join(pieces)
null
null
null
Encode a string into multiple lines of base-64 data.
pcsd
def encodestring s pieces = [] for i in range 0 len s MAXBINSIZE chunk = s[i i + MAXBINSIZE ] pieces append binascii b2a base64 chunk return '' join pieces
4151
def encodestring(s): pieces = [] for i in range(0, len(s), MAXBINSIZE): chunk = s[i:(i + MAXBINSIZE)] pieces.append(binascii.b2a_base64(chunk)) return ''.join(pieces)
Encode a string into multiple lines of base-64 data.
encode a string into multiple lines of base - 64 data .
Question: What does this function do? Code: def encodestring(s): pieces = [] for i in range(0, len(s), MAXBINSIZE): chunk = s[i:(i + MAXBINSIZE)] pieces.append(binascii.b2a_base64(chunk)) return ''.join(pieces)
null
null
null
What does this function do?
@ensure_csrf_cookie @cache_if_anonymous() def courses(request): courses_list = [] programs_list = [] course_discovery_meanings = getattr(settings, 'COURSE_DISCOVERY_MEANINGS', {}) if (not settings.FEATURES.get('ENABLE_COURSE_DISCOVERY')): courses_list = get_courses(request.user) if configuration_helpers.get_val...
null
null
null
Render "find courses" page. The course selection work is done in courseware.courses.
pcsd
@ensure csrf cookie @cache if anonymous def courses request courses list = [] programs list = [] course discovery meanings = getattr settings 'COURSE DISCOVERY MEANINGS' {} if not settings FEATURES get 'ENABLE COURSE DISCOVERY' courses list = get courses request user if configuration helpers get value 'ENABLE COURSE SO...
4187
@ensure_csrf_cookie @cache_if_anonymous() def courses(request): courses_list = [] programs_list = [] course_discovery_meanings = getattr(settings, 'COURSE_DISCOVERY_MEANINGS', {}) if (not settings.FEATURES.get('ENABLE_COURSE_DISCOVERY')): courses_list = get_courses(request.user) if configuration_helpers.get_val...
Render "find courses" page. The course selection work is done in courseware.courses.
render " find courses " page .
Question: What does this function do? Code: @ensure_csrf_cookie @cache_if_anonymous() def courses(request): courses_list = [] programs_list = [] course_discovery_meanings = getattr(settings, 'COURSE_DISCOVERY_MEANINGS', {}) if (not settings.FEATURES.get('ENABLE_COURSE_DISCOVERY')): courses_list = get_courses(r...
null
null
null
What does this function do?
def address_pairs(fields): pairs = list(zip(fields[::2], fields[1::2])) if (len(fields) % 2): pairs.append(fields[(-1)]) return pairs
null
null
null
Zips address fields into pairs, appending the last field if the total is an odd number.
pcsd
def address pairs fields pairs = list zip fields[ 2] fields[1 2] if len fields % 2 pairs append fields[ -1 ] return pairs
4195
def address_pairs(fields): pairs = list(zip(fields[::2], fields[1::2])) if (len(fields) % 2): pairs.append(fields[(-1)]) return pairs
Zips address fields into pairs, appending the last field if the total is an odd number.
zips address fields into pairs , appending the last field if the total is an odd number .
Question: What does this function do? Code: def address_pairs(fields): pairs = list(zip(fields[::2], fields[1::2])) if (len(fields) % 2): pairs.append(fields[(-1)]) return pairs
null
null
null
What does this function do?
def p_statement_expr(t): t[0] = t[1]
null
null
null
statement : expression
pcsd
def p statement expr t t[0] = t[1]
4202
def p_statement_expr(t): t[0] = t[1]
statement : expression
statement : expression
Question: What does this function do? Code: def p_statement_expr(t): t[0] = t[1]
null
null
null
What does this function do?
def history_changed(proc, TIMEOUT, to): proc.send('\x1b[A') assert proc.expect([TIMEOUT, to])
null
null
null
Ensures that history changed.
pcsd
def history changed proc TIMEOUT to proc send '\x1b[A' assert proc expect [TIMEOUT to]
4205
def history_changed(proc, TIMEOUT, to): proc.send('\x1b[A') assert proc.expect([TIMEOUT, to])
Ensures that history changed.
ensures that history changed .
Question: What does this function do? Code: def history_changed(proc, TIMEOUT, to): proc.send('\x1b[A') assert proc.expect([TIMEOUT, to])
null
null
null
What does this function do?
def install(): p = PollReactor() from twisted.internet.main import installReactor installReactor(p)
null
null
null
Install the poll() reactor.
pcsd
def install p = Poll Reactor from twisted internet main import install Reactor install Reactor p
4208
def install(): p = PollReactor() from twisted.internet.main import installReactor installReactor(p)
Install the poll() reactor.
install the poll ( ) reactor .
Question: What does this function do? Code: def install(): p = PollReactor() from twisted.internet.main import installReactor installReactor(p)