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 isGoodResult(name, show, log=True, season=(-1)): all_show_names = allPossibleShowNames(show, season=season) showNames = (map(sanitizeSceneName, all_show_names) + all_show_names) for curName in set(showNames): if (not show.is_anime): escaped_name = re.sub(u'\\\\[\\s.-]', u'\\W+', re.escape(curName)) if sh...
null
null
null
Use an automatically-created regex to make sure the result actually is the show it claims to be
pcsd
def is Good Result name show log=True season= -1 all show names = all Possible Show Names show season=season show Names = map sanitize Scene Name all show names + all show names for cur Name in set show Names if not show is anime escaped name = re sub u'\\\\[\\s -]' u'\\W+' re escape cur Name if show startyear escaped ...
4805
def isGoodResult(name, show, log=True, season=(-1)): all_show_names = allPossibleShowNames(show, season=season) showNames = (map(sanitizeSceneName, all_show_names) + all_show_names) for curName in set(showNames): if (not show.is_anime): escaped_name = re.sub(u'\\\\[\\s.-]', u'\\W+', re.escape(curName)) if sh...
Use an automatically-created regex to make sure the result actually is the show it claims to be
use an automatically - created regex to make sure the result actually is the show it claims to be
Question: What does this function do? Code: def isGoodResult(name, show, log=True, season=(-1)): all_show_names = allPossibleShowNames(show, season=season) showNames = (map(sanitizeSceneName, all_show_names) + all_show_names) for curName in set(showNames): if (not show.is_anime): escaped_name = re.sub(u'\\\\...
null
null
null
What does this function do?
def get_server(*args, **kwargs): from django.conf import settings server_name = getattr(settings, 'LETTUCE_TEST_SERVER', 'lettuce.django.server.DefaultServer') (module, klass) = server_name.rsplit('.', 1) Server = getattr(__import__(module, fromlist=[klass]), klass) global server, django_url server = Server(*args...
null
null
null
Look up the server we are using and set it as the global
pcsd
def get server *args **kwargs from django conf import settings server name = getattr settings 'LETTUCE TEST SERVER' 'lettuce django server Default Server' module klass = server name rsplit ' ' 1 Server = getattr import module fromlist=[klass] klass global server django url server = Server *args **kwargs django url = se...
4820
def get_server(*args, **kwargs): from django.conf import settings server_name = getattr(settings, 'LETTUCE_TEST_SERVER', 'lettuce.django.server.DefaultServer') (module, klass) = server_name.rsplit('.', 1) Server = getattr(__import__(module, fromlist=[klass]), klass) global server, django_url server = Server(*args...
Look up the server we are using and set it as the global
look up the server we are using and set it as the global
Question: What does this function do? Code: def get_server(*args, **kwargs): from django.conf import settings server_name = getattr(settings, 'LETTUCE_TEST_SERVER', 'lettuce.django.server.DefaultServer') (module, klass) = server_name.rsplit('.', 1) Server = getattr(__import__(module, fromlist=[klass]), klass) g...
null
null
null
What does this function do?
def render_to_kml(*args, **kwargs): return HttpResponse(loader.render_to_string(*args, **kwargs), content_type='application/vnd.google-earth.kml+xml')
null
null
null
Renders the response as KML (using the correct MIME type).
pcsd
def render to kml *args **kwargs return Http Response loader render to string *args **kwargs content type='application/vnd google-earth kml+xml'
4831
def render_to_kml(*args, **kwargs): return HttpResponse(loader.render_to_string(*args, **kwargs), content_type='application/vnd.google-earth.kml+xml')
Renders the response as KML (using the correct MIME type).
renders the response as kml .
Question: What does this function do? Code: def render_to_kml(*args, **kwargs): return HttpResponse(loader.render_to_string(*args, **kwargs), content_type='application/vnd.google-earth.kml+xml')
null
null
null
What does this function do?
def parse_rows_with(reader, parsers): for row in reader: (yield parse_row(row, parsers))
null
null
null
wrap a reader to apply the parsers to each of its rows
pcsd
def parse rows with reader parsers for row in reader yield parse row row parsers
4833
def parse_rows_with(reader, parsers): for row in reader: (yield parse_row(row, parsers))
wrap a reader to apply the parsers to each of its rows
wrap a reader to apply the parsers to each of its rows
Question: What does this function do? Code: def parse_rows_with(reader, parsers): for row in reader: (yield parse_row(row, parsers))
null
null
null
What does this function do?
def _strptime(data_string, format='%a %b %d %H:%M:%S %Y'): global _TimeRE_cache, _regex_cache with _cache_lock: if (_getlang() != _TimeRE_cache.locale_time.lang): _TimeRE_cache = TimeRE() _regex_cache.clear() if (len(_regex_cache) > _CACHE_MAX_SIZE): _regex_cache.clear() locale_time = _TimeRE_cache.loc...
null
null
null
Return a time struct based on the input string and the format string.
pcsd
def strptime data string format='%a %b %d %H %M %S %Y' global Time RE cache regex cache with cache lock if getlang != Time RE cache locale time lang Time RE cache = Time RE regex cache clear if len regex cache > CACHE MAX SIZE regex cache clear locale time = Time RE cache locale time format regex = regex cache get form...
4844
def _strptime(data_string, format='%a %b %d %H:%M:%S %Y'): global _TimeRE_cache, _regex_cache with _cache_lock: if (_getlang() != _TimeRE_cache.locale_time.lang): _TimeRE_cache = TimeRE() _regex_cache.clear() if (len(_regex_cache) > _CACHE_MAX_SIZE): _regex_cache.clear() locale_time = _TimeRE_cache.loc...
Return a time struct based on the input string and the format string.
return a time struct based on the input string and the format string .
Question: What does this function do? Code: def _strptime(data_string, format='%a %b %d %H:%M:%S %Y'): global _TimeRE_cache, _regex_cache with _cache_lock: if (_getlang() != _TimeRE_cache.locale_time.lang): _TimeRE_cache = TimeRE() _regex_cache.clear() if (len(_regex_cache) > _CACHE_MAX_SIZE): _regex_...
null
null
null
What does this function do?
def extract_subdomain(host=None, base_domain=None): if (host is None): host = request.host if (base_domain is None): base_domain = g.domain if (not host): return '' end_index = (host.find(base_domain) - 1) if (end_index < 0): return '' return host[:end_index]
null
null
null
Try to extract a subdomain from the request, as compared to g.domain. host and base_domain exist as arguments primarily for the sake of unit tests, although their usage should not be considered restrained to that.
pcsd
def extract subdomain host=None base domain=None if host is None host = request host if base domain is None base domain = g domain if not host return '' end index = host find base domain - 1 if end index < 0 return '' return host[ end index]
4865
def extract_subdomain(host=None, base_domain=None): if (host is None): host = request.host if (base_domain is None): base_domain = g.domain if (not host): return '' end_index = (host.find(base_domain) - 1) if (end_index < 0): return '' return host[:end_index]
Try to extract a subdomain from the request, as compared to g.domain. host and base_domain exist as arguments primarily for the sake of unit tests, although their usage should not be considered restrained to that.
try to extract a subdomain from the request , as compared to g . domain .
Question: What does this function do? Code: def extract_subdomain(host=None, base_domain=None): if (host is None): host = request.host if (base_domain is None): base_domain = g.domain if (not host): return '' end_index = (host.find(base_domain) - 1) if (end_index < 0): return '' return host[:end_index]...
null
null
null
What does this function do?
def is_page_candidate(urlLink, urlTitle, title, artist): title = slugify(title.lower()) artist = slugify(artist.lower()) sitename = re.search(u'//([^/]+)/.*', slugify(urlLink.lower())).group(1) urlTitle = slugify(urlTitle.lower()) if (urlTitle.find(title) != (-1)): return True tokens = (([((by + '_') + artist) ...
null
null
null
Return True if the URL title makes it a good candidate to be a page that contains lyrics of title by artist.
pcsd
def is page candidate url Link url Title title artist title = slugify title lower artist = slugify artist lower sitename = re search u'// [^/]+ / *' slugify url Link lower group 1 url Title = slugify url Title lower if url Title find title != -1 return True tokens = [ by + ' ' + artist for by in BY TRANS] + [artist sit...
4866
def is_page_candidate(urlLink, urlTitle, title, artist): title = slugify(title.lower()) artist = slugify(artist.lower()) sitename = re.search(u'//([^/]+)/.*', slugify(urlLink.lower())).group(1) urlTitle = slugify(urlTitle.lower()) if (urlTitle.find(title) != (-1)): return True tokens = (([((by + '_') + artist) ...
Return True if the URL title makes it a good candidate to be a page that contains lyrics of title by artist.
return true if the url title makes it a good candidate to be a page that contains lyrics of title by artist .
Question: What does this function do? Code: def is_page_candidate(urlLink, urlTitle, title, artist): title = slugify(title.lower()) artist = slugify(artist.lower()) sitename = re.search(u'//([^/]+)/.*', slugify(urlLink.lower())).group(1) urlTitle = slugify(urlTitle.lower()) if (urlTitle.find(title) != (-1)): ...
null
null
null
What does this function do?
def restore_cache(old_cache): global FS_CACHE FS_CACHE = old_cache
null
null
null
Restores cache from the result of a previous clear_cache call.
pcsd
def restore cache old cache global FS CACHE FS CACHE = old cache
4892
def restore_cache(old_cache): global FS_CACHE FS_CACHE = old_cache
Restores cache from the result of a previous clear_cache call.
restores cache from the result of a previous clear _ cache call .
Question: What does this function do? Code: def restore_cache(old_cache): global FS_CACHE FS_CACHE = old_cache
null
null
null
What does this function do?
def technical_500_response(request, exc_type, exc_value, tb): template_info = None template_does_not_exist = False loader_debug_info = None if issubclass(exc_type, TemplateDoesNotExist): from django.template.loader import template_source_loaders template_does_not_exist = True loader_debug_info = [] for load...
null
null
null
Create a technical server error response. The last three arguments are the values returned from sys.exc_info() and friends.
pcsd
def technical 500 response request exc type exc value tb template info = None template does not exist = False loader debug info = None if issubclass exc type Template Does Not Exist from django template loader import template source loaders template does not exist = True loader debug info = [] for loader in template so...
4893
def technical_500_response(request, exc_type, exc_value, tb): template_info = None template_does_not_exist = False loader_debug_info = None if issubclass(exc_type, TemplateDoesNotExist): from django.template.loader import template_source_loaders template_does_not_exist = True loader_debug_info = [] for load...
Create a technical server error response. The last three arguments are the values returned from sys.exc_info() and friends.
create a technical server error response .
Question: What does this function do? Code: def technical_500_response(request, exc_type, exc_value, tb): template_info = None template_does_not_exist = False loader_debug_info = None if issubclass(exc_type, TemplateDoesNotExist): from django.template.loader import template_source_loaders template_does_not_e...
null
null
null
What does this function do?
@_get_client def image_location_delete(client, image_id, location_id, status, session=None): client.image_location_delete(image_id=image_id, location_id=location_id, status=status)
null
null
null
Delete an image location.
pcsd
@ get client def image location delete client image id location id status session=None client image location delete image id=image id location id=location id status=status
4907
@_get_client def image_location_delete(client, image_id, location_id, status, session=None): client.image_location_delete(image_id=image_id, location_id=location_id, status=status)
Delete an image location.
delete an image location .
Question: What does this function do? Code: @_get_client def image_location_delete(client, image_id, location_id, status, session=None): client.image_location_delete(image_id=image_id, location_id=location_id, status=status)
null
null
null
What does this function do?
def list_config_modules(etcdir): if (not os.path.isdir(etcdir)): return iter(()) return (name for name in os.listdir(etcdir) if (name.endswith('.py') and os.path.isfile(os.path.join(etcdir, name))))
null
null
null
Returns an iterator that yields the name of all the config modules.
pcsd
def list config modules etcdir if not os path isdir etcdir return iter return name for name in os listdir etcdir if name endswith ' py' and os path isfile os path join etcdir name
4910
def list_config_modules(etcdir): if (not os.path.isdir(etcdir)): return iter(()) return (name for name in os.listdir(etcdir) if (name.endswith('.py') and os.path.isfile(os.path.join(etcdir, name))))
Returns an iterator that yields the name of all the config modules.
returns an iterator that yields the name of all the config modules .
Question: What does this function do? Code: def list_config_modules(etcdir): if (not os.path.isdir(etcdir)): return iter(()) return (name for name in os.listdir(etcdir) if (name.endswith('.py') and os.path.isfile(os.path.join(etcdir, name))))
null
null
null
What does this function do?
def line_2d_to_3d(line, zs=0, zdir=u'z'): line.__class__ = Line3D line.set_3d_properties(zs, zdir)
null
null
null
Convert a 2D line to 3D.
pcsd
def line 2d to 3d line zs=0 zdir=u'z' line class = Line3D line set 3d properties zs zdir
4913
def line_2d_to_3d(line, zs=0, zdir=u'z'): line.__class__ = Line3D line.set_3d_properties(zs, zdir)
Convert a 2D line to 3D.
convert a 2d line to 3d .
Question: What does this function do? Code: def line_2d_to_3d(line, zs=0, zdir=u'z'): line.__class__ = Line3D line.set_3d_properties(zs, zdir)
null
null
null
What does this function do?
def row2feature(row, id_field, geometry_field): feature = {'type': 'Feature', 'properties': _copy(row)} geometry = feature['properties'].pop(geometry_field) feature['geometry'] = _loadshape(_unhexlify(geometry)) feature['id'] = feature['properties'].pop(id_field) return feature
null
null
null
Convert a database row dict to a feature dict.
pcsd
def row2feature row id field geometry field feature = {'type' 'Feature' 'properties' copy row } geometry = feature['properties'] pop geometry field feature['geometry'] = loadshape unhexlify geometry feature['id'] = feature['properties'] pop id field return feature
4920
def row2feature(row, id_field, geometry_field): feature = {'type': 'Feature', 'properties': _copy(row)} geometry = feature['properties'].pop(geometry_field) feature['geometry'] = _loadshape(_unhexlify(geometry)) feature['id'] = feature['properties'].pop(id_field) return feature
Convert a database row dict to a feature dict.
convert a database row dict to a feature dict .
Question: What does this function do? Code: def row2feature(row, id_field, geometry_field): feature = {'type': 'Feature', 'properties': _copy(row)} geometry = feature['properties'].pop(geometry_field) feature['geometry'] = _loadshape(_unhexlify(geometry)) feature['id'] = feature['properties'].pop(id_field) retu...
null
null
null
What does this function do?
def voidptr_output(func, argtypes): func.argtypes = argtypes func.restype = c_void_p func.errcheck = check_pointer return func
null
null
null
For functions that return c_void_p.
pcsd
def voidptr output func argtypes func argtypes = argtypes func restype = c void p func errcheck = check pointer return func
4921
def voidptr_output(func, argtypes): func.argtypes = argtypes func.restype = c_void_p func.errcheck = check_pointer return func
For functions that return c_void_p.
for functions that return c _ void _ p .
Question: What does this function do? Code: def voidptr_output(func, argtypes): func.argtypes = argtypes func.restype = c_void_p func.errcheck = check_pointer return func
null
null
null
What does this function do?
def get_cosine(vec1, vec2): return (numpy.dot(vec1, vec2) / (numpy.linalg.norm(vec1) * numpy.linalg.norm(vec2)))
null
null
null
Get cosine for two given vectors
pcsd
def get cosine vec1 vec2 return numpy dot vec1 vec2 / numpy linalg norm vec1 * numpy linalg norm vec2
4923
def get_cosine(vec1, vec2): return (numpy.dot(vec1, vec2) / (numpy.linalg.norm(vec1) * numpy.linalg.norm(vec2)))
Get cosine for two given vectors
get cosine for two given vectors
Question: What does this function do? Code: def get_cosine(vec1, vec2): return (numpy.dot(vec1, vec2) / (numpy.linalg.norm(vec1) * numpy.linalg.norm(vec2)))
null
null
null
What does this function do?
def get_view_restrictions(pages): restricted_pages = defaultdict(list) if (not get_cms_setting('PERMISSION')): return restricted_pages if (not pages): return restricted_pages is_public_pages = (not pages[0].publisher_is_draft) if is_public_pages: draft_ids = (page.publisher_public_id for page in pages) pag...
null
null
null
Load all view restrictions for the pages
pcsd
def get view restrictions pages restricted pages = defaultdict list if not get cms setting 'PERMISSION' return restricted pages if not pages return restricted pages is public pages = not pages[0] publisher is draft if is public pages draft ids = page publisher public id for page in pages pages = Page objects filter pk ...
4928
def get_view_restrictions(pages): restricted_pages = defaultdict(list) if (not get_cms_setting('PERMISSION')): return restricted_pages if (not pages): return restricted_pages is_public_pages = (not pages[0].publisher_is_draft) if is_public_pages: draft_ids = (page.publisher_public_id for page in pages) pag...
Load all view restrictions for the pages
load all view restrictions for the pages
Question: What does this function do? Code: def get_view_restrictions(pages): restricted_pages = defaultdict(list) if (not get_cms_setting('PERMISSION')): return restricted_pages if (not pages): return restricted_pages is_public_pages = (not pages[0].publisher_is_draft) if is_public_pages: draft_ids = (pa...
null
null
null
What does this function do?
def _next_tree(candidate): (left, rest) = _split_tree(candidate) left_height = max(left) rest_height = max(rest) valid = (rest_height >= left_height) if (valid and (rest_height == left_height)): if (len(left) > len(rest)): valid = False elif ((len(left) == len(rest)) and (left > rest)): valid = False if...
null
null
null
One iteration of the Wright, Richmond, Odlyzko and McKay algorithm.
pcsd
def next tree candidate left rest = split tree candidate left height = max left rest height = max rest valid = rest height >= left height if valid and rest height == left height if len left > len rest valid = False elif len left == len rest and left > rest valid = False if valid return candidate else p = len left new c...
4929
def _next_tree(candidate): (left, rest) = _split_tree(candidate) left_height = max(left) rest_height = max(rest) valid = (rest_height >= left_height) if (valid and (rest_height == left_height)): if (len(left) > len(rest)): valid = False elif ((len(left) == len(rest)) and (left > rest)): valid = False if...
One iteration of the Wright, Richmond, Odlyzko and McKay algorithm.
one iteration of the wright , richmond , odlyzko and mckay algorithm .
Question: What does this function do? Code: def _next_tree(candidate): (left, rest) = _split_tree(candidate) left_height = max(left) rest_height = max(rest) valid = (rest_height >= left_height) if (valid and (rest_height == left_height)): if (len(left) > len(rest)): valid = False elif ((len(left) == len(...
null
null
null
What does this function do?
def fix_w602(source, aggressive=True): if (not aggressive): return source return refactor(source, [u'raise'], ignore=u'with_traceback')
null
null
null
Fix deprecated form of raising exception.
pcsd
def fix w602 source aggressive=True if not aggressive return source return refactor source [u'raise'] ignore=u'with traceback'
4933
def fix_w602(source, aggressive=True): if (not aggressive): return source return refactor(source, [u'raise'], ignore=u'with_traceback')
Fix deprecated form of raising exception.
fix deprecated form of raising exception .
Question: What does this function do? Code: def fix_w602(source, aggressive=True): if (not aggressive): return source return refactor(source, [u'raise'], ignore=u'with_traceback')
null
null
null
What does this function do?
def introduce_vdi(session, sr_ref, vdi_uuid=None, target_lun=None): try: session.call_xenapi('SR.scan', sr_ref) if vdi_uuid: LOG.debug(('vdi_uuid: %s' % vdi_uuid)) vdi_ref = session.call_xenapi('VDI.get_by_uuid', vdi_uuid) elif target_lun: vdi_refs = session.call_xenapi('SR.get_VDIs', sr_ref) for cur...
null
null
null
Introduce VDI in the host.
pcsd
def introduce vdi session sr ref vdi uuid=None target lun=None try session call xenapi 'SR scan' sr ref if vdi uuid LOG debug 'vdi uuid %s' % vdi uuid vdi ref = session call xenapi 'VDI get by uuid' vdi uuid elif target lun vdi refs = session call xenapi 'SR get VD Is' sr ref for curr ref in vdi refs curr rec = session...
4938
def introduce_vdi(session, sr_ref, vdi_uuid=None, target_lun=None): try: session.call_xenapi('SR.scan', sr_ref) if vdi_uuid: LOG.debug(('vdi_uuid: %s' % vdi_uuid)) vdi_ref = session.call_xenapi('VDI.get_by_uuid', vdi_uuid) elif target_lun: vdi_refs = session.call_xenapi('SR.get_VDIs', sr_ref) for cur...
Introduce VDI in the host.
introduce vdi in the host .
Question: What does this function do? Code: def introduce_vdi(session, sr_ref, vdi_uuid=None, target_lun=None): try: session.call_xenapi('SR.scan', sr_ref) if vdi_uuid: LOG.debug(('vdi_uuid: %s' % vdi_uuid)) vdi_ref = session.call_xenapi('VDI.get_by_uuid', vdi_uuid) elif target_lun: vdi_refs = sessio...
null
null
null
What does this function do?
@requires_application() def test_text(): with TestingCanvas(bgcolor='w', size=(92, 92), dpi=92) as c: pos = ([(92 // 2)] * 2) text = Text('testing', font_size=20, color='k', pos=pos, anchor_x='center', anchor_y='baseline', parent=c.scene) assert_image_approved(c.render(), 'visuals/text1.png') text.text = ['foo...
null
null
null
Test basic text support
pcsd
@requires application def test text with Testing Canvas bgcolor='w' size= 92 92 dpi=92 as c pos = [ 92 // 2 ] * 2 text = Text 'testing' font size=20 color='k' pos=pos anchor x='center' anchor y='baseline' parent=c scene assert image approved c render 'visuals/text1 png' text text = ['foo' 'bar'] text pos = [10 10] try ...
4961
@requires_application() def test_text(): with TestingCanvas(bgcolor='w', size=(92, 92), dpi=92) as c: pos = ([(92 // 2)] * 2) text = Text('testing', font_size=20, color='k', pos=pos, anchor_x='center', anchor_y='baseline', parent=c.scene) assert_image_approved(c.render(), 'visuals/text1.png') text.text = ['foo...
Test basic text support
test basic text support
Question: What does this function do? Code: @requires_application() def test_text(): with TestingCanvas(bgcolor='w', size=(92, 92), dpi=92) as c: pos = ([(92 // 2)] * 2) text = Text('testing', font_size=20, color='k', pos=pos, anchor_x='center', anchor_y='baseline', parent=c.scene) assert_image_approved(c.ren...
null
null
null
What does this function do?
@newrelic.agent.function_trace() @block_user_agents @require_http_methods(['GET', 'POST']) @login_required @ratelimit(key='user', rate=limit_banned_ip_to_0, block=True) @process_document_path @check_readonly @prevent_indexing @never_cache def edit(request, document_slug, document_locale, revision_id=None): doc = get_o...
null
null
null
Create a new revision of a wiki document, or edit document metadata.
pcsd
@newrelic agent function trace @block user agents @require http methods ['GET' 'POST'] @login required @ratelimit key='user' rate=limit banned ip to 0 block=True @process document path @check readonly @prevent indexing @never cache def edit request document slug document locale revision id=None doc = get object or 404 ...
4965
@newrelic.agent.function_trace() @block_user_agents @require_http_methods(['GET', 'POST']) @login_required @ratelimit(key='user', rate=limit_banned_ip_to_0, block=True) @process_document_path @check_readonly @prevent_indexing @never_cache def edit(request, document_slug, document_locale, revision_id=None): doc = get_o...
Create a new revision of a wiki document, or edit document metadata.
create a new revision of a wiki document , or edit document metadata .
Question: What does this function do? Code: @newrelic.agent.function_trace() @block_user_agents @require_http_methods(['GET', 'POST']) @login_required @ratelimit(key='user', rate=limit_banned_ip_to_0, block=True) @process_document_path @check_readonly @prevent_indexing @never_cache def edit(request, document_slug, d...
null
null
null
What does this function do?
@_define_event def post_run_cell(): pass
null
null
null
Fires after user-entered code runs.
pcsd
@ define event def post run cell pass
4970
@_define_event def post_run_cell(): pass
Fires after user-entered code runs.
fires after user - entered code runs .
Question: What does this function do? Code: @_define_event def post_run_cell(): pass
null
null
null
What does this function do?
@cronjobs.register def update_visitors_metric(): if settings.STAGE: return latest_metric = _get_latest_metric(VISITORS_METRIC_CODE) if (latest_metric is not None): latest_metric_date = latest_metric.start else: latest_metric_date = date(2011, 1, 1) start = (latest_metric_date + timedelta(days=1)) end = (dat...
null
null
null
Get new visitor data from Google Analytics and save.
pcsd
@cronjobs register def update visitors metric if settings STAGE return latest metric = get latest metric VISITORS METRIC CODE if latest metric is not None latest metric date = latest metric start else latest metric date = date 2011 1 1 start = latest metric date + timedelta days=1 end = date today - timedelta days=1 vi...
4979
@cronjobs.register def update_visitors_metric(): if settings.STAGE: return latest_metric = _get_latest_metric(VISITORS_METRIC_CODE) if (latest_metric is not None): latest_metric_date = latest_metric.start else: latest_metric_date = date(2011, 1, 1) start = (latest_metric_date + timedelta(days=1)) end = (dat...
Get new visitor data from Google Analytics and save.
get new visitor data from google analytics and save .
Question: What does this function do? Code: @cronjobs.register def update_visitors_metric(): if settings.STAGE: return latest_metric = _get_latest_metric(VISITORS_METRIC_CODE) if (latest_metric is not None): latest_metric_date = latest_metric.start else: latest_metric_date = date(2011, 1, 1) start = (late...
null
null
null
What does this function do?
def _add_new_repo(alias, uri, compressed, enabled=True): repostr = ('# ' if (not enabled) else '') repostr += ('src/gz ' if compressed else 'src ') repostr += (((alias + ' ') + uri) + '\n') conffile = os.path.join(OPKG_CONFDIR, (alias + '.conf')) with open(conffile, 'a') as fhandle: fhandle.write(repostr)
null
null
null
Add a new repo entry
pcsd
def add new repo alias uri compressed enabled=True repostr = '# ' if not enabled else '' repostr += 'src/gz ' if compressed else 'src ' repostr += alias + ' ' + uri + ' ' conffile = os path join OPKG CONFDIR alias + ' conf' with open conffile 'a' as fhandle fhandle write repostr
5001
def _add_new_repo(alias, uri, compressed, enabled=True): repostr = ('# ' if (not enabled) else '') repostr += ('src/gz ' if compressed else 'src ') repostr += (((alias + ' ') + uri) + '\n') conffile = os.path.join(OPKG_CONFDIR, (alias + '.conf')) with open(conffile, 'a') as fhandle: fhandle.write(repostr)
Add a new repo entry
add a new repo entry
Question: What does this function do? Code: def _add_new_repo(alias, uri, compressed, enabled=True): repostr = ('# ' if (not enabled) else '') repostr += ('src/gz ' if compressed else 'src ') repostr += (((alias + ' ') + uri) + '\n') conffile = os.path.join(OPKG_CONFDIR, (alias + '.conf')) with open(conffile, '...
null
null
null
What does this function do?
def show_message(message, col=c.r, update=False): g.content = content.generate_songlist_display() g.message = ((col + message) + c.w) if update: screen.update()
null
null
null
Show message using col, update screen if required.
pcsd
def show message message col=c r update=False g content = content generate songlist display g message = col + message + c w if update screen update
5003
def show_message(message, col=c.r, update=False): g.content = content.generate_songlist_display() g.message = ((col + message) + c.w) if update: screen.update()
Show message using col, update screen if required.
show message using col , update screen if required .
Question: What does this function do? Code: def show_message(message, col=c.r, update=False): g.content = content.generate_songlist_display() g.message = ((col + message) + c.w) if update: screen.update()
null
null
null
What does this function do?
def MakeBadSignatureResponse(): return '{"status": 21003}'
null
null
null
Returns a status code indicating an invalid signature.
pcsd
def Make Bad Signature Response return '{"status" 21003}'
5006
def MakeBadSignatureResponse(): return '{"status": 21003}'
Returns a status code indicating an invalid signature.
returns a status code indicating an invalid signature .
Question: What does this function do? Code: def MakeBadSignatureResponse(): return '{"status": 21003}'
null
null
null
What does this function do?
def facility_type(): return s3_rest_controller()
null
null
null
RESTful CRUD controller
pcsd
def facility type return s3 rest controller
5011
def facility_type(): return s3_rest_controller()
RESTful CRUD controller
restful crud controller
Question: What does this function do? Code: def facility_type(): return s3_rest_controller()
null
null
null
What does this function do?
def check_package_data(package_data): print 'checking package data' for (pkg, data) in package_data.items(): pkg_root = pjoin(*pkg.split('.')) for d in data: path = pjoin(pkg_root, d) if ('*' in path): assert (len(glob(path)) > 0), ('No files match pattern %s' % path) else: assert os.path.exists(...
null
null
null
verify that package_data globs make sense
pcsd
def check package data package data print 'checking package data' for pkg data in package data items pkg root = pjoin *pkg split ' ' for d in data path = pjoin pkg root d if '*' in path assert len glob path > 0 'No files match pattern %s' % path else assert os path exists path 'Missing package data %s' % path
5021
def check_package_data(package_data): print 'checking package data' for (pkg, data) in package_data.items(): pkg_root = pjoin(*pkg.split('.')) for d in data: path = pjoin(pkg_root, d) if ('*' in path): assert (len(glob(path)) > 0), ('No files match pattern %s' % path) else: assert os.path.exists(...
verify that package_data globs make sense
verify that package _ data globs make sense
Question: What does this function do? Code: def check_package_data(package_data): print 'checking package data' for (pkg, data) in package_data.items(): pkg_root = pjoin(*pkg.split('.')) for d in data: path = pjoin(pkg_root, d) if ('*' in path): assert (len(glob(path)) > 0), ('No files match pattern ...
null
null
null
What does this function do?
def _adjust(hsl, attribute, percent): hsl = list(hsl) if (attribute > 0): hsl[attribute] = _clamp((hsl[attribute] + percent)) else: hsl[attribute] += percent return hsl
null
null
null
Internal adjust function
pcsd
def adjust hsl attribute percent hsl = list hsl if attribute > 0 hsl[attribute] = clamp hsl[attribute] + percent else hsl[attribute] += percent return hsl
5037
def _adjust(hsl, attribute, percent): hsl = list(hsl) if (attribute > 0): hsl[attribute] = _clamp((hsl[attribute] + percent)) else: hsl[attribute] += percent return hsl
Internal adjust function
internal adjust function
Question: What does this function do? Code: def _adjust(hsl, attribute, percent): hsl = list(hsl) if (attribute > 0): hsl[attribute] = _clamp((hsl[attribute] + percent)) else: hsl[attribute] += percent return hsl
null
null
null
What does this function do?
def _check_diff(cat_name, base_path): po_path = ('%(path)s/en/LC_MESSAGES/django%(ext)s.po' % {'path': base_path, 'ext': ('js' if cat_name.endswith('-js') else '')}) p = Popen(("git diff -U0 %s | egrep '^[-+]msgid' | wc -l" % po_path), stdout=PIPE, stderr=PIPE, shell=True) (output, errors) = p.communicate() num_cha...
null
null
null
Output the approximate number of changed/added strings in the en catalog.
pcsd
def check diff cat name base path po path = '% path s/en/LC MESSAGES/django% ext s po' % {'path' base path 'ext' 'js' if cat name endswith '-js' else '' } p = Popen "git diff -U0 %s | egrep '^[-+]msgid' | wc -l" % po path stdout=PIPE stderr=PIPE shell=True output errors = p communicate num changes = int output strip pr...
5042
def _check_diff(cat_name, base_path): po_path = ('%(path)s/en/LC_MESSAGES/django%(ext)s.po' % {'path': base_path, 'ext': ('js' if cat_name.endswith('-js') else '')}) p = Popen(("git diff -U0 %s | egrep '^[-+]msgid' | wc -l" % po_path), stdout=PIPE, stderr=PIPE, shell=True) (output, errors) = p.communicate() num_cha...
Output the approximate number of changed/added strings in the en catalog.
output the approximate number of changed / added strings in the en catalog .
Question: What does this function do? Code: def _check_diff(cat_name, base_path): po_path = ('%(path)s/en/LC_MESSAGES/django%(ext)s.po' % {'path': base_path, 'ext': ('js' if cat_name.endswith('-js') else '')}) p = Popen(("git diff -U0 %s | egrep '^[-+]msgid' | wc -l" % po_path), stdout=PIPE, stderr=PIPE, shell=Tru...
null
null
null
What does this function do?
def __virtual__(): if (__grains__['os'] == 'Windows'): return __virtualname__ return False
null
null
null
Only work on Windows
pcsd
def virtual if grains ['os'] == 'Windows' return virtualname return False
5044
def __virtual__(): if (__grains__['os'] == 'Windows'): return __virtualname__ return False
Only work on Windows
only work on windows
Question: What does this function do? Code: def __virtual__(): if (__grains__['os'] == 'Windows'): return __virtualname__ return False
null
null
null
What does this function do?
def has_ipython(version='3.0'): version = str(version) try: import IPython except Exception: return (False, 'IPython library not found') else: if (LooseVersion(IPython.__version__) >= LooseVersion(version)): return (True, 'IPython present') else: message = ('current IPython version: (%s) is older than...
null
null
null
function that checks the presence of IPython
pcsd
def has ipython version='3 0' version = str version try import I Python except Exception return False 'I Python library not found' else if Loose Version I Python version >= Loose Version version return True 'I Python present' else message = 'current I Python version %s is older than expected version %s ' % I Python ver...
5049
def has_ipython(version='3.0'): version = str(version) try: import IPython except Exception: return (False, 'IPython library not found') else: if (LooseVersion(IPython.__version__) >= LooseVersion(version)): return (True, 'IPython present') else: message = ('current IPython version: (%s) is older than...
function that checks the presence of IPython
function that checks the presence of ipython
Question: What does this function do? Code: def has_ipython(version='3.0'): version = str(version) try: import IPython except Exception: return (False, 'IPython library not found') else: if (LooseVersion(IPython.__version__) >= LooseVersion(version)): return (True, 'IPython present') else: message ...
null
null
null
What does this function do?
def main(argv=None): from AnyQt.QtWidgets import QApplication if (argv is None): argv = sys.argv argv = list(argv) app = QApplication(argv) if (len(argv) > 1): filename = argv[1] else: filename = 'iris' data = Table(filename) class_var = data.domain.class_var if (class_var is None): return 1 elif clas...
null
null
null
Show and test the widget
pcsd
def main argv=None from Any Qt Qt Widgets import Q Application if argv is None argv = sys argv argv = list argv app = Q Application argv if len argv > 1 filename = argv[1] else filename = 'iris' data = Table filename class var = data domain class var if class var is None return 1 elif class var is discrete learners = [...
5051
def main(argv=None): from AnyQt.QtWidgets import QApplication if (argv is None): argv = sys.argv argv = list(argv) app = QApplication(argv) if (len(argv) > 1): filename = argv[1] else: filename = 'iris' data = Table(filename) class_var = data.domain.class_var if (class_var is None): return 1 elif clas...
Show and test the widget
show and test the widget
Question: What does this function do? Code: def main(argv=None): from AnyQt.QtWidgets import QApplication if (argv is None): argv = sys.argv argv = list(argv) app = QApplication(argv) if (len(argv) > 1): filename = argv[1] else: filename = 'iris' data = Table(filename) class_var = data.domain.class_var...
null
null
null
What does this function do?
def download_latest_artifacts(account_project): build = get_project_build(account_project) jobs = build['build']['jobs'] print 'Build {0[build][version]}, {1} jobs: {0[build][message]}'.format(build, len(jobs)) for job in jobs: name = job['name'].partition(':')[2].split(',')[0].strip() print ' {0}: {1[status]}...
null
null
null
Download all the artifacts from the latest build.
pcsd
def download latest artifacts account project build = get project build account project jobs = build['build']['jobs'] print 'Build {0[build][version]} {1} jobs {0[build][message]}' format build len jobs for job in jobs name = job['name'] partition ' ' [2] split ' ' [0] strip print ' {0} {1[status]} {1[artifacts Count]}...
5060
def download_latest_artifacts(account_project): build = get_project_build(account_project) jobs = build['build']['jobs'] print 'Build {0[build][version]}, {1} jobs: {0[build][message]}'.format(build, len(jobs)) for job in jobs: name = job['name'].partition(':')[2].split(',')[0].strip() print ' {0}: {1[status]}...
Download all the artifacts from the latest build.
download all the artifacts from the latest build .
Question: What does this function do? Code: def download_latest_artifacts(account_project): build = get_project_build(account_project) jobs = build['build']['jobs'] print 'Build {0[build][version]}, {1} jobs: {0[build][message]}'.format(build, len(jobs)) for job in jobs: name = job['name'].partition(':')[2].sp...
null
null
null
What does this function do?
def application_uri(environ): url = (environ['wsgi.url_scheme'] + '://') from urllib import quote if environ.get('HTTP_HOST'): url += environ['HTTP_HOST'] else: url += environ['SERVER_NAME'] if (environ['wsgi.url_scheme'] == 'https'): if (environ['SERVER_PORT'] != '443'): url += (':' + environ['SERVER_...
null
null
null
Return the application\'s base URI (no PATH_INFO or QUERY_STRING)
pcsd
def application uri environ url = environ['wsgi url scheme'] + ' //' from urllib import quote if environ get 'HTTP HOST' url += environ['HTTP HOST'] else url += environ['SERVER NAME'] if environ['wsgi url scheme'] == 'https' if environ['SERVER PORT'] != '443' url += ' ' + environ['SERVER PORT'] elif environ['SERVER POR...
5062
def application_uri(environ): url = (environ['wsgi.url_scheme'] + '://') from urllib import quote if environ.get('HTTP_HOST'): url += environ['HTTP_HOST'] else: url += environ['SERVER_NAME'] if (environ['wsgi.url_scheme'] == 'https'): if (environ['SERVER_PORT'] != '443'): url += (':' + environ['SERVER_...
Return the application\'s base URI (no PATH_INFO or QUERY_STRING)
return the applications base uri
Question: What does this function do? Code: def application_uri(environ): url = (environ['wsgi.url_scheme'] + '://') from urllib import quote if environ.get('HTTP_HOST'): url += environ['HTTP_HOST'] else: url += environ['SERVER_NAME'] if (environ['wsgi.url_scheme'] == 'https'): if (environ['SERVER_PORT'...
null
null
null
What does this function do?
def _handleLegacyResult(result): if (not isinstance(result, dict)): warnings.warn('The Gerrit status callback uses the old way to communicate results. The outcome might be not what is expected.') (message, verified, reviewed) = result result = makeReviewResult(message, (GERRIT_LABEL_VERIFIED, verified), (GERRIT...
null
null
null
make sure the result is backward compatible
pcsd
def handle Legacy Result result if not isinstance result dict warnings warn 'The Gerrit status callback uses the old way to communicate results The outcome might be not what is expected ' message verified reviewed = result result = make Review Result message GERRIT LABEL VERIFIED verified GERRIT LABEL REVIEWED reviewed...
5063
def _handleLegacyResult(result): if (not isinstance(result, dict)): warnings.warn('The Gerrit status callback uses the old way to communicate results. The outcome might be not what is expected.') (message, verified, reviewed) = result result = makeReviewResult(message, (GERRIT_LABEL_VERIFIED, verified), (GERRIT...
make sure the result is backward compatible
make sure the result is backward compatible
Question: What does this function do? Code: def _handleLegacyResult(result): if (not isinstance(result, dict)): warnings.warn('The Gerrit status callback uses the old way to communicate results. The outcome might be not what is expected.') (message, verified, reviewed) = result result = makeReviewResult(mess...
null
null
null
What does this function do?
def get_list_or_404(klass, **kwargs): obj_list = get_object_list(klass, **kwargs) if (not obj_list): raise NotFoundError(message='Object list is empty') return obj_list
null
null
null
Abstraction over `get_object_list`. Raises 404 error if the `obj_list` is empty.
pcsd
def get list or 404 klass **kwargs obj list = get object list klass **kwargs if not obj list raise Not Found Error message='Object list is empty' return obj list
5064
def get_list_or_404(klass, **kwargs): obj_list = get_object_list(klass, **kwargs) if (not obj_list): raise NotFoundError(message='Object list is empty') return obj_list
Abstraction over `get_object_list`. Raises 404 error if the `obj_list` is empty.
abstraction over get _ object _ list .
Question: What does this function do? Code: def get_list_or_404(klass, **kwargs): obj_list = get_object_list(klass, **kwargs) if (not obj_list): raise NotFoundError(message='Object list is empty') return obj_list
null
null
null
What does this function do?
def sign(message, key): return chopstring(message, key['d'], (key['p'] * key['q']), decrypt_int)
null
null
null
Signs a string \'message\' with the private key \'key\'
pcsd
def sign message key return chopstring message key['d'] key['p'] * key['q'] decrypt int
5066
def sign(message, key): return chopstring(message, key['d'], (key['p'] * key['q']), decrypt_int)
Signs a string \'message\' with the private key \'key\'
signs a string message with the private key key
Question: What does this function do? Code: def sign(message, key): return chopstring(message, key['d'], (key['p'] * key['q']), decrypt_int)
null
null
null
What does this function do?
def _write_fileobject(filename, compress=('zlib', 3)): compressmethod = compress[0] compresslevel = compress[1] if (compressmethod == 'gzip'): return _buffered_write_file(BinaryGzipFile(filename, 'wb', compresslevel=compresslevel)) elif (compressmethod == 'bz2'): return _buffered_write_file(bz2.BZ2File(filename...
null
null
null
Return the right compressor file object in write mode.
pcsd
def write fileobject filename compress= 'zlib' 3 compressmethod = compress[0] compresslevel = compress[1] if compressmethod == 'gzip' return buffered write file Binary Gzip File filename 'wb' compresslevel=compresslevel elif compressmethod == 'bz2' return buffered write file bz2 BZ2File filename 'wb' compresslevel=comp...
5067
def _write_fileobject(filename, compress=('zlib', 3)): compressmethod = compress[0] compresslevel = compress[1] if (compressmethod == 'gzip'): return _buffered_write_file(BinaryGzipFile(filename, 'wb', compresslevel=compresslevel)) elif (compressmethod == 'bz2'): return _buffered_write_file(bz2.BZ2File(filename...
Return the right compressor file object in write mode.
return the right compressor file object in write mode .
Question: What does this function do? Code: def _write_fileobject(filename, compress=('zlib', 3)): compressmethod = compress[0] compresslevel = compress[1] if (compressmethod == 'gzip'): return _buffered_write_file(BinaryGzipFile(filename, 'wb', compresslevel=compresslevel)) elif (compressmethod == 'bz2'): r...
null
null
null
What does this function do?
def __virtual__(): if (__grains__['os'] == 'FreeBSD'): return __virtualname__ return (False, 'The freebsd_sysctl execution module cannot be loaded: only available on FreeBSD systems.')
null
null
null
Only runs on FreeBSD systems
pcsd
def virtual if grains ['os'] == 'Free BSD' return virtualname return False 'The freebsd sysctl execution module cannot be loaded only available on Free BSD systems '
5074
def __virtual__(): if (__grains__['os'] == 'FreeBSD'): return __virtualname__ return (False, 'The freebsd_sysctl execution module cannot be loaded: only available on FreeBSD systems.')
Only runs on FreeBSD systems
only runs on freebsd systems
Question: What does this function do? Code: def __virtual__(): if (__grains__['os'] == 'FreeBSD'): return __virtualname__ return (False, 'The freebsd_sysctl execution module cannot be loaded: only available on FreeBSD systems.')
null
null
null
What does this function do?
def __methods(cls): _dict = {} __methodDict(cls, _dict) return _dict.keys()
null
null
null
helper function for Scrolled Canvas
pcsd
def methods cls dict = {} method Dict cls dict return dict keys
5078
def __methods(cls): _dict = {} __methodDict(cls, _dict) return _dict.keys()
helper function for Scrolled Canvas
helper function for scrolled canvas
Question: What does this function do? Code: def __methods(cls): _dict = {} __methodDict(cls, _dict) return _dict.keys()
null
null
null
What does this function do?
def with_foreground_server_thread(startextra={}): def _deco_wrapper(f): @with_tmpdir @wraps(f) def wrapper(self, tmp, *args, **kwargs): th = None phase = dict() try: startparams = _start_params(tmp, logtarget='INHERITED', **startextra) th = Thread(name='_TestCaseWorker', target=self._testStartFo...
null
null
null
Helper to decorate tests uses foreground server (as thread), started directly in test-cases To be used only in subclasses
pcsd
def with foreground server thread startextra={} def deco wrapper f @with tmpdir @wraps f def wrapper self tmp *args **kwargs th = None phase = dict try startparams = start params tmp logtarget='INHERITED' **startextra th = Thread name=' Test Case Worker' target=self test Start Foreground args= tmp startparams phase th ...
5081
def with_foreground_server_thread(startextra={}): def _deco_wrapper(f): @with_tmpdir @wraps(f) def wrapper(self, tmp, *args, **kwargs): th = None phase = dict() try: startparams = _start_params(tmp, logtarget='INHERITED', **startextra) th = Thread(name='_TestCaseWorker', target=self._testStartFo...
Helper to decorate tests uses foreground server (as thread), started directly in test-cases To be used only in subclasses
helper to decorate tests uses foreground server , started directly in test - cases
Question: What does this function do? Code: def with_foreground_server_thread(startextra={}): def _deco_wrapper(f): @with_tmpdir @wraps(f) def wrapper(self, tmp, *args, **kwargs): th = None phase = dict() try: startparams = _start_params(tmp, logtarget='INHERITED', **startextra) th = Thread(n...
null
null
null
What does this function do?
def render_parallel(children): if (len(children) == 1): return children[0] children_latex = [k.latex for k in children if (k.latex != '||')] latex = '\\|'.join(children_latex) tall = any((k.tall for k in children)) return LatexRendered(latex, tall=tall)
null
null
null
Simply join the child nodes with a double vertical line.
pcsd
def render parallel children if len children == 1 return children[0] children latex = [k latex for k in children if k latex != '||' ] latex = '\\|' join children latex tall = any k tall for k in children return Latex Rendered latex tall=tall
5082
def render_parallel(children): if (len(children) == 1): return children[0] children_latex = [k.latex for k in children if (k.latex != '||')] latex = '\\|'.join(children_latex) tall = any((k.tall for k in children)) return LatexRendered(latex, tall=tall)
Simply join the child nodes with a double vertical line.
simply join the child nodes with a double vertical line .
Question: What does this function do? Code: def render_parallel(children): if (len(children) == 1): return children[0] children_latex = [k.latex for k in children if (k.latex != '||')] latex = '\\|'.join(children_latex) tall = any((k.tall for k in children)) return LatexRendered(latex, tall=tall)
null
null
null
What does this function do?
def system_shutdown(): logging.info('Performing system shutdown') Thread(target=halt).start() while __INITIALIZED__: time.sleep(1.0) if sabnzbd.WIN32: powersup.win_shutdown() elif DARWIN: powersup.osx_shutdown() else: powersup.linux_shutdown()
null
null
null
Shutdown system after halting download and saving bookkeeping
pcsd
def system shutdown logging info 'Performing system shutdown' Thread target=halt start while INITIALIZED time sleep 1 0 if sabnzbd WIN32 powersup win shutdown elif DARWIN powersup osx shutdown else powersup linux shutdown
5084
def system_shutdown(): logging.info('Performing system shutdown') Thread(target=halt).start() while __INITIALIZED__: time.sleep(1.0) if sabnzbd.WIN32: powersup.win_shutdown() elif DARWIN: powersup.osx_shutdown() else: powersup.linux_shutdown()
Shutdown system after halting download and saving bookkeeping
shutdown system after halting download and saving bookkeeping
Question: What does this function do? Code: def system_shutdown(): logging.info('Performing system shutdown') Thread(target=halt).start() while __INITIALIZED__: time.sleep(1.0) if sabnzbd.WIN32: powersup.win_shutdown() elif DARWIN: powersup.osx_shutdown() else: powersup.linux_shutdown()
null
null
null
What does this function do?
def to_language(locale): p = locale.find('_') if (p >= 0): return ((locale[:p].lower() + '-') + locale[(p + 1):].lower()) else: return locale.lower()
null
null
null
Turns a locale name (en_US) into a language name (en-us).
pcsd
def to language locale p = locale find ' ' if p >= 0 return locale[ p] lower + '-' + locale[ p + 1 ] lower else return locale lower
5086
def to_language(locale): p = locale.find('_') if (p >= 0): return ((locale[:p].lower() + '-') + locale[(p + 1):].lower()) else: return locale.lower()
Turns a locale name (en_US) into a language name (en-us).
turns a locale name into a language name .
Question: What does this function do? Code: def to_language(locale): p = locale.find('_') if (p >= 0): return ((locale[:p].lower() + '-') + locale[(p + 1):].lower()) else: return locale.lower()
null
null
null
What does this function do?
def remove_app(app_name, dry_run=False, yes=False): if ((not dry_run) and (not yes)): confirm = raw_input(u'All doctypes (including custom), modules related to this app will be deleted. Are you sure you want to continue (y/n) ? ') if (confirm != u'y'): return from frappe.utils.backups import scheduled_backup ...
null
null
null
Delete app and all linked to the app\'s module with the app.
pcsd
def remove app app name dry run=False yes=False if not dry run and not yes confirm = raw input u'All doctypes including custom modules related to this app will be deleted Are you sure you want to continue y/n ? ' if confirm != u'y' return from frappe utils backups import scheduled backup print u'Backing up ' scheduled ...
5092
def remove_app(app_name, dry_run=False, yes=False): if ((not dry_run) and (not yes)): confirm = raw_input(u'All doctypes (including custom), modules related to this app will be deleted. Are you sure you want to continue (y/n) ? ') if (confirm != u'y'): return from frappe.utils.backups import scheduled_backup ...
Delete app and all linked to the app\'s module with the app.
delete app and all linked to the apps module with the app .
Question: What does this function do? Code: def remove_app(app_name, dry_run=False, yes=False): if ((not dry_run) and (not yes)): confirm = raw_input(u'All doctypes (including custom), modules related to this app will be deleted. Are you sure you want to continue (y/n) ? ') if (confirm != u'y'): return from...
null
null
null
What does this function do?
def _isproperdist(X): X = np.asarray(X) if ((not np.allclose(np.sum(X), 1)) or (not np.all((X >= 0))) or (not np.all((X <= 1)))): return False else: return True
null
null
null
Checks to see if `X` is a proper probability distribution
pcsd
def isproperdist X X = np asarray X if not np allclose np sum X 1 or not np all X >= 0 or not np all X <= 1 return False else return True
5116
def _isproperdist(X): X = np.asarray(X) if ((not np.allclose(np.sum(X), 1)) or (not np.all((X >= 0))) or (not np.all((X <= 1)))): return False else: return True
Checks to see if `X` is a proper probability distribution
checks to see if x is a proper probability distribution
Question: What does this function do? Code: def _isproperdist(X): X = np.asarray(X) if ((not np.allclose(np.sum(X), 1)) or (not np.all((X >= 0))) or (not np.all((X <= 1)))): return False else: return True
null
null
null
What does this function do?
def SetFileProperty(output, source_name, property_name, values, sep): output.write('set_source_files_properties(') output.write(source_name) output.write(' PROPERTIES ') output.write(property_name) output.write(' "') for value in values: output.write(CMakeStringEscape(value)) output.write(sep) output.write('...
null
null
null
Given a set of source file, sets the given property on them.
pcsd
def Set File Property output source name property name values sep output write 'set source files properties ' output write source name output write ' PROPERTIES ' output write property name output write ' "' for value in values output write C Make String Escape value output write sep output write '" '
5127
def SetFileProperty(output, source_name, property_name, values, sep): output.write('set_source_files_properties(') output.write(source_name) output.write(' PROPERTIES ') output.write(property_name) output.write(' "') for value in values: output.write(CMakeStringEscape(value)) output.write(sep) output.write('...
Given a set of source file, sets the given property on them.
given a set of source file , sets the given property on them .
Question: What does this function do? Code: def SetFileProperty(output, source_name, property_name, values, sep): output.write('set_source_files_properties(') output.write(source_name) output.write(' PROPERTIES ') output.write(property_name) output.write(' "') for value in values: output.write(CMakeStringEsc...
null
null
null
What does this function do?
def cell_to_packed_rowcol(cell): (row, col, row_abs, col_abs) = cell_to_rowcol(cell) if (col >= MAX_COL): raise Exception(('Column %s greater than IV in formula' % cell)) if (row >= MAX_ROW): raise Exception(('Row %s greater than %d in formula' % (cell, MAX_ROW))) col |= (int((not row_abs)) << 15) col |= (int(...
null
null
null
pack row and column into the required 4 byte format
pcsd
def cell to packed rowcol cell row col row abs col abs = cell to rowcol cell if col >= MAX COL raise Exception 'Column %s greater than IV in formula' % cell if row >= MAX ROW raise Exception 'Row %s greater than %d in formula' % cell MAX ROW col |= int not row abs << 15 col |= int not col abs << 14 return row col
5132
def cell_to_packed_rowcol(cell): (row, col, row_abs, col_abs) = cell_to_rowcol(cell) if (col >= MAX_COL): raise Exception(('Column %s greater than IV in formula' % cell)) if (row >= MAX_ROW): raise Exception(('Row %s greater than %d in formula' % (cell, MAX_ROW))) col |= (int((not row_abs)) << 15) col |= (int(...
pack row and column into the required 4 byte format
pack row and column into the required 4 byte format
Question: What does this function do? Code: def cell_to_packed_rowcol(cell): (row, col, row_abs, col_abs) = cell_to_rowcol(cell) if (col >= MAX_COL): raise Exception(('Column %s greater than IV in formula' % cell)) if (row >= MAX_ROW): raise Exception(('Row %s greater than %d in formula' % (cell, MAX_ROW))) ...
null
null
null
What does this function do?
def remove_duplicates(errors): passed = defaultdict(list) for error in errors: key = (error.linter, error.number) if (key in DUPLICATES): if (key in passed[error.lnum]): continue passed[error.lnum] = DUPLICATES[key] (yield error)
null
null
null
Filter duplicates from given error\'s list.
pcsd
def remove duplicates errors passed = defaultdict list for error in errors key = error linter error number if key in DUPLICATES if key in passed[error lnum] continue passed[error lnum] = DUPLICATES[key] yield error
5135
def remove_duplicates(errors): passed = defaultdict(list) for error in errors: key = (error.linter, error.number) if (key in DUPLICATES): if (key in passed[error.lnum]): continue passed[error.lnum] = DUPLICATES[key] (yield error)
Filter duplicates from given error\'s list.
filter duplicates from given errors list .
Question: What does this function do? Code: def remove_duplicates(errors): passed = defaultdict(list) for error in errors: key = (error.linter, error.number) if (key in DUPLICATES): if (key in passed[error.lnum]): continue passed[error.lnum] = DUPLICATES[key] (yield error)
null
null
null
What does this function do?
@pytest.mark.django_db def test_boolean_should_not_prevent_rendering_of_other_columns(): class Table(tables.Table, ): boolean = tables.BooleanColumn(yesno=u'waar,onwaar') class Meta: model = Person fields = (u'boolean', u'name') (Occupation.objects.create(name=u'Waar', boolean=True),) (Occupation.objects.c...
null
null
null
Test for issue 360
pcsd
@pytest mark django db def test boolean should not prevent rendering of other columns class Table tables Table boolean = tables Boolean Column yesno=u'waar onwaar' class Meta model = Person fields = u'boolean' u'name' Occupation objects create name=u'Waar' boolean=True Occupation objects create name=u'Onwaar' boolean=F...
5141
@pytest.mark.django_db def test_boolean_should_not_prevent_rendering_of_other_columns(): class Table(tables.Table, ): boolean = tables.BooleanColumn(yesno=u'waar,onwaar') class Meta: model = Person fields = (u'boolean', u'name') (Occupation.objects.create(name=u'Waar', boolean=True),) (Occupation.objects.c...
Test for issue 360
test for issue 360
Question: What does this function do? Code: @pytest.mark.django_db def test_boolean_should_not_prevent_rendering_of_other_columns(): class Table(tables.Table, ): boolean = tables.BooleanColumn(yesno=u'waar,onwaar') class Meta: model = Person fields = (u'boolean', u'name') (Occupation.objects.create(name=...
null
null
null
What does this function do?
def curve(n_turns): phi = np.linspace(0, (2 * np.pi), 2000) return [(np.cos(phi) * (1 + (0.5 * np.cos((n_turns * phi))))), (np.sin(phi) * (1 + (0.5 * np.cos((n_turns * phi))))), (0.5 * np.sin((n_turns * phi)))]
null
null
null
The function creating the x, y, z coordinates needed to plot
pcsd
def curve n turns phi = np linspace 0 2 * np pi 2000 return [ np cos phi * 1 + 0 5 * np cos n turns * phi np sin phi * 1 + 0 5 * np cos n turns * phi 0 5 * np sin n turns * phi ]
5148
def curve(n_turns): phi = np.linspace(0, (2 * np.pi), 2000) return [(np.cos(phi) * (1 + (0.5 * np.cos((n_turns * phi))))), (np.sin(phi) * (1 + (0.5 * np.cos((n_turns * phi))))), (0.5 * np.sin((n_turns * phi)))]
The function creating the x, y, z coordinates needed to plot
the function creating the x , y , z coordinates needed to plot
Question: What does this function do? Code: def curve(n_turns): phi = np.linspace(0, (2 * np.pi), 2000) return [(np.cos(phi) * (1 + (0.5 * np.cos((n_turns * phi))))), (np.sin(phi) * (1 + (0.5 * np.cos((n_turns * phi))))), (0.5 * np.sin((n_turns * phi)))]
null
null
null
What does this function do?
@image_comparison(baseline_images=[u'EventCollection_plot__add_positions']) def test__EventCollection__add_positions(): (splt, coll, props) = generate_EventCollection_plot() new_positions = np.hstack([props[u'positions'], props[u'extra_positions'][0]]) coll.add_positions(props[u'extra_positions'][0]) np.testing.ass...
null
null
null
check to make sure add_positions works properly
pcsd
@image comparison baseline images=[u'Event Collection plot add positions'] def test Event Collection add positions splt coll props = generate Event Collection plot new positions = np hstack [props[u'positions'] props[u'extra positions'][0]] coll add positions props[u'extra positions'][0] np testing assert array equal n...
5149
@image_comparison(baseline_images=[u'EventCollection_plot__add_positions']) def test__EventCollection__add_positions(): (splt, coll, props) = generate_EventCollection_plot() new_positions = np.hstack([props[u'positions'], props[u'extra_positions'][0]]) coll.add_positions(props[u'extra_positions'][0]) np.testing.ass...
check to make sure add_positions works properly
check to make sure add _ positions works properly
Question: What does this function do? Code: @image_comparison(baseline_images=[u'EventCollection_plot__add_positions']) def test__EventCollection__add_positions(): (splt, coll, props) = generate_EventCollection_plot() new_positions = np.hstack([props[u'positions'], props[u'extra_positions'][0]]) coll.add_position...
null
null
null
What does this function do?
def parse_header(line): parts = _parseparam((';' + line)) key = parts.next() pdict = {} for p in parts: i = p.find('=') if (i >= 0): name = p[:i].strip().lower() value = p[(i + 1):].strip() if ((len(value) >= 2) and (value[0] == value[(-1)] == '"')): value = value[1:(-1)] value = value.replace(...
null
null
null
Parse a Content-type like header. Return the main content-type and a dictionary of options.
pcsd
def parse header line parts = parseparam ' ' + line key = parts next pdict = {} for p in parts i = p find '=' if i >= 0 name = p[ i] strip lower value = p[ i + 1 ] strip if len value >= 2 and value[0] == value[ -1 ] == '"' value = value[1 -1 ] value = value replace '\\\\' '\\' replace '\\"' '"' pdict[name] = value retu...
5152
def parse_header(line): parts = _parseparam((';' + line)) key = parts.next() pdict = {} for p in parts: i = p.find('=') if (i >= 0): name = p[:i].strip().lower() value = p[(i + 1):].strip() if ((len(value) >= 2) and (value[0] == value[(-1)] == '"')): value = value[1:(-1)] value = value.replace(...
Parse a Content-type like header. Return the main content-type and a dictionary of options.
parse a content - type like header .
Question: What does this function do? Code: def parse_header(line): parts = _parseparam((';' + line)) key = parts.next() pdict = {} for p in parts: i = p.find('=') if (i >= 0): name = p[:i].strip().lower() value = p[(i + 1):].strip() if ((len(value) >= 2) and (value[0] == value[(-1)] == '"')): v...
null
null
null
What does this function do?
@sopel.module.require_privmsg @sopel.module.require_admin @sopel.module.commands(u'join') @sopel.module.priority(u'low') @sopel.module.example(u'.join #example or .join #example key') def join(bot, trigger): (channel, key) = (trigger.group(3), trigger.group(4)) if (not channel): return elif (not key): bot.join(c...
null
null
null
Join the specified channel. This is an admin-only command.
pcsd
@sopel module require privmsg @sopel module require admin @sopel module commands u'join' @sopel module priority u'low' @sopel module example u' join #example or join #example key' def join bot trigger channel key = trigger group 3 trigger group 4 if not channel return elif not key bot join channel else bot join channel...
5156
@sopel.module.require_privmsg @sopel.module.require_admin @sopel.module.commands(u'join') @sopel.module.priority(u'low') @sopel.module.example(u'.join #example or .join #example key') def join(bot, trigger): (channel, key) = (trigger.group(3), trigger.group(4)) if (not channel): return elif (not key): bot.join(c...
Join the specified channel. This is an admin-only command.
join the specified channel .
Question: What does this function do? Code: @sopel.module.require_privmsg @sopel.module.require_admin @sopel.module.commands(u'join') @sopel.module.priority(u'low') @sopel.module.example(u'.join #example or .join #example key') def join(bot, trigger): (channel, key) = (trigger.group(3), trigger.group(4)) if (not c...
null
null
null
What does this function do?
def addSymmetricXPath(outputs, path, x): vertexes = [] loops = [getSymmetricXLoop(path, vertexes, (- x)), getSymmetricXLoop(path, vertexes, x)] outputs.append(getPillarOutput(loops))
null
null
null
Add x path output to outputs.
pcsd
def add Symmetric X Path outputs path x vertexes = [] loops = [get Symmetric X Loop path vertexes - x get Symmetric X Loop path vertexes x ] outputs append get Pillar Output loops
5157
def addSymmetricXPath(outputs, path, x): vertexes = [] loops = [getSymmetricXLoop(path, vertexes, (- x)), getSymmetricXLoop(path, vertexes, x)] outputs.append(getPillarOutput(loops))
Add x path output to outputs.
add x path output to outputs .
Question: What does this function do? Code: def addSymmetricXPath(outputs, path, x): vertexes = [] loops = [getSymmetricXLoop(path, vertexes, (- x)), getSymmetricXLoop(path, vertexes, x)] outputs.append(getPillarOutput(loops))
null
null
null
What does this function do?
def execute_cmd(cmd, from_async=False): for hook in frappe.get_hooks(u'override_whitelisted_methods', {}).get(cmd, []): cmd = hook break try: method = get_attr(cmd) except: frappe.respond_as_web_page(title=u'Invalid Method', html=u'Method not found', indicator_color=u'red', http_status_code=404) return if...
null
null
null
execute a request as python module
pcsd
def execute cmd cmd from async=False for hook in frappe get hooks u'override whitelisted methods' {} get cmd [] cmd = hook break try method = get attr cmd except frappe respond as web page title=u'Invalid Method' html=u'Method not found' indicator color=u'red' http status code=404 return if from async method = method q...
5178
def execute_cmd(cmd, from_async=False): for hook in frappe.get_hooks(u'override_whitelisted_methods', {}).get(cmd, []): cmd = hook break try: method = get_attr(cmd) except: frappe.respond_as_web_page(title=u'Invalid Method', html=u'Method not found', indicator_color=u'red', http_status_code=404) return if...
execute a request as python module
execute a request as python module
Question: What does this function do? Code: def execute_cmd(cmd, from_async=False): for hook in frappe.get_hooks(u'override_whitelisted_methods', {}).get(cmd, []): cmd = hook break try: method = get_attr(cmd) except: frappe.respond_as_web_page(title=u'Invalid Method', html=u'Method not found', indicator_c...
null
null
null
What does this function do?
def dup_gf_factor(f, K): f = dup_convert(f, K, K.dom) (coeff, factors) = gf_factor(f, K.mod, K.dom) for (i, (f, k)) in enumerate(factors): factors[i] = (dup_convert(f, K.dom, K), k) return (K.convert(coeff, K.dom), factors)
null
null
null
Factor univariate polynomials over finite fields.
pcsd
def dup gf factor f K f = dup convert f K K dom coeff factors = gf factor f K mod K dom for i f k in enumerate factors factors[i] = dup convert f K dom K k return K convert coeff K dom factors
5185
def dup_gf_factor(f, K): f = dup_convert(f, K, K.dom) (coeff, factors) = gf_factor(f, K.mod, K.dom) for (i, (f, k)) in enumerate(factors): factors[i] = (dup_convert(f, K.dom, K), k) return (K.convert(coeff, K.dom), factors)
Factor univariate polynomials over finite fields.
factor univariate polynomials over finite fields .
Question: What does this function do? Code: def dup_gf_factor(f, K): f = dup_convert(f, K, K.dom) (coeff, factors) = gf_factor(f, K.mod, K.dom) for (i, (f, k)) in enumerate(factors): factors[i] = (dup_convert(f, K.dom, K), k) return (K.convert(coeff, K.dom), factors)
null
null
null
What does this function do?
def mask_comments(input): search_re = re.compile('(.*?)(#)(.*)') return [search_re.sub(comment_replace, line) for line in input]
null
null
null
Mask the quoted strings so we skip braces inside quoted strings.
pcsd
def mask comments input search re = re compile ' *? # * ' return [search re sub comment replace line for line in input]
5193
def mask_comments(input): search_re = re.compile('(.*?)(#)(.*)') return [search_re.sub(comment_replace, line) for line in input]
Mask the quoted strings so we skip braces inside quoted strings.
mask the quoted strings so we skip braces inside quoted strings .
Question: What does this function do? Code: def mask_comments(input): search_re = re.compile('(.*?)(#)(.*)') return [search_re.sub(comment_replace, line) for line in input]
null
null
null
What does this function do?
def _get_meg_system(info): system = '306m' for ch in info['chs']: if (ch['kind'] == FIFF.FIFFV_MEG_CH): coil_type = (ch['coil_type'] & 65535) if (coil_type == FIFF.FIFFV_COIL_NM_122): system = '122m' break elif ((coil_type // 1000) == 3): system = '306m' break elif ((coil_type == FIFF.FI...
null
null
null
Educated guess for the helmet type based on channels.
pcsd
def get meg system info system = '306m' for ch in info['chs'] if ch['kind'] == FIFF FIFFV MEG CH coil type = ch['coil type'] & 65535 if coil type == FIFF FIFFV COIL NM 122 system = '122m' break elif coil type // 1000 == 3 system = '306m' break elif coil type == FIFF FIFFV COIL MAGNES MAG or coil type == FIFF FIFFV COIL...
5210
def _get_meg_system(info): system = '306m' for ch in info['chs']: if (ch['kind'] == FIFF.FIFFV_MEG_CH): coil_type = (ch['coil_type'] & 65535) if (coil_type == FIFF.FIFFV_COIL_NM_122): system = '122m' break elif ((coil_type // 1000) == 3): system = '306m' break elif ((coil_type == FIFF.FI...
Educated guess for the helmet type based on channels.
educated guess for the helmet type based on channels .
Question: What does this function do? Code: def _get_meg_system(info): system = '306m' for ch in info['chs']: if (ch['kind'] == FIFF.FIFFV_MEG_CH): coil_type = (ch['coil_type'] & 65535) if (coil_type == FIFF.FIFFV_COIL_NM_122): system = '122m' break elif ((coil_type // 1000) == 3): system = ...
null
null
null
What does this function do?
def get_quote_num(num, count, name): if num: num = int(num) if (count == 0): raise Exception('No quotes found for {}.'.format(name)) if (num and (num < 0)): num = (((count + num) + 1) if ((num + count) > (-1)) else (count + 1)) if (num and (num > count)): raise Exception('I only have {} quote{} for {}.'.for...
null
null
null
Returns the quote number to fetch from the DB
pcsd
def get quote num num count name if num num = int num if count == 0 raise Exception 'No quotes found for {} ' format name if num and num < 0 num = count + num + 1 if num + count > -1 else count + 1 if num and num > count raise Exception 'I only have {} quote{} for {} ' format count 's' '' [ count == 1 ] name if num and...
5212
def get_quote_num(num, count, name): if num: num = int(num) if (count == 0): raise Exception('No quotes found for {}.'.format(name)) if (num and (num < 0)): num = (((count + num) + 1) if ((num + count) > (-1)) else (count + 1)) if (num and (num > count)): raise Exception('I only have {} quote{} for {}.'.for...
Returns the quote number to fetch from the DB
returns the quote number to fetch from the db
Question: What does this function do? Code: def get_quote_num(num, count, name): if num: num = int(num) if (count == 0): raise Exception('No quotes found for {}.'.format(name)) if (num and (num < 0)): num = (((count + num) + 1) if ((num + count) > (-1)) else (count + 1)) if (num and (num > count)): raise...
null
null
null
What does this function do?
def sorted_score(scores): score_lst = [(scores[k], k) for k in scores] sort_lst = sorted(score_lst, reverse=True) return [(i[1], i[0]) for i in sort_lst]
null
null
null
count the list for max to min.
pcsd
def sorted score scores score lst = [ scores[k] k for k in scores] sort lst = sorted score lst reverse=True return [ i[1] i[0] for i in sort lst]
5218
def sorted_score(scores): score_lst = [(scores[k], k) for k in scores] sort_lst = sorted(score_lst, reverse=True) return [(i[1], i[0]) for i in sort_lst]
count the list for max to min.
count the list for max to min .
Question: What does this function do? Code: def sorted_score(scores): score_lst = [(scores[k], k) for k in scores] sort_lst = sorted(score_lst, reverse=True) return [(i[1], i[0]) for i in sort_lst]
null
null
null
What does this function do?
def create_vbd(session, vm_ref, vdi_ref, userdevice, vbd_type='disk', read_only=False, bootable=False, osvol=False, empty=False, unpluggable=True): vbd_rec = {} vbd_rec['VM'] = vm_ref if (vdi_ref is None): vdi_ref = 'OpaqueRef:NULL' vbd_rec['VDI'] = vdi_ref vbd_rec['userdevice'] = str(userdevice) vbd_rec['boota...
null
null
null
Create a VBD record and returns its reference.
pcsd
def create vbd session vm ref vdi ref userdevice vbd type='disk' read only=False bootable=False osvol=False empty=False unpluggable=True vbd rec = {} vbd rec['VM'] = vm ref if vdi ref is None vdi ref = 'Opaque Ref NULL' vbd rec['VDI'] = vdi ref vbd rec['userdevice'] = str userdevice vbd rec['bootable'] = bootable vbd r...
5228
def create_vbd(session, vm_ref, vdi_ref, userdevice, vbd_type='disk', read_only=False, bootable=False, osvol=False, empty=False, unpluggable=True): vbd_rec = {} vbd_rec['VM'] = vm_ref if (vdi_ref is None): vdi_ref = 'OpaqueRef:NULL' vbd_rec['VDI'] = vdi_ref vbd_rec['userdevice'] = str(userdevice) vbd_rec['boota...
Create a VBD record and returns its reference.
create a vbd record and returns its reference .
Question: What does this function do? Code: def create_vbd(session, vm_ref, vdi_ref, userdevice, vbd_type='disk', read_only=False, bootable=False, osvol=False, empty=False, unpluggable=True): vbd_rec = {} vbd_rec['VM'] = vm_ref if (vdi_ref is None): vdi_ref = 'OpaqueRef:NULL' vbd_rec['VDI'] = vdi_ref vbd_rec[...
null
null
null
What does this function do?
def _parse_settings_eth(opts, iface_type, enabled, iface): result = {'name': iface} if ('proto' in opts): valid = ['none', 'bootp', 'dhcp'] if (opts['proto'] in valid): result['proto'] = opts['proto'] else: _raise_error_iface(iface, opts['proto'], valid) if ('dns' in opts): result['dns'] = opts['dns'] ...
null
null
null
Filters given options and outputs valid settings for a network interface.
pcsd
def parse settings eth opts iface type enabled iface result = {'name' iface} if 'proto' in opts valid = ['none' 'bootp' 'dhcp'] if opts['proto'] in valid result['proto'] = opts['proto'] else raise error iface iface opts['proto'] valid if 'dns' in opts result['dns'] = opts['dns'] result['peerdns'] = 'yes' if 'mtu' in op...
5232
def _parse_settings_eth(opts, iface_type, enabled, iface): result = {'name': iface} if ('proto' in opts): valid = ['none', 'bootp', 'dhcp'] if (opts['proto'] in valid): result['proto'] = opts['proto'] else: _raise_error_iface(iface, opts['proto'], valid) if ('dns' in opts): result['dns'] = opts['dns'] ...
Filters given options and outputs valid settings for a network interface.
filters given options and outputs valid settings for a network interface .
Question: What does this function do? Code: def _parse_settings_eth(opts, iface_type, enabled, iface): result = {'name': iface} if ('proto' in opts): valid = ['none', 'bootp', 'dhcp'] if (opts['proto'] in valid): result['proto'] = opts['proto'] else: _raise_error_iface(iface, opts['proto'], valid) if ...
null
null
null
What does this function do?
def check_acls_comm_obj(obj, profile): if obj.read_permission_public: return True if (obj.read_permission_reviewer and check_acls(profile, obj, 'reviewer')): return True if (obj.read_permission_senior_reviewer and check_acls(profile, obj, 'senior_reviewer')): return True if (obj.read_permission_mozilla_contac...
null
null
null
Cross-reference ACLs and Note/Thread permissions.
pcsd
def check acls comm obj obj profile if obj read permission public return True if obj read permission reviewer and check acls profile obj 'reviewer' return True if obj read permission senior reviewer and check acls profile obj 'senior reviewer' return True if obj read permission mozilla contact and check acls profile ob...
5233
def check_acls_comm_obj(obj, profile): if obj.read_permission_public: return True if (obj.read_permission_reviewer and check_acls(profile, obj, 'reviewer')): return True if (obj.read_permission_senior_reviewer and check_acls(profile, obj, 'senior_reviewer')): return True if (obj.read_permission_mozilla_contac...
Cross-reference ACLs and Note/Thread permissions.
cross - reference acls and note / thread permissions .
Question: What does this function do? Code: def check_acls_comm_obj(obj, profile): if obj.read_permission_public: return True if (obj.read_permission_reviewer and check_acls(profile, obj, 'reviewer')): return True if (obj.read_permission_senior_reviewer and check_acls(profile, obj, 'senior_reviewer')): retu...
null
null
null
What does this function do?
def locked(): return coin_flip()
null
null
null
Locked or unlocked.
pcsd
def locked return coin flip
5236
def locked(): return coin_flip()
Locked or unlocked.
locked or unlocked .
Question: What does this function do? Code: def locked(): return coin_flip()
null
null
null
What does this function do?
def _eat_items(value, iter_parts, part, end_char, replace_char=''): current = part chunks = [current.replace(replace_char, '')] while True: try: current = six.advance_iterator(iter_parts) except StopIteration: raise ValueError(value) chunks.append(current.replace(replace_char, '')) if current.endswith(...
null
null
null
Eat items from an iterator, optionally replacing characters with a blank and stopping when the end_char has been reached.
pcsd
def eat items value iter parts part end char replace char='' current = part chunks = [current replace replace char '' ] while True try current = six advance iterator iter parts except Stop Iteration raise Value Error value chunks append current replace replace char '' if current endswith end char break return ' ' join ...
5246
def _eat_items(value, iter_parts, part, end_char, replace_char=''): current = part chunks = [current.replace(replace_char, '')] while True: try: current = six.advance_iterator(iter_parts) except StopIteration: raise ValueError(value) chunks.append(current.replace(replace_char, '')) if current.endswith(...
Eat items from an iterator, optionally replacing characters with a blank and stopping when the end_char has been reached.
eat items from an iterator , optionally replacing characters with a blank and stopping when the end _ char has been reached .
Question: What does this function do? Code: def _eat_items(value, iter_parts, part, end_char, replace_char=''): current = part chunks = [current.replace(replace_char, '')] while True: try: current = six.advance_iterator(iter_parts) except StopIteration: raise ValueError(value) chunks.append(current.re...
null
null
null
What does this function do?
def compress_signals(signals): groups = group_by_all(reversed(signals), key=(lambda sig: (sig.link, sig.id))) signals = [] def has_none(signals): return any(((sig.value is None) for sig in signals)) for ((link, id), signals_grouped) in groups: if ((len(signals_grouped) > 1) and has_none(signals_grouped[1:])): ...
null
null
null
Compress a list of signals.
pcsd
def compress signals signals groups = group by all reversed signals key= lambda sig sig link sig id signals = [] def has none signals return any sig value is None for sig in signals for link id signals grouped in groups if len signals grouped > 1 and has none signals grouped[1 ] signals append signals grouped[0] signal...
5248
def compress_signals(signals): groups = group_by_all(reversed(signals), key=(lambda sig: (sig.link, sig.id))) signals = [] def has_none(signals): return any(((sig.value is None) for sig in signals)) for ((link, id), signals_grouped) in groups: if ((len(signals_grouped) > 1) and has_none(signals_grouped[1:])): ...
Compress a list of signals.
compress a list of signals .
Question: What does this function do? Code: def compress_signals(signals): groups = group_by_all(reversed(signals), key=(lambda sig: (sig.link, sig.id))) signals = [] def has_none(signals): return any(((sig.value is None) for sig in signals)) for ((link, id), signals_grouped) in groups: if ((len(signals_grou...
null
null
null
What does this function do?
def _ng86(seq1, seq2, k, codon_table): (S_sites1, N_sites1) = _count_site_NG86(seq1, codon_table=codon_table, k=k) (S_sites2, N_sites2) = _count_site_NG86(seq2, codon_table=codon_table, k=k) S_sites = ((S_sites1 + S_sites2) / 2.0) N_sites = ((N_sites1 + N_sites2) / 2.0) SN = [0, 0] for (i, j) in zip(seq1, seq2): ...
null
null
null
Main function for NG86 method (PRIVATE).
pcsd
def ng86 seq1 seq2 k codon table S sites1 N sites1 = count site NG86 seq1 codon table=codon table k=k S sites2 N sites2 = count site NG86 seq2 codon table=codon table k=k S sites = S sites1 + S sites2 / 2 0 N sites = N sites1 + N sites2 / 2 0 SN = [0 0] for i j in zip seq1 seq2 SN = [ m + n for m n in zip SN count diff...
5252
def _ng86(seq1, seq2, k, codon_table): (S_sites1, N_sites1) = _count_site_NG86(seq1, codon_table=codon_table, k=k) (S_sites2, N_sites2) = _count_site_NG86(seq2, codon_table=codon_table, k=k) S_sites = ((S_sites1 + S_sites2) / 2.0) N_sites = ((N_sites1 + N_sites2) / 2.0) SN = [0, 0] for (i, j) in zip(seq1, seq2): ...
Main function for NG86 method (PRIVATE).
main function for ng86 method .
Question: What does this function do? Code: def _ng86(seq1, seq2, k, codon_table): (S_sites1, N_sites1) = _count_site_NG86(seq1, codon_table=codon_table, k=k) (S_sites2, N_sites2) = _count_site_NG86(seq2, codon_table=codon_table, k=k) S_sites = ((S_sites1 + S_sites2) / 2.0) N_sites = ((N_sites1 + N_sites2) / 2.0...
null
null
null
What does this function do?
def ismount(path): if islink(path): return False try: s1 = os.lstat(path) s2 = os.lstat(join(path, '..')) except os.error: return False dev1 = s1.st_dev dev2 = s2.st_dev if (dev1 != dev2): return True ino1 = s1.st_ino ino2 = s2.st_ino if (ino1 == ino2): return True return False
null
null
null
Test whether a path is a mount point
pcsd
def ismount path if islink path return False try s1 = os lstat path s2 = os lstat join path ' ' except os error return False dev1 = s1 st dev dev2 = s2 st dev if dev1 != dev2 return True ino1 = s1 st ino ino2 = s2 st ino if ino1 == ino2 return True return False
5255
def ismount(path): if islink(path): return False try: s1 = os.lstat(path) s2 = os.lstat(join(path, '..')) except os.error: return False dev1 = s1.st_dev dev2 = s2.st_dev if (dev1 != dev2): return True ino1 = s1.st_ino ino2 = s2.st_ino if (ino1 == ino2): return True return False
Test whether a path is a mount point
test whether a path is a mount point
Question: What does this function do? Code: def ismount(path): if islink(path): return False try: s1 = os.lstat(path) s2 = os.lstat(join(path, '..')) except os.error: return False dev1 = s1.st_dev dev2 = s2.st_dev if (dev1 != dev2): return True ino1 = s1.st_ino ino2 = s2.st_ino if (ino1 == ino2): ...
null
null
null
What does this function do?
def information(title, message=None, details=None, informative_text=None): if (message is None): message = title mbox = QtWidgets.QMessageBox(active_window()) mbox.setStandardButtons(QtWidgets.QMessageBox.Close) mbox.setDefaultButton(QtWidgets.QMessageBox.Close) mbox.setWindowTitle(title) mbox.setWindowModality...
null
null
null
Show information with the provided title and message.
pcsd
def information title message=None details=None informative text=None if message is None message = title mbox = Qt Widgets Q Message Box active window mbox set Standard Buttons Qt Widgets Q Message Box Close mbox set Default Button Qt Widgets Q Message Box Close mbox set Window Title title mbox set Window Modality Qt W...
5260
def information(title, message=None, details=None, informative_text=None): if (message is None): message = title mbox = QtWidgets.QMessageBox(active_window()) mbox.setStandardButtons(QtWidgets.QMessageBox.Close) mbox.setDefaultButton(QtWidgets.QMessageBox.Close) mbox.setWindowTitle(title) mbox.setWindowModality...
Show information with the provided title and message.
show information with the provided title and message .
Question: What does this function do? Code: def information(title, message=None, details=None, informative_text=None): if (message is None): message = title mbox = QtWidgets.QMessageBox(active_window()) mbox.setStandardButtons(QtWidgets.QMessageBox.Close) mbox.setDefaultButton(QtWidgets.QMessageBox.Close) mbo...
null
null
null
What does this function do?
def config_from_file(filename, config=None): if config: try: with open(filename, 'w') as fdesc: fdesc.write(json.dumps(config)) except IOError as error: _LOGGER.error('Saving configuration file failed: %s', error) return False return True elif os.path.isfile(filename): try: with open(filename,...
null
null
null
Small configuration file management function.
pcsd
def config from file filename config=None if config try with open filename 'w' as fdesc fdesc write json dumps config except IO Error as error LOGGER error 'Saving configuration file failed %s' error return False return True elif os path isfile filename try with open filename 'r' as fdesc return json loads fdesc read e...
5269
def config_from_file(filename, config=None): if config: try: with open(filename, 'w') as fdesc: fdesc.write(json.dumps(config)) except IOError as error: _LOGGER.error('Saving configuration file failed: %s', error) return False return True elif os.path.isfile(filename): try: with open(filename,...
Small configuration file management function.
small configuration file management function .
Question: What does this function do? Code: def config_from_file(filename, config=None): if config: try: with open(filename, 'w') as fdesc: fdesc.write(json.dumps(config)) except IOError as error: _LOGGER.error('Saving configuration file failed: %s', error) return False return True elif os.path....
null
null
null
What does this function do?
def getGeometryOutputByArguments(arguments, elementNode): return getGeometryOutput(None, elementNode)
null
null
null
Get vector3 vertexes from attribute dictionary by arguments.
pcsd
def get Geometry Output By Arguments arguments element Node return get Geometry Output None element Node
5271
def getGeometryOutputByArguments(arguments, elementNode): return getGeometryOutput(None, elementNode)
Get vector3 vertexes from attribute dictionary by arguments.
get vector3 vertexes from attribute dictionary by arguments .
Question: What does this function do? Code: def getGeometryOutputByArguments(arguments, elementNode): return getGeometryOutput(None, elementNode)
null
null
null
What does this function do?
def unesc(s, esc_chars): for c in esc_chars: esc_str = (u'\\' + c) s = s.replace(esc_str, c) return s
null
null
null
UnEscape special characters
pcsd
def unesc s esc chars for c in esc chars esc str = u'\\' + c s = s replace esc str c return s
5273
def unesc(s, esc_chars): for c in esc_chars: esc_str = (u'\\' + c) s = s.replace(esc_str, c) return s
UnEscape special characters
unescape special characters
Question: What does this function do? Code: def unesc(s, esc_chars): for c in esc_chars: esc_str = (u'\\' + c) s = s.replace(esc_str, c) return s
null
null
null
What does this function do?
def import_dashboard_config(modules): config = collections.defaultdict(dict) for module in modules: for (key, submodule) in import_submodules(module).items(): if hasattr(submodule, 'DASHBOARD'): dashboard = submodule.DASHBOARD config[dashboard].update(submodule.__dict__) elif (hasattr(submodule, 'PANE...
null
null
null
Imports configuration from all the modules and merges it.
pcsd
def import dashboard config modules config = collections defaultdict dict for module in modules for key submodule in import submodules module items if hasattr submodule 'DASHBOARD' dashboard = submodule DASHBOARD config[dashboard] update submodule dict elif hasattr submodule 'PANEL' or hasattr submodule 'PANEL GROUP' o...
5279
def import_dashboard_config(modules): config = collections.defaultdict(dict) for module in modules: for (key, submodule) in import_submodules(module).items(): if hasattr(submodule, 'DASHBOARD'): dashboard = submodule.DASHBOARD config[dashboard].update(submodule.__dict__) elif (hasattr(submodule, 'PANE...
Imports configuration from all the modules and merges it.
imports configuration from all the modules and merges it .
Question: What does this function do? Code: def import_dashboard_config(modules): config = collections.defaultdict(dict) for module in modules: for (key, submodule) in import_submodules(module).items(): if hasattr(submodule, 'DASHBOARD'): dashboard = submodule.DASHBOARD config[dashboard].update(submod...
null
null
null
What does this function do?
@utils.arg('server', metavar='<server>', help=_('Name or ID of server.')) def do_shelve(cs, args): _find_server(cs, args.server).shelve()
null
null
null
Shelve a server.
pcsd
@utils arg 'server' metavar='<server>' help= 'Name or ID of server ' def do shelve cs args find server cs args server shelve
5295
@utils.arg('server', metavar='<server>', help=_('Name or ID of server.')) def do_shelve(cs, args): _find_server(cs, args.server).shelve()
Shelve a server.
shelve a server .
Question: What does this function do? Code: @utils.arg('server', metavar='<server>', help=_('Name or ID of server.')) def do_shelve(cs, args): _find_server(cs, args.server).shelve()
null
null
null
What does this function do?
def addLoopByComplex(derivation, endMultiplier, loopLists, path, pointComplex, vertexes): loops = loopLists[(-1)] loop = [] loops.append(loop) for point in path: pointMinusBegin = (point - derivation.axisStart) dotVector3 = derivation.axisProjectiveSpace.getDotVector3(pointMinusBegin) dotVector3Complex = dotV...
null
null
null
Add an indexed loop to the vertexes.
pcsd
def add Loop By Complex derivation end Multiplier loop Lists path point Complex vertexes loops = loop Lists[ -1 ] loop = [] loops append loop for point in path point Minus Begin = point - derivation axis Start dot Vector3 = derivation axis Projective Space get Dot Vector3 point Minus Begin dot Vector3Complex = dot Vect...
5298
def addLoopByComplex(derivation, endMultiplier, loopLists, path, pointComplex, vertexes): loops = loopLists[(-1)] loop = [] loops.append(loop) for point in path: pointMinusBegin = (point - derivation.axisStart) dotVector3 = derivation.axisProjectiveSpace.getDotVector3(pointMinusBegin) dotVector3Complex = dotV...
Add an indexed loop to the vertexes.
add an indexed loop to the vertexes .
Question: What does this function do? Code: def addLoopByComplex(derivation, endMultiplier, loopLists, path, pointComplex, vertexes): loops = loopLists[(-1)] loop = [] loops.append(loop) for point in path: pointMinusBegin = (point - derivation.axisStart) dotVector3 = derivation.axisProjectiveSpace.getDotVect...
null
null
null
What does this function do?
def _nt_quote_args(args): for (i, arg) in enumerate(args): if (' ' in arg): args[i] = ('"%s"' % arg) return args
null
null
null
Quote command-line arguments for DOS/Windows conventions. Just wraps every argument which contains blanks in double quotes, and returns a new argument list.
pcsd
def nt quote args args for i arg in enumerate args if ' ' in arg args[i] = '"%s"' % arg return args
5300
def _nt_quote_args(args): for (i, arg) in enumerate(args): if (' ' in arg): args[i] = ('"%s"' % arg) return args
Quote command-line arguments for DOS/Windows conventions. Just wraps every argument which contains blanks in double quotes, and returns a new argument list.
quote command - line arguments for dos / windows conventions .
Question: What does this function do? Code: def _nt_quote_args(args): for (i, arg) in enumerate(args): if (' ' in arg): args[i] = ('"%s"' % arg) return args
null
null
null
What does this function do?
def getNewDerivation(elementNode): return PegDerivation(elementNode)
null
null
null
Get new derivation.
pcsd
def get New Derivation element Node return Peg Derivation element Node
5308
def getNewDerivation(elementNode): return PegDerivation(elementNode)
Get new derivation.
get new derivation .
Question: What does this function do? Code: def getNewDerivation(elementNode): return PegDerivation(elementNode)
null
null
null
What does this function do?
@click.command(u'run-patch') @click.argument(u'module') @pass_context def run_patch(context, module): import frappe.modules.patch_handler for site in context.sites: frappe.init(site=site) try: frappe.connect() frappe.modules.patch_handler.run_single(module, force=context.force) finally: frappe.destroy(...
null
null
null
Run a particular patch
pcsd
@click command u'run-patch' @click argument u'module' @pass context def run patch context module import frappe modules patch handler for site in context sites frappe init site=site try frappe connect frappe modules patch handler run single module force=context force finally frappe destroy
5309
@click.command(u'run-patch') @click.argument(u'module') @pass_context def run_patch(context, module): import frappe.modules.patch_handler for site in context.sites: frappe.init(site=site) try: frappe.connect() frappe.modules.patch_handler.run_single(module, force=context.force) finally: frappe.destroy(...
Run a particular patch
run a particular patch
Question: What does this function do? Code: @click.command(u'run-patch') @click.argument(u'module') @pass_context def run_patch(context, module): import frappe.modules.patch_handler for site in context.sites: frappe.init(site=site) try: frappe.connect() frappe.modules.patch_handler.run_single(module, for...
null
null
null
What does this function do?
@register.filter(is_safe=True) @stringfilter def safe(value): return mark_safe(value)
null
null
null
Marks the value as a string that should not be auto-escaped.
pcsd
@register filter is safe=True @stringfilter def safe value return mark safe value
5315
@register.filter(is_safe=True) @stringfilter def safe(value): return mark_safe(value)
Marks the value as a string that should not be auto-escaped.
marks the value as a string that should not be auto - escaped .
Question: What does this function do? Code: @register.filter(is_safe=True) @stringfilter def safe(value): return mark_safe(value)
null
null
null
What does this function do?
def get_desktop_root(*append): return __get_root('desktop', *append)
null
null
null
Returns the directory for Desktop.
pcsd
def get desktop root *append return get root 'desktop' *append
5319
def get_desktop_root(*append): return __get_root('desktop', *append)
Returns the directory for Desktop.
returns the directory for desktop .
Question: What does this function do? Code: def get_desktop_root(*append): return __get_root('desktop', *append)
null
null
null
What does this function do?
def fake_execute(*cmd_parts, **kwargs): global _fake_execute_repliers process_input = kwargs.get('process_input', None) check_exit_code = kwargs.get('check_exit_code', 0) delay_on_retry = kwargs.get('delay_on_retry', True) attempts = kwargs.get('attempts', 1) run_as_root = kwargs.get('run_as_root', False) cmd_st...
null
null
null
This function stubs out execute. It optionally executes a preconfigured function to return expected data.
pcsd
def fake execute *cmd parts **kwargs global fake execute repliers process input = kwargs get 'process input' None check exit code = kwargs get 'check exit code' 0 delay on retry = kwargs get 'delay on retry' True attempts = kwargs get 'attempts' 1 run as root = kwargs get 'run as root' False cmd str = ' ' join str part...
5332
def fake_execute(*cmd_parts, **kwargs): global _fake_execute_repliers process_input = kwargs.get('process_input', None) check_exit_code = kwargs.get('check_exit_code', 0) delay_on_retry = kwargs.get('delay_on_retry', True) attempts = kwargs.get('attempts', 1) run_as_root = kwargs.get('run_as_root', False) cmd_st...
This function stubs out execute. It optionally executes a preconfigured function to return expected data.
this function stubs out execute .
Question: What does this function do? Code: def fake_execute(*cmd_parts, **kwargs): global _fake_execute_repliers process_input = kwargs.get('process_input', None) check_exit_code = kwargs.get('check_exit_code', 0) delay_on_retry = kwargs.get('delay_on_retry', True) attempts = kwargs.get('attempts', 1) run_as_...
null
null
null
What does this function do?
def normalize_col_name(col_name, used_column_names, is_relation): field_params = {} field_notes = [] new_name = col_name.lower() if (new_name != col_name): field_notes.append(u'Field name made lowercase.') if is_relation: if new_name.endswith(u'_id'): new_name = new_name[:(-3)] else: field_params[u'db_...
null
null
null
Modify the column name to make it Python-compatible as a field name
pcsd
def normalize col name col name used column names is relation field params = {} field notes = [] new name = col name lower if new name != col name field notes append u'Field name made lowercase ' if is relation if new name endswith u' id' new name = new name[ -3 ] else field params[u'db column'] = col name new name num...
5342
def normalize_col_name(col_name, used_column_names, is_relation): field_params = {} field_notes = [] new_name = col_name.lower() if (new_name != col_name): field_notes.append(u'Field name made lowercase.') if is_relation: if new_name.endswith(u'_id'): new_name = new_name[:(-3)] else: field_params[u'db_...
Modify the column name to make it Python-compatible as a field name
modify the column name to make it python - compatible as a field name
Question: What does this function do? Code: def normalize_col_name(col_name, used_column_names, is_relation): field_params = {} field_notes = [] new_name = col_name.lower() if (new_name != col_name): field_notes.append(u'Field name made lowercase.') if is_relation: if new_name.endswith(u'_id'): new_name ...
null
null
null
What does this function do?
def track_sunset(offset=None): def track_sunset_decorator(action): 'Decorator to track sunset events.' event.track_sunset(HASS, functools.partial(action, HASS), offset) return action return track_sunset_decorator
null
null
null
Decorator factory to track sunset events.
pcsd
def track sunset offset=None def track sunset decorator action 'Decorator to track sunset events ' event track sunset HASS functools partial action HASS offset return action return track sunset decorator
5345
def track_sunset(offset=None): def track_sunset_decorator(action): 'Decorator to track sunset events.' event.track_sunset(HASS, functools.partial(action, HASS), offset) return action return track_sunset_decorator
Decorator factory to track sunset events.
decorator factory to track sunset events .
Question: What does this function do? Code: def track_sunset(offset=None): def track_sunset_decorator(action): 'Decorator to track sunset events.' event.track_sunset(HASS, functools.partial(action, HASS), offset) return action return track_sunset_decorator
null
null
null
What does this function do?
@_default_app.route(u'/') def start_page(): if (not _home): abort(404) return redirect(_home)
null
null
null
Redirect user to registered UI home
pcsd
@ default app route u'/' def start page if not home abort 404 return redirect home
5346
@_default_app.route(u'/') def start_page(): if (not _home): abort(404) return redirect(_home)
Redirect user to registered UI home
redirect user to registered ui home
Question: What does this function do? Code: @_default_app.route(u'/') def start_page(): if (not _home): abort(404) return redirect(_home)
null
null
null
What does this function do?
def is_numlike(obj): try: (obj + 1) except: return False else: return True
null
null
null
return true if *obj* looks like a number
pcsd
def is numlike obj try obj + 1 except return False else return True
5347
def is_numlike(obj): try: (obj + 1) except: return False else: return True
return true if *obj* looks like a number
return true if * obj * looks like a number
Question: What does this function do? Code: def is_numlike(obj): try: (obj + 1) except: return False else: return True
null
null
null
What does this function do?
@snippet def topic_exists(client, to_delete): TOPIC_NAME = ('topic_exists-%d' % (_millis(),)) topic = client.topic(TOPIC_NAME) to_delete.append(topic) assert (not topic.exists()) topic.create() assert topic.exists()
null
null
null
Test existence of a topic.
pcsd
@snippet def topic exists client to delete TOPIC NAME = 'topic exists-%d' % millis topic = client topic TOPIC NAME to delete append topic assert not topic exists topic create assert topic exists
5349
@snippet def topic_exists(client, to_delete): TOPIC_NAME = ('topic_exists-%d' % (_millis(),)) topic = client.topic(TOPIC_NAME) to_delete.append(topic) assert (not topic.exists()) topic.create() assert topic.exists()
Test existence of a topic.
test existence of a topic .
Question: What does this function do? Code: @snippet def topic_exists(client, to_delete): TOPIC_NAME = ('topic_exists-%d' % (_millis(),)) topic = client.topic(TOPIC_NAME) to_delete.append(topic) assert (not topic.exists()) topic.create() assert topic.exists()
null
null
null
What does this function do?
def chain_future(a, b): def copy(future): assert (future is a) if (isinstance(a, TracebackFuture) and isinstance(b, TracebackFuture) and (a.exc_info() is not None)): b.set_exc_info(a.exc_info()) elif (a.exception() is not None): b.set_exception(a.exception()) else: b.set_result(a.result()) a.add_done...
null
null
null
Chain two futures together so that when one completes, so does the other. The result (success or failure) of ``a`` will be copied to ``b``.
pcsd
def chain future a b def copy future assert future is a if isinstance a Traceback Future and isinstance b Traceback Future and a exc info is not None b set exc info a exc info elif a exception is not None b set exception a exception else b set result a result a add done callback copy
5350
def chain_future(a, b): def copy(future): assert (future is a) if (isinstance(a, TracebackFuture) and isinstance(b, TracebackFuture) and (a.exc_info() is not None)): b.set_exc_info(a.exc_info()) elif (a.exception() is not None): b.set_exception(a.exception()) else: b.set_result(a.result()) a.add_done...
Chain two futures together so that when one completes, so does the other. The result (success or failure) of ``a`` will be copied to ``b``.
chain two futures together so that when one completes , so does the other .
Question: What does this function do? Code: def chain_future(a, b): def copy(future): assert (future is a) if (isinstance(a, TracebackFuture) and isinstance(b, TracebackFuture) and (a.exc_info() is not None)): b.set_exc_info(a.exc_info()) elif (a.exception() is not None): b.set_exception(a.exception()) ...
null
null
null
What does this function do?
@register.assignment_tag(takes_context=True) def assignment_tag_without_context_parameter(arg): return 'Expected result'
null
null
null
Expected assignment_tag_without_context_parameter __doc__
pcsd
@register assignment tag takes context=True def assignment tag without context parameter arg return 'Expected result'
5351
@register.assignment_tag(takes_context=True) def assignment_tag_without_context_parameter(arg): return 'Expected result'
Expected assignment_tag_without_context_parameter __doc__
expected assignment _ tag _ without _ context _ parameter _ _ doc _ _
Question: What does this function do? Code: @register.assignment_tag(takes_context=True) def assignment_tag_without_context_parameter(arg): return 'Expected result'
null
null
null
What does this function do?
def update_network_dict(): url = u'http://sickragetv.github.io/network_timezones/network_timezones.txt' try: url_data = sickrage.srCore.srWebSession.get(url).text except Exception: sickrage.srCore.srLogger.warning((u'Updating network timezones failed, this can happen from time to time. URL: %s' % url)) return ...
null
null
null
Update timezone information from SR repositories
pcsd
def update network dict url = u'http //sickragetv github io/network timezones/network timezones txt' try url data = sickrage sr Core sr Web Session get url text except Exception sickrage sr Core sr Logger warning u'Updating network timezones failed this can happen from time to time URL %s' % url return d = {} try for l...
5355
def update_network_dict(): url = u'http://sickragetv.github.io/network_timezones/network_timezones.txt' try: url_data = sickrage.srCore.srWebSession.get(url).text except Exception: sickrage.srCore.srLogger.warning((u'Updating network timezones failed, this can happen from time to time. URL: %s' % url)) return ...
Update timezone information from SR repositories
update timezone information from sr repositories
Question: What does this function do? Code: def update_network_dict(): url = u'http://sickragetv.github.io/network_timezones/network_timezones.txt' try: url_data = sickrage.srCore.srWebSession.get(url).text except Exception: sickrage.srCore.srLogger.warning((u'Updating network timezones failed, this can happe...
null
null
null
What does this function do?
def __virtual__(): if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.')
null
null
null
Only load this module if keystone is installed on this minion.
pcsd
def virtual if HAS KEYSTONE return 'keystone' return False 'keystone execution module cannot be loaded keystoneclient python library not available '
5360
def __virtual__(): if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.')
Only load this module if keystone is installed on this minion.
only load this module if keystone is installed on this minion .
Question: What does this function do? Code: def __virtual__(): if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.')
null
null
null
What does this function do?
def get_bounds(reads, start_pos_index, end_pos_index): max_low = sys.maxint max_high = (- sys.maxint) for read in reads: if (read[start_pos_index] < max_low): max_low = read[start_pos_index] if (read[end_pos_index] > max_high): max_high = read[end_pos_index] return (max_low, max_high)
null
null
null
Returns the minimum and maximum position for a set of reads.
pcsd
def get bounds reads start pos index end pos index max low = sys maxint max high = - sys maxint for read in reads if read[start pos index] < max low max low = read[start pos index] if read[end pos index] > max high max high = read[end pos index] return max low max high
5361
def get_bounds(reads, start_pos_index, end_pos_index): max_low = sys.maxint max_high = (- sys.maxint) for read in reads: if (read[start_pos_index] < max_low): max_low = read[start_pos_index] if (read[end_pos_index] > max_high): max_high = read[end_pos_index] return (max_low, max_high)
Returns the minimum and maximum position for a set of reads.
returns the minimum and maximum position for a set of reads .
Question: What does this function do? Code: def get_bounds(reads, start_pos_index, end_pos_index): max_low = sys.maxint max_high = (- sys.maxint) for read in reads: if (read[start_pos_index] < max_low): max_low = read[start_pos_index] if (read[end_pos_index] > max_high): max_high = read[end_pos_index] ...
null
null
null
What does this function do?
def multireader(*streams): class reader(object, ): def __init__(self, stream): self.stream = stream def __call__(self): self.text = self.stream.readlines() threads = [] readers = [] for stream in streams: curReader = reader(stream) thread = Threading.Thread(Threading.ThreadStart(curReader)) readers....
null
null
null
creates multiple threads to read std err/std out at the same time to avoid blocking
pcsd
def multireader *streams class reader object def init self stream self stream = stream def call self self text = self stream readlines threads = [] readers = [] for stream in streams cur Reader = reader stream thread = Threading Thread Threading Thread Start cur Reader readers append cur Reader threads append thread th...
5363
def multireader(*streams): class reader(object, ): def __init__(self, stream): self.stream = stream def __call__(self): self.text = self.stream.readlines() threads = [] readers = [] for stream in streams: curReader = reader(stream) thread = Threading.Thread(Threading.ThreadStart(curReader)) readers....
creates multiple threads to read std err/std out at the same time to avoid blocking
creates multiple threads to read std err / std out at the same time to avoid blocking
Question: What does this function do? Code: def multireader(*streams): class reader(object, ): def __init__(self, stream): self.stream = stream def __call__(self): self.text = self.stream.readlines() threads = [] readers = [] for stream in streams: curReader = reader(stream) thread = Threading.Thre...
null
null
null
What does this function do?
def _sync(form, saltenv=None): if (saltenv is None): saltenv = _get_top_file_envs() if isinstance(saltenv, six.string_types): saltenv = saltenv.split(',') (ret, touched) = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv) if touched: mod_file = os.path.join(__opts__['cachedir'], 'module_refresh') wit...
null
null
null
Sync the given directory in the given environment
pcsd
def sync form saltenv=None if saltenv is None saltenv = get top file envs if isinstance saltenv six string types saltenv = saltenv split ' ' ret touched = salt utils extmods sync opts form saltenv=saltenv if touched mod file = os path join opts ['cachedir'] 'module refresh' with salt utils fopen mod file 'a+' as ofile ...
5366
def _sync(form, saltenv=None): if (saltenv is None): saltenv = _get_top_file_envs() if isinstance(saltenv, six.string_types): saltenv = saltenv.split(',') (ret, touched) = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv) if touched: mod_file = os.path.join(__opts__['cachedir'], 'module_refresh') wit...
Sync the given directory in the given environment
sync the given directory in the given environment
Question: What does this function do? Code: def _sync(form, saltenv=None): if (saltenv is None): saltenv = _get_top_file_envs() if isinstance(saltenv, six.string_types): saltenv = saltenv.split(',') (ret, touched) = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv) if touched: mod_file = os.path.joi...
null
null
null
What does this function do?
def close(): devices.reset()
null
null
null
Explicitly clears all contexts in the current thread, and destroys all contexts if the current thread is the main thread.
pcsd
def close devices reset
5377
def close(): devices.reset()
Explicitly clears all contexts in the current thread, and destroys all contexts if the current thread is the main thread.
explicitly clears all contexts in the current thread , and destroys all contexts if the current thread is the main thread .
Question: What does this function do? Code: def close(): devices.reset()
null
null
null
What does this function do?
def whiten_individuals_loop(x, transform, group_iter): x_new = [] for g in group_iter(): x_g = x[g] x_new.append(np.dot(transform, x_g)) return np.concatenate(x_new)
null
null
null
apply linear transform for each individual loop version
pcsd
def whiten individuals loop x transform group iter x new = [] for g in group iter x g = x[g] x new append np dot transform x g return np concatenate x new
5381
def whiten_individuals_loop(x, transform, group_iter): x_new = [] for g in group_iter(): x_g = x[g] x_new.append(np.dot(transform, x_g)) return np.concatenate(x_new)
apply linear transform for each individual loop version
apply linear transform for each individual loop version
Question: What does this function do? Code: def whiten_individuals_loop(x, transform, group_iter): x_new = [] for g in group_iter(): x_g = x[g] x_new.append(np.dot(transform, x_g)) return np.concatenate(x_new)
null
null
null
What does this function do?
def compute_chunk(source, target, chunk, chunk_expr, parts): (source_part, target_part) = parts part = source[source_part] result = compute(chunk_expr, {chunk: part}, return_type='native') target[target_part] = result
null
null
null
Pull out a part, compute it, insert it into the target
pcsd
def compute chunk source target chunk chunk expr parts source part target part = parts part = source[source part] result = compute chunk expr {chunk part} return type='native' target[target part] = result
5393
def compute_chunk(source, target, chunk, chunk_expr, parts): (source_part, target_part) = parts part = source[source_part] result = compute(chunk_expr, {chunk: part}, return_type='native') target[target_part] = result
Pull out a part, compute it, insert it into the target
pull out a part , compute it , insert it into the target
Question: What does this function do? Code: def compute_chunk(source, target, chunk, chunk_expr, parts): (source_part, target_part) = parts part = source[source_part] result = compute(chunk_expr, {chunk: part}, return_type='native') target[target_part] = result
null
null
null
What does this function do?
def read_pyfile(filename): with open(filename, 'rb') as pyfile: encoding = tokenize.detect_encoding(pyfile.readline)[0] with open(filename, 'r', encoding=encoding) as pyfile: source = pyfile.read() return source
null
null
null
Read and return the contents of a Python source file (as a string), taking into account the file encoding.
pcsd
def read pyfile filename with open filename 'rb' as pyfile encoding = tokenize detect encoding pyfile readline [0] with open filename 'r' encoding=encoding as pyfile source = pyfile read return source
5394
def read_pyfile(filename): with open(filename, 'rb') as pyfile: encoding = tokenize.detect_encoding(pyfile.readline)[0] with open(filename, 'r', encoding=encoding) as pyfile: source = pyfile.read() return source
Read and return the contents of a Python source file (as a string), taking into account the file encoding.
read and return the contents of a python source file , taking into account the file encoding .
Question: What does this function do? Code: def read_pyfile(filename): with open(filename, 'rb') as pyfile: encoding = tokenize.detect_encoding(pyfile.readline)[0] with open(filename, 'r', encoding=encoding) as pyfile: source = pyfile.read() return source
null
null
null
What does this function do?
def nudge_dataset(X, Y): direction_vectors = [[[0, 1, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [1, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 1], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 1, 0]]] shift = (lambda x, w: convolve(x.reshape((8, 8)), mode='constant', weights=w).ravel()) X = np.concatenate(([X] + [np.apply_along_ax...
null
null
null
This produces a dataset 5 times bigger than the original one, by moving the 8x8 images in X around by 1px to left, right, down, up
pcsd
def nudge dataset X Y direction vectors = [[[0 1 0] [0 0 0] [0 0 0]] [[0 0 0] [1 0 0] [0 0 0]] [[0 0 0] [0 0 1] [0 0 0]] [[0 0 0] [0 0 0] [0 1 0]]] shift = lambda x w convolve x reshape 8 8 mode='constant' weights=w ravel X = np concatenate [X] + [np apply along axis shift 1 X vector for vector in direction vectors] Y ...
5396
def nudge_dataset(X, Y): direction_vectors = [[[0, 1, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [1, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 1], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 1, 0]]] shift = (lambda x, w: convolve(x.reshape((8, 8)), mode='constant', weights=w).ravel()) X = np.concatenate(([X] + [np.apply_along_ax...
This produces a dataset 5 times bigger than the original one, by moving the 8x8 images in X around by 1px to left, right, down, up
this produces a dataset 5 times bigger than the original one , by moving the 8x8 images in x around by 1px to left , right , down , up
Question: What does this function do? Code: def nudge_dataset(X, Y): direction_vectors = [[[0, 1, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [1, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 1], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 1, 0]]] shift = (lambda x, w: convolve(x.reshape((8, 8)), mode='constant', weights=w).ravel()...