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 parse_url(url): (scheme, host, port, user, password, path, query) = _parse_url(url) return dict(transport=scheme, hostname=host, port=port, userid=user, password=password, virtual_host=path, **query)
null
null
null
Parse URL into mapping of components.
pcsd
def parse url url scheme host port user password path query = parse url url return dict transport=scheme hostname=host port=port userid=user password=password virtual host=path **query
2558
def parse_url(url): (scheme, host, port, user, password, path, query) = _parse_url(url) return dict(transport=scheme, hostname=host, port=port, userid=user, password=password, virtual_host=path, **query)
Parse URL into mapping of components.
parse url into mapping of components .
Question: What does this function do? Code: def parse_url(url): (scheme, host, port, user, password, path, query) = _parse_url(url) return dict(transport=scheme, hostname=host, port=port, userid=user, password=password, virtual_host=path, **query)
null
null
null
What does this function do?
@task def send_purchase_receipt(contrib_id, **kw): contrib = Contribution.objects.get(pk=contrib_id) with contrib.user.activate_lang(): addon = contrib.addon version = (addon.current_version or addon.latest_version) subject = _('Receipt for {0}').format(contrib.addon.name) data = {'app_name': addon.name, 'dev...
null
null
null
Sends an email to the purchaser of the app.
pcsd
@task def send purchase receipt contrib id **kw contrib = Contribution objects get pk=contrib id with contrib user activate lang addon = contrib addon version = addon current version or addon latest version subject = 'Receipt for {0}' format contrib addon name data = {'app name' addon name 'developer name' version deve...
2559
@task def send_purchase_receipt(contrib_id, **kw): contrib = Contribution.objects.get(pk=contrib_id) with contrib.user.activate_lang(): addon = contrib.addon version = (addon.current_version or addon.latest_version) subject = _('Receipt for {0}').format(contrib.addon.name) data = {'app_name': addon.name, 'dev...
Sends an email to the purchaser of the app.
sends an email to the purchaser of the app .
Question: What does this function do? Code: @task def send_purchase_receipt(contrib_id, **kw): contrib = Contribution.objects.get(pk=contrib_id) with contrib.user.activate_lang(): addon = contrib.addon version = (addon.current_version or addon.latest_version) subject = _('Receipt for {0}').format(contrib.add...
null
null
null
What does this function do?
def _PERM_OP(a, b, n, m): t = (((a >> n) ^ b) & m) b = (b ^ t) a = (a ^ (t << n)) return (a, b)
null
null
null
Cleverer bit manipulation.
pcsd
def PERM OP a b n m t = a >> n ^ b & m b = b ^ t a = a ^ t << n return a b
2561
def _PERM_OP(a, b, n, m): t = (((a >> n) ^ b) & m) b = (b ^ t) a = (a ^ (t << n)) return (a, b)
Cleverer bit manipulation.
cleverer bit manipulation .
Question: What does this function do? Code: def _PERM_OP(a, b, n, m): t = (((a >> n) ^ b) & m) b = (b ^ t) a = (a ^ (t << n)) return (a, b)
null
null
null
What does this function do?
@pytest.fixture def member(): from django.contrib.auth import get_user_model return get_user_model().objects.get(username='member')
null
null
null
Require a member user.
pcsd
@pytest fixture def member from django contrib auth import get user model return get user model objects get username='member'
2563
@pytest.fixture def member(): from django.contrib.auth import get_user_model return get_user_model().objects.get(username='member')
Require a member user.
require a member user .
Question: What does this function do? Code: @pytest.fixture def member(): from django.contrib.auth import get_user_model return get_user_model().objects.get(username='member')
null
null
null
What does this function do?
@csrf_protect @require_POST def post_comment(request, next=None, using=None): data = request.POST.copy() if request.user.is_authenticated(): if (not data.get('name', '')): data['name'] = (request.user.get_full_name() or request.user.username) if (not data.get('email', '')): data['email'] = request.user.emai...
null
null
null
Post a comment. HTTP POST is required. If ``POST[\'submit\'] == "preview"`` or if there are errors a preview template, ``comments/preview.html``, will be rendered.
pcsd
@csrf protect @require POST def post comment request next=None using=None data = request POST copy if request user is authenticated if not data get 'name' '' data['name'] = request user get full name or request user username if not data get 'email' '' data['email'] = request user email next = data get 'next' next ctype...
2567
@csrf_protect @require_POST def post_comment(request, next=None, using=None): data = request.POST.copy() if request.user.is_authenticated(): if (not data.get('name', '')): data['name'] = (request.user.get_full_name() or request.user.username) if (not data.get('email', '')): data['email'] = request.user.emai...
Post a comment. HTTP POST is required. If ``POST[\'submit\'] == "preview"`` or if there are errors a preview template, ``comments/preview.html``, will be rendered.
post a comment .
Question: What does this function do? Code: @csrf_protect @require_POST def post_comment(request, next=None, using=None): data = request.POST.copy() if request.user.is_authenticated(): if (not data.get('name', '')): data['name'] = (request.user.get_full_name() or request.user.username) if (not data.get('ema...
null
null
null
What does this function do?
def compare_float(expected, actual, relTol=None, absTol=None): if ((relTol is None) and (absTol is None)): raise ValueError(u"You haven't specified a 'relTol' relative tolerance or a 'absTol' absolute tolerance function argument. You must specify one.") msg = u'' if (absTol is not None): absDiff = abs((expected ...
null
null
null
Fail if the floating point values are not close enough, with the given message. You can specify a relative tolerance, absolute tolerance, or both.
pcsd
def compare float expected actual rel Tol=None abs Tol=None if rel Tol is None and abs Tol is None raise Value Error u"You haven't specified a 'rel Tol' relative tolerance or a 'abs Tol' absolute tolerance function argument You must specify one " msg = u'' if abs Tol is not None abs Diff = abs expected - actual if abs ...
2577
def compare_float(expected, actual, relTol=None, absTol=None): if ((relTol is None) and (absTol is None)): raise ValueError(u"You haven't specified a 'relTol' relative tolerance or a 'absTol' absolute tolerance function argument. You must specify one.") msg = u'' if (absTol is not None): absDiff = abs((expected ...
Fail if the floating point values are not close enough, with the given message. You can specify a relative tolerance, absolute tolerance, or both.
fail if the floating point values are not close enough , with the given message .
Question: What does this function do? Code: def compare_float(expected, actual, relTol=None, absTol=None): if ((relTol is None) and (absTol is None)): raise ValueError(u"You haven't specified a 'relTol' relative tolerance or a 'absTol' absolute tolerance function argument. You must specify one.") msg = u'' if (...
null
null
null
What does this function do?
def post_begin(): for fn in post_configure: fn(options, file_config) global util, fixtures, engines, exclusions, assertions, warnings, profiling, config, testing from sqlalchemy import testing from sqlalchemy.testing import fixtures, engines, exclusions, assertions, warnings, profiling, config from sqlalchemy im...
null
null
null
things to set up later, once we know coverage is running.
pcsd
def post begin for fn in post configure fn options file config global util fixtures engines exclusions assertions warnings profiling config testing from sqlalchemy import testing from sqlalchemy testing import fixtures engines exclusions assertions warnings profiling config from sqlalchemy import util
2578
def post_begin(): for fn in post_configure: fn(options, file_config) global util, fixtures, engines, exclusions, assertions, warnings, profiling, config, testing from sqlalchemy import testing from sqlalchemy.testing import fixtures, engines, exclusions, assertions, warnings, profiling, config from sqlalchemy im...
things to set up later, once we know coverage is running.
things to set up later , once we know coverage is running .
Question: What does this function do? Code: def post_begin(): for fn in post_configure: fn(options, file_config) global util, fixtures, engines, exclusions, assertions, warnings, profiling, config, testing from sqlalchemy import testing from sqlalchemy.testing import fixtures, engines, exclusions, assertions, ...
null
null
null
What does this function do?
def enable_trace(): global app_or_default app_or_default = _app_or_default_trace
null
null
null
Enable tracing of app instances.
pcsd
def enable trace global app or default app or default = app or default trace
2579
def enable_trace(): global app_or_default app_or_default = _app_or_default_trace
Enable tracing of app instances.
enable tracing of app instances .
Question: What does this function do? Code: def enable_trace(): global app_or_default app_or_default = _app_or_default_trace
null
null
null
What does this function do?
@require_POST @login_required def reply(request, forum_slug, thread_id): forum = get_object_or_404(Forum, slug=forum_slug) user = request.user if (not forum.allows_posting_by(user)): if forum.allows_viewing_by(user): raise PermissionDenied else: raise Http404 form = ReplyForm(request.POST) post_preview =...
null
null
null
Reply to a thread.
pcsd
@require POST @login required def reply request forum slug thread id forum = get object or 404 Forum slug=forum slug user = request user if not forum allows posting by user if forum allows viewing by user raise Permission Denied else raise Http404 form = Reply Form request POST post preview = None if form is valid thre...
2581
@require_POST @login_required def reply(request, forum_slug, thread_id): forum = get_object_or_404(Forum, slug=forum_slug) user = request.user if (not forum.allows_posting_by(user)): if forum.allows_viewing_by(user): raise PermissionDenied else: raise Http404 form = ReplyForm(request.POST) post_preview =...
Reply to a thread.
reply to a thread .
Question: What does this function do? Code: @require_POST @login_required def reply(request, forum_slug, thread_id): forum = get_object_or_404(Forum, slug=forum_slug) user = request.user if (not forum.allows_posting_by(user)): if forum.allows_viewing_by(user): raise PermissionDenied else: raise Http404 ...
null
null
null
What does this function do?
def cast(x, f, default=None): if ((f is str) and isinstance(x, unicode)): return decode_utf8(x) if ((f is bool) and (x in ('1', 'True', 'true'))): return True if ((f is bool) and (x in ('0', 'False', 'false'))): return False if (f is int): f = (lambda x: int(round(float(x)))) try: return f(x) except: ...
null
null
null
Returns f(x) or default.
pcsd
def cast x f default=None if f is str and isinstance x unicode return decode utf8 x if f is bool and x in '1' 'True' 'true' return True if f is bool and x in '0' 'False' 'false' return False if f is int f = lambda x int round float x try return f x except return default
2582
def cast(x, f, default=None): if ((f is str) and isinstance(x, unicode)): return decode_utf8(x) if ((f is bool) and (x in ('1', 'True', 'true'))): return True if ((f is bool) and (x in ('0', 'False', 'false'))): return False if (f is int): f = (lambda x: int(round(float(x)))) try: return f(x) except: ...
Returns f(x) or default.
returns f ( x ) or default .
Question: What does this function do? Code: def cast(x, f, default=None): if ((f is str) and isinstance(x, unicode)): return decode_utf8(x) if ((f is bool) and (x in ('1', 'True', 'true'))): return True if ((f is bool) and (x in ('0', 'False', 'false'))): return False if (f is int): f = (lambda x: int(ro...
null
null
null
What does this function do?
def getClippedLoopPath(clip, loopPath): if (clip <= 0.0): return loopPath loopPathLength = getPathLength(loopPath) clip = min(clip, (0.3 * loopPathLength)) lastLength = 0.0 pointIndex = 0 totalLength = 0.0 while ((totalLength < clip) and (pointIndex < (len(loopPath) - 1))): firstPoint = loopPath[pointIndex] ...
null
null
null
Get a clipped loop path.
pcsd
def get Clipped Loop Path clip loop Path if clip <= 0 0 return loop Path loop Path Length = get Path Length loop Path clip = min clip 0 3 * loop Path Length last Length = 0 0 point Index = 0 total Length = 0 0 while total Length < clip and point Index < len loop Path - 1 first Point = loop Path[point Index] second Poin...
2585
def getClippedLoopPath(clip, loopPath): if (clip <= 0.0): return loopPath loopPathLength = getPathLength(loopPath) clip = min(clip, (0.3 * loopPathLength)) lastLength = 0.0 pointIndex = 0 totalLength = 0.0 while ((totalLength < clip) and (pointIndex < (len(loopPath) - 1))): firstPoint = loopPath[pointIndex] ...
Get a clipped loop path.
get a clipped loop path .
Question: What does this function do? Code: def getClippedLoopPath(clip, loopPath): if (clip <= 0.0): return loopPath loopPathLength = getPathLength(loopPath) clip = min(clip, (0.3 * loopPathLength)) lastLength = 0.0 pointIndex = 0 totalLength = 0.0 while ((totalLength < clip) and (pointIndex < (len(loopPat...
null
null
null
What does this function do?
def new_plugin_wizard(directory=None): if (directory is None): print 'This wizard will create a new plugin for you in the current directory.' directory = os.getcwd() else: print ("This wizard will create a new plugin for you in '%s'." % directory) if (os.path.exists(directory) and (not os.path.isdir(directory)...
null
null
null
Start the wizard to create a new plugin in the current working directory.
pcsd
def new plugin wizard directory=None if directory is None print 'This wizard will create a new plugin for you in the current directory ' directory = os getcwd else print "This wizard will create a new plugin for you in '%s' " % directory if os path exists directory and not os path isdir directory print "Error The path ...
2597
def new_plugin_wizard(directory=None): if (directory is None): print 'This wizard will create a new plugin for you in the current directory.' directory = os.getcwd() else: print ("This wizard will create a new plugin for you in '%s'." % directory) if (os.path.exists(directory) and (not os.path.isdir(directory)...
Start the wizard to create a new plugin in the current working directory.
start the wizard to create a new plugin in the current working directory .
Question: What does this function do? Code: def new_plugin_wizard(directory=None): if (directory is None): print 'This wizard will create a new plugin for you in the current directory.' directory = os.getcwd() else: print ("This wizard will create a new plugin for you in '%s'." % directory) if (os.path.exis...
null
null
null
What does this function do?
def formatter(): output = s3_rest_controller() return output
null
null
null
RESTful CRUD controller
pcsd
def formatter output = s3 rest controller return output
2601
def formatter(): output = s3_rest_controller() return output
RESTful CRUD controller
restful crud controller
Question: What does this function do? Code: def formatter(): output = s3_rest_controller() return output
null
null
null
What does this function do?
def reload_library(): global library available[:] = library = update_user_library(_base_library)
null
null
null
Reload style library.
pcsd
def reload library global library available[ ] = library = update user library base library
2602
def reload_library(): global library available[:] = library = update_user_library(_base_library)
Reload style library.
reload style library .
Question: What does this function do? Code: def reload_library(): global library available[:] = library = update_user_library(_base_library)
null
null
null
What does this function do?
def new_figure_manager(num, *args, **kwargs): FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) canvas = FigureCanvasTemplate(thisFig) manager = FigureManagerTemplate(canvas, num) return manager
null
null
null
Create a new figure manager instance
pcsd
def new figure manager num *args **kwargs Figure Class = kwargs pop 'Figure Class' Figure this Fig = Figure Class *args **kwargs canvas = Figure Canvas Template this Fig manager = Figure Manager Template canvas num return manager
2606
def new_figure_manager(num, *args, **kwargs): FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) canvas = FigureCanvasTemplate(thisFig) manager = FigureManagerTemplate(canvas, num) return manager
Create a new figure manager instance
create a new figure manager instance
Question: What does this function do? Code: def new_figure_manager(num, *args, **kwargs): FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) canvas = FigureCanvasTemplate(thisFig) manager = FigureManagerTemplate(canvas, num) return manager
null
null
null
What does this function do?
def set_dirty(): thread_ident = thread.get_ident() if dirty.has_key(thread_ident): dirty[thread_ident] = True else: raise TransactionManagementError("This code isn't under transaction management")
null
null
null
Sets a dirty flag for the current thread and code streak. This can be used to decide in a managed block of code to decide whether there are open changes waiting for commit.
pcsd
def set dirty thread ident = thread get ident if dirty has key thread ident dirty[thread ident] = True else raise Transaction Management Error "This code isn't under transaction management"
2607
def set_dirty(): thread_ident = thread.get_ident() if dirty.has_key(thread_ident): dirty[thread_ident] = True else: raise TransactionManagementError("This code isn't under transaction management")
Sets a dirty flag for the current thread and code streak. This can be used to decide in a managed block of code to decide whether there are open changes waiting for commit.
sets a dirty flag for the current thread and code streak .
Question: What does this function do? Code: def set_dirty(): thread_ident = thread.get_ident() if dirty.has_key(thread_ident): dirty[thread_ident] = True else: raise TransactionManagementError("This code isn't under transaction management")
null
null
null
What does this function do?
def _goBooleanProxy(expression): initTechnique(kb.technique) if conf.dnsDomain: query = agent.prefixQuery(kb.injection.data[kb.technique].vector) query = agent.suffixQuery(query) payload = agent.payload(newValue=query) output = _goDns(payload, expression) if (output is not None): return output vector = ...
null
null
null
Retrieve the output of a boolean based SQL query
pcsd
def go Boolean Proxy expression init Technique kb technique if conf dns Domain query = agent prefix Query kb injection data[kb technique] vector query = agent suffix Query query payload = agent payload new Value=query output = go Dns payload expression if output is not None return output vector = kb injection data[kb t...
2615
def _goBooleanProxy(expression): initTechnique(kb.technique) if conf.dnsDomain: query = agent.prefixQuery(kb.injection.data[kb.technique].vector) query = agent.suffixQuery(query) payload = agent.payload(newValue=query) output = _goDns(payload, expression) if (output is not None): return output vector = ...
Retrieve the output of a boolean based SQL query
retrieve the output of a boolean based sql query
Question: What does this function do? Code: def _goBooleanProxy(expression): initTechnique(kb.technique) if conf.dnsDomain: query = agent.prefixQuery(kb.injection.data[kb.technique].vector) query = agent.suffixQuery(query) payload = agent.payload(newValue=query) output = _goDns(payload, expression) if (o...
null
null
null
What does this function do?
def simple_moving_average(iterable, k=10): a = (iterable if isinstance(iterable, list) else list(iterable)) for m in xrange(len(a)): i = (m - k) j = ((m + k) + 1) w = a[max(0, i):j] (yield (float(sum(w)) / (len(w) or 1)))
null
null
null
Returns an iterator over the simple moving average of the given list of values.
pcsd
def simple moving average iterable k=10 a = iterable if isinstance iterable list else list iterable for m in xrange len a i = m - k j = m + k + 1 w = a[max 0 i j] yield float sum w / len w or 1
2616
def simple_moving_average(iterable, k=10): a = (iterable if isinstance(iterable, list) else list(iterable)) for m in xrange(len(a)): i = (m - k) j = ((m + k) + 1) w = a[max(0, i):j] (yield (float(sum(w)) / (len(w) or 1)))
Returns an iterator over the simple moving average of the given list of values.
returns an iterator over the simple moving average of the given list of values .
Question: What does this function do? Code: def simple_moving_average(iterable, k=10): a = (iterable if isinstance(iterable, list) else list(iterable)) for m in xrange(len(a)): i = (m - k) j = ((m + k) + 1) w = a[max(0, i):j] (yield (float(sum(w)) / (len(w) or 1)))
null
null
null
What does this function do?
def _compile_func(body): body = u'def {0}():\n {1}'.format(FUNC_NAME, body.replace('\n', '\n ')) code = compile(body, 'inline', 'exec') env = {} eval(code, env) return env[FUNC_NAME]
null
null
null
Given Python code for a function body, return a compiled callable that invokes that code.
pcsd
def compile func body body = u'def {0} {1}' format FUNC NAME body replace ' ' ' ' code = compile body 'inline' 'exec' env = {} eval code env return env[FUNC NAME]
2628
def _compile_func(body): body = u'def {0}():\n {1}'.format(FUNC_NAME, body.replace('\n', '\n ')) code = compile(body, 'inline', 'exec') env = {} eval(code, env) return env[FUNC_NAME]
Given Python code for a function body, return a compiled callable that invokes that code.
given python code for a function body , return a compiled callable that invokes that code .
Question: What does this function do? Code: def _compile_func(body): body = u'def {0}():\n {1}'.format(FUNC_NAME, body.replace('\n', '\n ')) code = compile(body, 'inline', 'exec') env = {} eval(code, env) return env[FUNC_NAME]
null
null
null
What does this function do?
def destroy(name, conn=None, call=None): if (call == 'function'): raise SaltCloudSystemExit('The destroy action must be called with -d, --destroy, -a or --action.') __utils__['cloud.fire_event']('event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_di...
null
null
null
Delete a single VM
pcsd
def destroy name conn=None call=None if call == 'function' raise Salt Cloud System Exit 'The destroy action must be called with -d --destroy -a or --action ' utils ['cloud fire event'] 'event' 'destroying instance' 'salt/cloud/{0}/destroying' format name args={'name' name} sock dir= opts ['sock dir'] transport= opts ['...
2631
def destroy(name, conn=None, call=None): if (call == 'function'): raise SaltCloudSystemExit('The destroy action must be called with -d, --destroy, -a or --action.') __utils__['cloud.fire_event']('event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_di...
Delete a single VM
delete a single vm
Question: What does this function do? Code: def destroy(name, conn=None, call=None): if (call == 'function'): raise SaltCloudSystemExit('The destroy action must be called with -d, --destroy, -a or --action.') __utils__['cloud.fire_event']('event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), ...
null
null
null
What does this function do?
def get_user_profile(user): try: listeners = get_memcached(get_key('listeners')) return listeners[user]['profile'] except: return user
null
null
null
return user profile
pcsd
def get user profile user try listeners = get memcached get key 'listeners' return listeners[user]['profile'] except return user
2635
def get_user_profile(user): try: listeners = get_memcached(get_key('listeners')) return listeners[user]['profile'] except: return user
return user profile
return user profile
Question: What does this function do? Code: def get_user_profile(user): try: listeners = get_memcached(get_key('listeners')) return listeners[user]['profile'] except: return user
null
null
null
What does this function do?
def asquare(cdfvals, axis=0): ndim = len(cdfvals.shape) nobs = cdfvals.shape[axis] slice_reverse = ([slice(None)] * ndim) islice = ([None] * ndim) islice[axis] = slice(None) slice_reverse[axis] = slice(None, None, (-1)) asqu = ((- ((((2.0 * np.arange(1.0, (nobs + 1))[islice]) - 1) * (np.log(cdfvals) + np.log((1 ...
null
null
null
vectorized Anderson Darling A^2, Stephens 1974
pcsd
def asquare cdfvals axis=0 ndim = len cdfvals shape nobs = cdfvals shape[axis] slice reverse = [slice None ] * ndim islice = [None] * ndim islice[axis] = slice None slice reverse[axis] = slice None None -1 asqu = - 2 0 * np arange 1 0 nobs + 1 [islice] - 1 * np log cdfvals + np log 1 - cdfvals[slice reverse] / nobs sum...
2642
def asquare(cdfvals, axis=0): ndim = len(cdfvals.shape) nobs = cdfvals.shape[axis] slice_reverse = ([slice(None)] * ndim) islice = ([None] * ndim) islice[axis] = slice(None) slice_reverse[axis] = slice(None, None, (-1)) asqu = ((- ((((2.0 * np.arange(1.0, (nobs + 1))[islice]) - 1) * (np.log(cdfvals) + np.log((1 ...
vectorized Anderson Darling A^2, Stephens 1974
vectorized anderson darling a ^ 2 , stephens 1974
Question: What does this function do? Code: def asquare(cdfvals, axis=0): ndim = len(cdfvals.shape) nobs = cdfvals.shape[axis] slice_reverse = ([slice(None)] * ndim) islice = ([None] * ndim) islice[axis] = slice(None) slice_reverse[axis] = slice(None, None, (-1)) asqu = ((- ((((2.0 * np.arange(1.0, (nobs + 1)...
null
null
null
What does this function do?
def resource_type_versioned_topic(resource_type, version=None): _validate_resource_type(resource_type) cls = resources.get_resource_cls(resource_type) return (topics.RESOURCE_TOPIC_PATTERN % {'resource_type': resource_type, 'version': (version or cls.VERSION)})
null
null
null
Return the topic for a resource type. If no version is provided, the latest version of the object will be used.
pcsd
def resource type versioned topic resource type version=None validate resource type resource type cls = resources get resource cls resource type return topics RESOURCE TOPIC PATTERN % {'resource type' resource type 'version' version or cls VERSION }
2644
def resource_type_versioned_topic(resource_type, version=None): _validate_resource_type(resource_type) cls = resources.get_resource_cls(resource_type) return (topics.RESOURCE_TOPIC_PATTERN % {'resource_type': resource_type, 'version': (version or cls.VERSION)})
Return the topic for a resource type. If no version is provided, the latest version of the object will be used.
return the topic for a resource type .
Question: What does this function do? Code: def resource_type_versioned_topic(resource_type, version=None): _validate_resource_type(resource_type) cls = resources.get_resource_cls(resource_type) return (topics.RESOURCE_TOPIC_PATTERN % {'resource_type': resource_type, 'version': (version or cls.VERSION)})
null
null
null
What does this function do?
@contextfunction def object_tree_path(context, object, skipself=False): response_format = 'html' if ('response_format' in context): response_format = context['response_format'] path = object.get_tree_path(skipself) return Markup(render_to_string('core/tags/object_tree_path', {'path': path, 'skipself': skipself}, ...
null
null
null
Object tree path
pcsd
@contextfunction def object tree path context object skipself=False response format = 'html' if 'response format' in context response format = context['response format'] path = object get tree path skipself return Markup render to string 'core/tags/object tree path' {'path' path 'skipself' skipself} response format=res...
2645
@contextfunction def object_tree_path(context, object, skipself=False): response_format = 'html' if ('response_format' in context): response_format = context['response_format'] path = object.get_tree_path(skipself) return Markup(render_to_string('core/tags/object_tree_path', {'path': path, 'skipself': skipself}, ...
Object tree path
object tree path
Question: What does this function do? Code: @contextfunction def object_tree_path(context, object, skipself=False): response_format = 'html' if ('response_format' in context): response_format = context['response_format'] path = object.get_tree_path(skipself) return Markup(render_to_string('core/tags/object_tre...
null
null
null
What does this function do?
def write_model_metadata_bundle(path, metadata, replace=False): if os.path.exists(path): if (not os.path.isdir(path)): raise CubesError('Target exists and is a file, can not replace') elif (not os.path.exists(os.path.join(path, 'model.json'))): raise CubesError('Target is not a model directory, can not repla...
null
null
null
Writes a model metadata bundle into new directory `target` from `metadata`. Directory should not exist.
pcsd
def write model metadata bundle path metadata replace=False if os path exists path if not os path isdir path raise Cubes Error 'Target exists and is a file can not replace' elif not os path exists os path join path 'model json' raise Cubes Error 'Target is not a model directory can not replace ' if replace shutil rmtre...
2650
def write_model_metadata_bundle(path, metadata, replace=False): if os.path.exists(path): if (not os.path.isdir(path)): raise CubesError('Target exists and is a file, can not replace') elif (not os.path.exists(os.path.join(path, 'model.json'))): raise CubesError('Target is not a model directory, can not repla...
Writes a model metadata bundle into new directory `target` from `metadata`. Directory should not exist.
writes a model metadata bundle into new directory target from metadata .
Question: What does this function do? Code: def write_model_metadata_bundle(path, metadata, replace=False): if os.path.exists(path): if (not os.path.isdir(path)): raise CubesError('Target exists and is a file, can not replace') elif (not os.path.exists(os.path.join(path, 'model.json'))): raise CubesError(...
null
null
null
What does this function do?
def MAMA(ds, count, fastlimit=(-4e+37), slowlimit=(-4e+37)): ret = call_talib_with_ds(ds, count, talib.MAMA, fastlimit, slowlimit) if (ret is None): ret = (None, None) return ret
null
null
null
MESA Adaptive Moving Average
pcsd
def MAMA ds count fastlimit= -4e+37 slowlimit= -4e+37 ret = call talib with ds ds count talib MAMA fastlimit slowlimit if ret is None ret = None None return ret
2658
def MAMA(ds, count, fastlimit=(-4e+37), slowlimit=(-4e+37)): ret = call_talib_with_ds(ds, count, talib.MAMA, fastlimit, slowlimit) if (ret is None): ret = (None, None) return ret
MESA Adaptive Moving Average
mesa adaptive moving average
Question: What does this function do? Code: def MAMA(ds, count, fastlimit=(-4e+37), slowlimit=(-4e+37)): ret = call_talib_with_ds(ds, count, talib.MAMA, fastlimit, slowlimit) if (ret is None): ret = (None, None) return ret
null
null
null
What does this function do?
def complete_year_spans(spans): spans.sort(key=(lambda x: x['from'])) for (x, y) in pairwise(spans): if ('to' not in x): x['to'] = (y['from'] - 1) if (spans and ('to' not in spans[(-1)])): spans[(-1)]['to'] = datetime.now().year
null
null
null
Set the `to` value of spans if empty and sort them chronologically.
pcsd
def complete year spans spans spans sort key= lambda x x['from'] for x y in pairwise spans if 'to' not in x x['to'] = y['from'] - 1 if spans and 'to' not in spans[ -1 ] spans[ -1 ]['to'] = datetime now year
2671
def complete_year_spans(spans): spans.sort(key=(lambda x: x['from'])) for (x, y) in pairwise(spans): if ('to' not in x): x['to'] = (y['from'] - 1) if (spans and ('to' not in spans[(-1)])): spans[(-1)]['to'] = datetime.now().year
Set the `to` value of spans if empty and sort them chronologically.
set the to value of spans if empty and sort them chronologically .
Question: What does this function do? Code: def complete_year_spans(spans): spans.sort(key=(lambda x: x['from'])) for (x, y) in pairwise(spans): if ('to' not in x): x['to'] = (y['from'] - 1) if (spans and ('to' not in spans[(-1)])): spans[(-1)]['to'] = datetime.now().year
null
null
null
What does this function do?
def p_declaration_specifiers_5(t): pass
null
null
null
declaration_specifiers : type_specifier
pcsd
def p declaration specifiers 5 t pass
2678
def p_declaration_specifiers_5(t): pass
declaration_specifiers : type_specifier
declaration _ specifiers : type _ specifier
Question: What does this function do? Code: def p_declaration_specifiers_5(t): pass
null
null
null
What does this function do?
def funcinfo(function): warnings.warn('[v2.5] Use inspect.getargspec instead of twisted.python.reflect.funcinfo', DeprecationWarning, stacklevel=2) code = function.func_code name = function.func_name argc = code.co_argcount argv = code.co_varnames[:argc] defaults = function.func_defaults out = [] out.append(('T...
null
null
null
this is more documentation for myself than useful code.
pcsd
def funcinfo function warnings warn '[v2 5] Use inspect getargspec instead of twisted python reflect funcinfo' Deprecation Warning stacklevel=2 code = function func code name = function func name argc = code co argcount argv = code co varnames[ argc] defaults = function func defaults out = [] out append 'The function %...
2687
def funcinfo(function): warnings.warn('[v2.5] Use inspect.getargspec instead of twisted.python.reflect.funcinfo', DeprecationWarning, stacklevel=2) code = function.func_code name = function.func_name argc = code.co_argcount argv = code.co_varnames[:argc] defaults = function.func_defaults out = [] out.append(('T...
this is more documentation for myself than useful code.
this is more documentation for myself than useful code .
Question: What does this function do? Code: def funcinfo(function): warnings.warn('[v2.5] Use inspect.getargspec instead of twisted.python.reflect.funcinfo', DeprecationWarning, stacklevel=2) code = function.func_code name = function.func_name argc = code.co_argcount argv = code.co_varnames[:argc] defaults = f...
null
null
null
What does this function do?
def emergency_dump_state(state, open_file=open, dump=None, stderr=None): from pprint import pformat from tempfile import mktemp stderr = (sys.stderr if (stderr is None) else stderr) if (dump is None): import pickle dump = pickle.dump persist = mktemp() print(u'EMERGENCY DUMP STATE TO FILE -> {0} <-'.format(pe...
null
null
null
Dump message state to stdout or file.
pcsd
def emergency dump state state open file=open dump=None stderr=None from pprint import pformat from tempfile import mktemp stderr = sys stderr if stderr is None else stderr if dump is None import pickle dump = pickle dump persist = mktemp print u'EMERGENCY DUMP STATE TO FILE -> {0} <-' format persist file=stderr fh = o...
2690
def emergency_dump_state(state, open_file=open, dump=None, stderr=None): from pprint import pformat from tempfile import mktemp stderr = (sys.stderr if (stderr is None) else stderr) if (dump is None): import pickle dump = pickle.dump persist = mktemp() print(u'EMERGENCY DUMP STATE TO FILE -> {0} <-'.format(pe...
Dump message state to stdout or file.
dump message state to stdout or file .
Question: What does this function do? Code: def emergency_dump_state(state, open_file=open, dump=None, stderr=None): from pprint import pformat from tempfile import mktemp stderr = (sys.stderr if (stderr is None) else stderr) if (dump is None): import pickle dump = pickle.dump persist = mktemp() print(u'EM...
null
null
null
What does this function do?
def unrepr(s): if (not s): return s if (sys.version_info < (3, 0)): b = _Builder2() else: b = _Builder3() obj = b.astnode(s) return b.build(obj)
null
null
null
Return a Python object compiled from a string.
pcsd
def unrepr s if not s return s if sys version info < 3 0 b = Builder2 else b = Builder3 obj = b astnode s return b build obj
2697
def unrepr(s): if (not s): return s if (sys.version_info < (3, 0)): b = _Builder2() else: b = _Builder3() obj = b.astnode(s) return b.build(obj)
Return a Python object compiled from a string.
return a python object compiled from a string .
Question: What does this function do? Code: def unrepr(s): if (not s): return s if (sys.version_info < (3, 0)): b = _Builder2() else: b = _Builder3() obj = b.astnode(s) return b.build(obj)
null
null
null
What does this function do?
def resolve_reverse_ipv6(packed_ip, flags=0): waiter = Waiter() core.dns_resolve_reverse_ipv6(packed_ip, flags, waiter.switch_args) (result, _type, ttl, addrs) = waiter.get() if (result != core.DNS_ERR_NONE): raise DNSError(result) return (ttl, addrs)
null
null
null
Lookup a PTR record for a given IPv6 address. To disable searching for this query, set *flags* to ``QUERY_NO_SEARCH``.
pcsd
def resolve reverse ipv6 packed ip flags=0 waiter = Waiter core dns resolve reverse ipv6 packed ip flags waiter switch args result type ttl addrs = waiter get if result != core DNS ERR NONE raise DNS Error result return ttl addrs
2706
def resolve_reverse_ipv6(packed_ip, flags=0): waiter = Waiter() core.dns_resolve_reverse_ipv6(packed_ip, flags, waiter.switch_args) (result, _type, ttl, addrs) = waiter.get() if (result != core.DNS_ERR_NONE): raise DNSError(result) return (ttl, addrs)
Lookup a PTR record for a given IPv6 address. To disable searching for this query, set *flags* to ``QUERY_NO_SEARCH``.
lookup a ptr record for a given ipv6 address .
Question: What does this function do? Code: def resolve_reverse_ipv6(packed_ip, flags=0): waiter = Waiter() core.dns_resolve_reverse_ipv6(packed_ip, flags, waiter.switch_args) (result, _type, ttl, addrs) = waiter.get() if (result != core.DNS_ERR_NONE): raise DNSError(result) return (ttl, addrs)
null
null
null
What does this function do?
def register(mgr): mgr.set_lang_info(lang, silvercity_lexer=RHTMLLexer(), buf_class=RHTMLBuffer, cile_driver_class=RHTMLCILEDriver, is_cpln_lang=True)
null
null
null
Register language support with the Manager.
pcsd
def register mgr mgr set lang info lang silvercity lexer=RHTML Lexer buf class=RHTML Buffer cile driver class=RHTMLCILE Driver is cpln lang=True
2718
def register(mgr): mgr.set_lang_info(lang, silvercity_lexer=RHTMLLexer(), buf_class=RHTMLBuffer, cile_driver_class=RHTMLCILEDriver, is_cpln_lang=True)
Register language support with the Manager.
register language support with the manager .
Question: What does this function do? Code: def register(mgr): mgr.set_lang_info(lang, silvercity_lexer=RHTMLLexer(), buf_class=RHTMLBuffer, cile_driver_class=RHTMLCILEDriver, is_cpln_lang=True)
null
null
null
What does this function do?
def get_unpack_formats(): formats = [(name, info[0], info[3]) for (name, info) in _UNPACK_FORMATS.items()] formats.sort() return formats
null
null
null
Returns a list of supported formats for unpacking. Each element of the returned sequence is a tuple (name, extensions, description)
pcsd
def get unpack formats formats = [ name info[0] info[3] for name info in UNPACK FORMATS items ] formats sort return formats
2721
def get_unpack_formats(): formats = [(name, info[0], info[3]) for (name, info) in _UNPACK_FORMATS.items()] formats.sort() return formats
Returns a list of supported formats for unpacking. Each element of the returned sequence is a tuple (name, extensions, description)
returns a list of supported formats for unpacking .
Question: What does this function do? Code: def get_unpack_formats(): formats = [(name, info[0], info[3]) for (name, info) in _UNPACK_FORMATS.items()] formats.sort() return formats
null
null
null
What does this function do?
def Deserializer(stream_or_string, **options): if isinstance(stream_or_string, basestring): stream = StringIO(stream_or_string) else: stream = stream_or_string try: for obj in PythonDeserializer(yaml.safe_load(stream), **options): (yield obj) except GeneratorExit: raise except Exception as e: raise De...
null
null
null
Deserialize a stream or string of YAML data.
pcsd
def Deserializer stream or string **options if isinstance stream or string basestring stream = String IO stream or string else stream = stream or string try for obj in Python Deserializer yaml safe load stream **options yield obj except Generator Exit raise except Exception as e raise Deserialization Error e
2727
def Deserializer(stream_or_string, **options): if isinstance(stream_or_string, basestring): stream = StringIO(stream_or_string) else: stream = stream_or_string try: for obj in PythonDeserializer(yaml.safe_load(stream), **options): (yield obj) except GeneratorExit: raise except Exception as e: raise De...
Deserialize a stream or string of YAML data.
deserialize a stream or string of yaml data .
Question: What does this function do? Code: def Deserializer(stream_or_string, **options): if isinstance(stream_or_string, basestring): stream = StringIO(stream_or_string) else: stream = stream_or_string try: for obj in PythonDeserializer(yaml.safe_load(stream), **options): (yield obj) except GeneratorE...
null
null
null
What does this function do?
def get_fields(conn, table): if DEBUG: print >>sys.stderr, 'Processing TABLE', table rows = query(conn, '\n SELECT COLUMN_NAME, DATA_TYPE,\n NULLABLE AS IS_NULLABLE,\n CHAR_LENGTH AS CHARACTER_MAXIMUM_LENGTH,\n DATA_PRECISION AS NUMERIC_PRECISION,\n DATA_SCALE AS N...
null
null
null
Retrieve field list for a given table
pcsd
def get fields conn table if DEBUG print >>sys stderr 'Processing TABLE' table rows = query conn ' SELECT COLUMN NAME DATA TYPE NULLABLE AS IS NULLABLE CHAR LENGTH AS CHARACTER MAXIMUM LENGTH DATA PRECISION AS NUMERIC PRECISION DATA SCALE AS NUMERIC SCALE DATA DEFAULT AS COLUMN DEFAULT FROM USER TAB COLUMNS WHERE TABLE...
2731
def get_fields(conn, table): if DEBUG: print >>sys.stderr, 'Processing TABLE', table rows = query(conn, '\n SELECT COLUMN_NAME, DATA_TYPE,\n NULLABLE AS IS_NULLABLE,\n CHAR_LENGTH AS CHARACTER_MAXIMUM_LENGTH,\n DATA_PRECISION AS NUMERIC_PRECISION,\n DATA_SCALE AS N...
Retrieve field list for a given table
retrieve field list for a given table
Question: What does this function do? Code: def get_fields(conn, table): if DEBUG: print >>sys.stderr, 'Processing TABLE', table rows = query(conn, '\n SELECT COLUMN_NAME, DATA_TYPE,\n NULLABLE AS IS_NULLABLE,\n CHAR_LENGTH AS CHARACTER_MAXIMUM_LENGTH,\n DATA_PRECISION AS ...
null
null
null
What does this function do?
def timeconvert(timestr): timestamp = None timetuple = email.utils.parsedate_tz(timestr) if (timetuple is not None): timestamp = email.utils.mktime_tz(timetuple) return timestamp
null
null
null
Convert RFC 2822 defined time string into system timestamp
pcsd
def timeconvert timestr timestamp = None timetuple = email utils parsedate tz timestr if timetuple is not None timestamp = email utils mktime tz timetuple return timestamp
2739
def timeconvert(timestr): timestamp = None timetuple = email.utils.parsedate_tz(timestr) if (timetuple is not None): timestamp = email.utils.mktime_tz(timetuple) return timestamp
Convert RFC 2822 defined time string into system timestamp
convert rfc 2822 defined time string into system timestamp
Question: What does this function do? Code: def timeconvert(timestr): timestamp = None timetuple = email.utils.parsedate_tz(timestr) if (timetuple is not None): timestamp = email.utils.mktime_tz(timetuple) return timestamp
null
null
null
What does this function do?
def threaded_reactor(): global _twisted_thread try: from twisted.internet import reactor except ImportError: return (None, None) if (not _twisted_thread): from twisted.python import threadable from threading import Thread _twisted_thread = Thread(target=(lambda : reactor.run(installSignalHandlers=False)))...
null
null
null
Start the Twisted reactor in a separate thread, if not already done. Returns the reactor. The thread will automatically be destroyed when all the tests are done.
pcsd
def threaded reactor global twisted thread try from twisted internet import reactor except Import Error return None None if not twisted thread from twisted python import threadable from threading import Thread twisted thread = Thread target= lambda reactor run install Signal Handlers=False twisted thread set Daemon Tru...
2752
def threaded_reactor(): global _twisted_thread try: from twisted.internet import reactor except ImportError: return (None, None) if (not _twisted_thread): from twisted.python import threadable from threading import Thread _twisted_thread = Thread(target=(lambda : reactor.run(installSignalHandlers=False)))...
Start the Twisted reactor in a separate thread, if not already done. Returns the reactor. The thread will automatically be destroyed when all the tests are done.
start the twisted reactor in a separate thread , if not already done .
Question: What does this function do? Code: def threaded_reactor(): global _twisted_thread try: from twisted.internet import reactor except ImportError: return (None, None) if (not _twisted_thread): from twisted.python import threadable from threading import Thread _twisted_thread = Thread(target=(lamb...
null
null
null
What does this function do?
@register.inclusion_tag('zinnia/tags/dummy.html', takes_context=True) def get_categories_tree(context, template='zinnia/tags/categories_tree.html'): return {'template': template, 'categories': Category.objects.all().annotate(count_entries=Count('entries')), 'context_category': context.get('category')}
null
null
null
Return the categories as a tree.
pcsd
@register inclusion tag 'zinnia/tags/dummy html' takes context=True def get categories tree context template='zinnia/tags/categories tree html' return {'template' template 'categories' Category objects all annotate count entries=Count 'entries' 'context category' context get 'category' }
2756
@register.inclusion_tag('zinnia/tags/dummy.html', takes_context=True) def get_categories_tree(context, template='zinnia/tags/categories_tree.html'): return {'template': template, 'categories': Category.objects.all().annotate(count_entries=Count('entries')), 'context_category': context.get('category')}
Return the categories as a tree.
return the categories as a tree .
Question: What does this function do? Code: @register.inclusion_tag('zinnia/tags/dummy.html', takes_context=True) def get_categories_tree(context, template='zinnia/tags/categories_tree.html'): return {'template': template, 'categories': Category.objects.all().annotate(count_entries=Count('entries')), 'context_categ...
null
null
null
What does this function do?
def load_le32(buf, pos): end = (pos + 4) if (end > len(buf)): raise BadRarFile('cannot load le32') return (S_LONG.unpack_from(buf, pos)[0], (pos + 4))
null
null
null
Load little-endian 32-bit integer
pcsd
def load le32 buf pos end = pos + 4 if end > len buf raise Bad Rar File 'cannot load le32' return S LONG unpack from buf pos [0] pos + 4
2757
def load_le32(buf, pos): end = (pos + 4) if (end > len(buf)): raise BadRarFile('cannot load le32') return (S_LONG.unpack_from(buf, pos)[0], (pos + 4))
Load little-endian 32-bit integer
load little - endian 32 - bit integer
Question: What does this function do? Code: def load_le32(buf, pos): end = (pos + 4) if (end > len(buf)): raise BadRarFile('cannot load le32') return (S_LONG.unpack_from(buf, pos)[0], (pos + 4))
null
null
null
What does this function do?
def create_ssh_wrapper(): ssh_wrapper = ssh_file(SSH_WRAPPER) with open(ssh_wrapper, u'w') as handle: handle.write(SSH_WRAPPER_TEMPLATE.format(known_hosts=ssh_file(KNOWN_HOSTS), identity=ssh_file(RSA_KEY))) os.chmod(ssh_wrapper, 493)
null
null
null
Creates wrapper for SSH to pass custom known hosts and key.
pcsd
def create ssh wrapper ssh wrapper = ssh file SSH WRAPPER with open ssh wrapper u'w' as handle handle write SSH WRAPPER TEMPLATE format known hosts=ssh file KNOWN HOSTS identity=ssh file RSA KEY os chmod ssh wrapper 493
2759
def create_ssh_wrapper(): ssh_wrapper = ssh_file(SSH_WRAPPER) with open(ssh_wrapper, u'w') as handle: handle.write(SSH_WRAPPER_TEMPLATE.format(known_hosts=ssh_file(KNOWN_HOSTS), identity=ssh_file(RSA_KEY))) os.chmod(ssh_wrapper, 493)
Creates wrapper for SSH to pass custom known hosts and key.
creates wrapper for ssh to pass custom known hosts and key .
Question: What does this function do? Code: def create_ssh_wrapper(): ssh_wrapper = ssh_file(SSH_WRAPPER) with open(ssh_wrapper, u'w') as handle: handle.write(SSH_WRAPPER_TEMPLATE.format(known_hosts=ssh_file(KNOWN_HOSTS), identity=ssh_file(RSA_KEY))) os.chmod(ssh_wrapper, 493)
null
null
null
What does this function do?
def has_required(programs): try: return check_required(programs) except exception.CommandNotFound: return False
null
null
null
Same as check_required but returns False if not all commands exist
pcsd
def has required programs try return check required programs except exception Command Not Found return False
2771
def has_required(programs): try: return check_required(programs) except exception.CommandNotFound: return False
Same as check_required but returns False if not all commands exist
same as check _ required but returns false if not all commands exist
Question: What does this function do? Code: def has_required(programs): try: return check_required(programs) except exception.CommandNotFound: return False
null
null
null
What does this function do?
def _add_metadata(bt, md_key, lines): taxonomy_md = biom_taxonomy_formatter(bt, md_key) if (taxonomy_md is not None): for i in range((len(lines) - 1)): lines[(i + 1)] = ((lines[(i + 1)] + ' DCTB ') + taxonomy_md[i]) return lines else: nls = ([' DCTB '.join(lines[0].split(' DCTB ')[:(-1)])] + lines[1:]) re...
null
null
null
Add metadata to formatted correlation output lines.
pcsd
def add metadata bt md key lines taxonomy md = biom taxonomy formatter bt md key if taxonomy md is not None for i in range len lines - 1 lines[ i + 1 ] = lines[ i + 1 ] + ' DCTB ' + taxonomy md[i] return lines else nls = [' DCTB ' join lines[0] split ' DCTB ' [ -1 ] ] + lines[1 ] return nls
2774
def _add_metadata(bt, md_key, lines): taxonomy_md = biom_taxonomy_formatter(bt, md_key) if (taxonomy_md is not None): for i in range((len(lines) - 1)): lines[(i + 1)] = ((lines[(i + 1)] + ' DCTB ') + taxonomy_md[i]) return lines else: nls = ([' DCTB '.join(lines[0].split(' DCTB ')[:(-1)])] + lines[1:]) re...
Add metadata to formatted correlation output lines.
add metadata to formatted correlation output lines .
Question: What does this function do? Code: def _add_metadata(bt, md_key, lines): taxonomy_md = biom_taxonomy_formatter(bt, md_key) if (taxonomy_md is not None): for i in range((len(lines) - 1)): lines[(i + 1)] = ((lines[(i + 1)] + ' DCTB ') + taxonomy_md[i]) return lines else: nls = ([' DCTB '.join(line...
null
null
null
What does this function do?
def get_component(obj, attr_name): if isinstance(obj, dict): val = obj.get(attr_name) else: val = getattr(obj, attr_name) if is_simple_callable(val): return val() return val
null
null
null
Given an object, and an attribute name, return that attribute on the object.
pcsd
def get component obj attr name if isinstance obj dict val = obj get attr name else val = getattr obj attr name if is simple callable val return val return val
2776
def get_component(obj, attr_name): if isinstance(obj, dict): val = obj.get(attr_name) else: val = getattr(obj, attr_name) if is_simple_callable(val): return val() return val
Given an object, and an attribute name, return that attribute on the object.
given an object , and an attribute name , return that attribute on the object .
Question: What does this function do? Code: def get_component(obj, attr_name): if isinstance(obj, dict): val = obj.get(attr_name) else: val = getattr(obj, attr_name) if is_simple_callable(val): return val() return val
null
null
null
What does this function do?
def _create_playlist(context, name, tracks): uri_schemes = set([urllib.parse.urlparse(t.uri).scheme for t in tracks]) for scheme in uri_schemes: new_playlist = context.core.playlists.create(name, scheme).get() if (new_playlist is None): logger.debug(u"Backend for scheme %s can't create playlists", scheme) c...
null
null
null
Creates new playlist using backend appropriate for the given tracks
pcsd
def create playlist context name tracks uri schemes = set [urllib parse urlparse t uri scheme for t in tracks] for scheme in uri schemes new playlist = context core playlists create name scheme get if new playlist is None logger debug u"Backend for scheme %s can't create playlists" scheme continue new playlist = new pl...
2781
def _create_playlist(context, name, tracks): uri_schemes = set([urllib.parse.urlparse(t.uri).scheme for t in tracks]) for scheme in uri_schemes: new_playlist = context.core.playlists.create(name, scheme).get() if (new_playlist is None): logger.debug(u"Backend for scheme %s can't create playlists", scheme) c...
Creates new playlist using backend appropriate for the given tracks
creates new playlist using backend appropriate for the given tracks
Question: What does this function do? Code: def _create_playlist(context, name, tracks): uri_schemes = set([urllib.parse.urlparse(t.uri).scheme for t in tracks]) for scheme in uri_schemes: new_playlist = context.core.playlists.create(name, scheme).get() if (new_playlist is None): logger.debug(u"Backend for ...
null
null
null
What does this function do?
@pytest.fixture def templates(): from pootle_language.models import Language return Language.objects.get(code='templates')
null
null
null
Require the special Templates language.
pcsd
@pytest fixture def templates from pootle language models import Language return Language objects get code='templates'
2788
@pytest.fixture def templates(): from pootle_language.models import Language return Language.objects.get(code='templates')
Require the special Templates language.
require the special templates language .
Question: What does this function do? Code: @pytest.fixture def templates(): from pootle_language.models import Language return Language.objects.get(code='templates')
null
null
null
What does this function do?
def notify(conf, context, topic, msg, envelope): return rpc_amqp.notify(conf, context, topic, msg, rpc_amqp.get_connection_pool(conf, Connection), envelope)
null
null
null
Sends a notification event on a topic.
pcsd
def notify conf context topic msg envelope return rpc amqp notify conf context topic msg rpc amqp get connection pool conf Connection envelope
2790
def notify(conf, context, topic, msg, envelope): return rpc_amqp.notify(conf, context, topic, msg, rpc_amqp.get_connection_pool(conf, Connection), envelope)
Sends a notification event on a topic.
sends a notification event on a topic .
Question: What does this function do? Code: def notify(conf, context, topic, msg, envelope): return rpc_amqp.notify(conf, context, topic, msg, rpc_amqp.get_connection_pool(conf, Connection), envelope)
null
null
null
What does this function do?
def setLevel(level=0): ILogger.level = level
null
null
null
Set Global Logging Level.
pcsd
def set Level level=0 I Logger level = level
2796
def setLevel(level=0): ILogger.level = level
Set Global Logging Level.
set global logging level .
Question: What does this function do? Code: def setLevel(level=0): ILogger.level = level
null
null
null
What does this function do?
def get_profile_from_user(user): for field in user._meta.get_fields(): try: if hasattr(user, field.name): attribute = getattr(user, field.name) if (get_profile_model() == type(attribute)): return attribute except Exception: logger.exception('Error getting profile attribute from user.') logger.i...
null
null
null
Tries to get the profile according to the class configured on AUTH_PROFILE_MODULE
pcsd
def get profile from user user for field in user meta get fields try if hasattr user field name attribute = getattr user field name if get profile model == type attribute return attribute except Exception logger exception 'Error getting profile attribute from user ' logger info 'Could not find profile attribute ' retur...
2804
def get_profile_from_user(user): for field in user._meta.get_fields(): try: if hasattr(user, field.name): attribute = getattr(user, field.name) if (get_profile_model() == type(attribute)): return attribute except Exception: logger.exception('Error getting profile attribute from user.') logger.i...
Tries to get the profile according to the class configured on AUTH_PROFILE_MODULE
tries to get the profile according to the class configured on auth _ profile _ module
Question: What does this function do? Code: def get_profile_from_user(user): for field in user._meta.get_fields(): try: if hasattr(user, field.name): attribute = getattr(user, field.name) if (get_profile_model() == type(attribute)): return attribute except Exception: logger.exception('Error g...
null
null
null
What does this function do?
def match_paren(parens): stack = Stack() for b in parens: if (b == '('): stack.push(1) elif (not stack.isEmpty()): stack.pop() else: return False return stack.isEmpty()
null
null
null
returns true or false if parenthesis expression passed is matching
pcsd
def match paren parens stack = Stack for b in parens if b == ' ' stack push 1 elif not stack is Empty stack pop else return False return stack is Empty
2807
def match_paren(parens): stack = Stack() for b in parens: if (b == '('): stack.push(1) elif (not stack.isEmpty()): stack.pop() else: return False return stack.isEmpty()
returns true or false if parenthesis expression passed is matching
returns true or false if parenthesis expression passed is matching
Question: What does this function do? Code: def match_paren(parens): stack = Stack() for b in parens: if (b == '('): stack.push(1) elif (not stack.isEmpty()): stack.pop() else: return False return stack.isEmpty()
null
null
null
What does this function do?
def convert_uptime_hours(sys_uptime): return ((int(sys_uptime) / 100.0) / 3600.0)
null
null
null
sys_uptime is in hundredths of seconds returns a float
pcsd
def convert uptime hours sys uptime return int sys uptime / 100 0 / 3600 0
2810
def convert_uptime_hours(sys_uptime): return ((int(sys_uptime) / 100.0) / 3600.0)
sys_uptime is in hundredths of seconds returns a float
sys _ uptime is in hundredths of seconds returns a float
Question: What does this function do? Code: def convert_uptime_hours(sys_uptime): return ((int(sys_uptime) / 100.0) / 3600.0)
null
null
null
What does this function do?
def plot_histograms(ax, prng, nb_samples=10000): params = ((10, 10), (4, 12), (50, 12), (6, 55)) for (a, b) in params: values = prng.beta(a, b, size=nb_samples) ax.hist(values, histtype='stepfilled', bins=30, alpha=0.8, normed=True) ax.annotate('Annotation', xy=(0.25, 4.25), xycoords='data', xytext=(0.9, 0.9), t...
null
null
null
Plot 4 histograms and a text annotation.
pcsd
def plot histograms ax prng nb samples=10000 params = 10 10 4 12 50 12 6 55 for a b in params values = prng beta a b size=nb samples ax hist values histtype='stepfilled' bins=30 alpha=0 8 normed=True ax annotate 'Annotation' xy= 0 25 4 25 xycoords='data' xytext= 0 9 0 9 textcoords='axes fraction' va='top' ha='right' bb...
2826
def plot_histograms(ax, prng, nb_samples=10000): params = ((10, 10), (4, 12), (50, 12), (6, 55)) for (a, b) in params: values = prng.beta(a, b, size=nb_samples) ax.hist(values, histtype='stepfilled', bins=30, alpha=0.8, normed=True) ax.annotate('Annotation', xy=(0.25, 4.25), xycoords='data', xytext=(0.9, 0.9), t...
Plot 4 histograms and a text annotation.
plot 4 histograms and a text annotation .
Question: What does this function do? Code: def plot_histograms(ax, prng, nb_samples=10000): params = ((10, 10), (4, 12), (50, 12), (6, 55)) for (a, b) in params: values = prng.beta(a, b, size=nb_samples) ax.hist(values, histtype='stepfilled', bins=30, alpha=0.8, normed=True) ax.annotate('Annotation', xy=(0.2...
null
null
null
What does this function do?
def nested_view(request): c = Client() c.get('/no_template_view/') return render(request, 'base.html', {'nested': 'yes'})
null
null
null
A view that uses test client to call another view.
pcsd
def nested view request c = Client c get '/no template view/' return render request 'base html' {'nested' 'yes'}
2830
def nested_view(request): c = Client() c.get('/no_template_view/') return render(request, 'base.html', {'nested': 'yes'})
A view that uses test client to call another view.
a view that uses test client to call another view .
Question: What does this function do? Code: def nested_view(request): c = Client() c.get('/no_template_view/') return render(request, 'base.html', {'nested': 'yes'})
null
null
null
What does this function do?
def setup_server(config): web_server = WebServer(bind=config[u'bind'], port=config[u'port'], ssl_certificate=config[u'ssl_certificate'], ssl_private_key=config[u'ssl_private_key']) _default_app.secret_key = get_secret() user = get_user() if ((not user) or (not user.password)): log.warning(u'No password set for we...
null
null
null
Sets up and starts/restarts the web service.
pcsd
def setup server config web server = Web Server bind=config[u'bind'] port=config[u'port'] ssl certificate=config[u'ssl certificate'] ssl private key=config[u'ssl private key'] default app secret key = get secret user = get user if not user or not user password log warning u'No password set for web server create one by ...
2831
def setup_server(config): web_server = WebServer(bind=config[u'bind'], port=config[u'port'], ssl_certificate=config[u'ssl_certificate'], ssl_private_key=config[u'ssl_private_key']) _default_app.secret_key = get_secret() user = get_user() if ((not user) or (not user.password)): log.warning(u'No password set for we...
Sets up and starts/restarts the web service.
sets up and starts / restarts the web service .
Question: What does this function do? Code: def setup_server(config): web_server = WebServer(bind=config[u'bind'], port=config[u'port'], ssl_certificate=config[u'ssl_certificate'], ssl_private_key=config[u'ssl_private_key']) _default_app.secret_key = get_secret() user = get_user() if ((not user) or (not user.pas...
null
null
null
What does this function do?
@pytest.fixture def small_push_dir(tmpdir): contents = ('abcdefghijlmnopqrstuvwxyz\n' * 10000) push_dir = tmpdir.join('push-from').ensure(dir=True) push_dir.join('arbitrary-file').write(contents) push_dir.join('pg_xlog').mksymlinkto('/tmp/wal-e-test-must-not-exist') push_dir.join('holy-smokes').ensure() return pu...
null
null
null
Create a small pg data directory-alike
pcsd
@pytest fixture def small push dir tmpdir contents = 'abcdefghijlmnopqrstuvwxyz ' * 10000 push dir = tmpdir join 'push-from' ensure dir=True push dir join 'arbitrary-file' write contents push dir join 'pg xlog' mksymlinkto '/tmp/wal-e-test-must-not-exist' push dir join 'holy-smokes' ensure return push dir
2835
@pytest.fixture def small_push_dir(tmpdir): contents = ('abcdefghijlmnopqrstuvwxyz\n' * 10000) push_dir = tmpdir.join('push-from').ensure(dir=True) push_dir.join('arbitrary-file').write(contents) push_dir.join('pg_xlog').mksymlinkto('/tmp/wal-e-test-must-not-exist') push_dir.join('holy-smokes').ensure() return pu...
Create a small pg data directory-alike
create a small pg data directory - alike
Question: What does this function do? Code: @pytest.fixture def small_push_dir(tmpdir): contents = ('abcdefghijlmnopqrstuvwxyz\n' * 10000) push_dir = tmpdir.join('push-from').ensure(dir=True) push_dir.join('arbitrary-file').write(contents) push_dir.join('pg_xlog').mksymlinkto('/tmp/wal-e-test-must-not-exist') p...
null
null
null
What does this function do?
@py.test.mark.parametrize('item_name', [item.name for item in six._urllib_request_moved_attributes]) def test_move_items_urllib_request(item_name): if (sys.version_info[:2] >= (2, 6)): assert (item_name in dir(six.moves.urllib.request)) getattr(six.moves.urllib.request, item_name)
null
null
null
Ensure that everything loads correctly.
pcsd
@py test mark parametrize 'item name' [item name for item in six urllib request moved attributes] def test move items urllib request item name if sys version info[ 2] >= 2 6 assert item name in dir six moves urllib request getattr six moves urllib request item name
2843
@py.test.mark.parametrize('item_name', [item.name for item in six._urllib_request_moved_attributes]) def test_move_items_urllib_request(item_name): if (sys.version_info[:2] >= (2, 6)): assert (item_name in dir(six.moves.urllib.request)) getattr(six.moves.urllib.request, item_name)
Ensure that everything loads correctly.
ensure that everything loads correctly .
Question: What does this function do? Code: @py.test.mark.parametrize('item_name', [item.name for item in six._urllib_request_moved_attributes]) def test_move_items_urllib_request(item_name): if (sys.version_info[:2] >= (2, 6)): assert (item_name in dir(six.moves.urllib.request)) getattr(six.moves.urllib.request...
null
null
null
What does this function do?
def mock_render_to_string(template_name, context): return str((template_name, context))
null
null
null
Return a string that encodes template_name and context
pcsd
def mock render to string template name context return str template name context
2853
def mock_render_to_string(template_name, context): return str((template_name, context))
Return a string that encodes template_name and context
return a string that encodes template _ name and context
Question: What does this function do? Code: def mock_render_to_string(template_name, context): return str((template_name, context))
null
null
null
What does this function do?
def dnsUse(payload, expression): start = time.time() retVal = None count = 0 offset = 1 if (conf.dnsDomain and (Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.ORACLE, DBMS.MYSQL, DBMS.PGSQL))): output = hashDBRetrieve(expression, checkConf=True) if ((output and (PARTIAL_VALUE_MARKER in output)) or (kb.dnsTes...
null
null
null
Retrieve the output of a SQL query taking advantage of the DNS resolution mechanism by making request back to attacker\'s machine.
pcsd
def dns Use payload expression start = time time ret Val = None count = 0 offset = 1 if conf dns Domain and Backend get Identified Dbms in DBMS MSSQL DBMS ORACLE DBMS MYSQL DBMS PGSQL output = hash DB Retrieve expression check Conf=True if output and PARTIAL VALUE MARKER in output or kb dns Test is None output = None i...
2859
def dnsUse(payload, expression): start = time.time() retVal = None count = 0 offset = 1 if (conf.dnsDomain and (Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.ORACLE, DBMS.MYSQL, DBMS.PGSQL))): output = hashDBRetrieve(expression, checkConf=True) if ((output and (PARTIAL_VALUE_MARKER in output)) or (kb.dnsTes...
Retrieve the output of a SQL query taking advantage of the DNS resolution mechanism by making request back to attacker\'s machine.
retrieve the output of a sql query taking advantage of the dns resolution mechanism by making request back to attackers machine .
Question: What does this function do? Code: def dnsUse(payload, expression): start = time.time() retVal = None count = 0 offset = 1 if (conf.dnsDomain and (Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.ORACLE, DBMS.MYSQL, DBMS.PGSQL))): output = hashDBRetrieve(expression, checkConf=True) if ((output and ...
null
null
null
What does this function do?
def addToNamePathDictionary(directoryPath, namePathDictionary): pluginFileNames = getPluginFileNamesFromDirectoryPath(directoryPath) for pluginFileName in pluginFileNames: namePathDictionary[pluginFileName.lstrip('_')] = os.path.join(directoryPath, pluginFileName) return getAbsoluteFrozenFolderPath(__file__, 'skei...
null
null
null
Add to the name path dictionary.
pcsd
def add To Name Path Dictionary directory Path name Path Dictionary plugin File Names = get Plugin File Names From Directory Path directory Path for plugin File Name in plugin File Names name Path Dictionary[plugin File Name lstrip ' ' ] = os path join directory Path plugin File Name return get Absolute Frozen Folder P...
2864
def addToNamePathDictionary(directoryPath, namePathDictionary): pluginFileNames = getPluginFileNamesFromDirectoryPath(directoryPath) for pluginFileName in pluginFileNames: namePathDictionary[pluginFileName.lstrip('_')] = os.path.join(directoryPath, pluginFileName) return getAbsoluteFrozenFolderPath(__file__, 'skei...
Add to the name path dictionary.
add to the name path dictionary .
Question: What does this function do? Code: def addToNamePathDictionary(directoryPath, namePathDictionary): pluginFileNames = getPluginFileNamesFromDirectoryPath(directoryPath) for pluginFileName in pluginFileNames: namePathDictionary[pluginFileName.lstrip('_')] = os.path.join(directoryPath, pluginFileName) ret...
null
null
null
What does this function do?
def tostring(element): rv = [] finalText = None def serializeElement(element): if (not hasattr(element, u'tag')): if element.docinfo.internalDTD: if element.docinfo.doctype: dtd_str = element.docinfo.doctype else: dtd_str = (u'<!DOCTYPE %s>' % element.docinfo.root_name) rv.append(dtd_str) ...
null
null
null
Serialize an element and its child nodes to a string
pcsd
def tostring element rv = [] final Text = None def serialize Element element if not hasattr element u'tag' if element docinfo internal DTD if element docinfo doctype dtd str = element docinfo doctype else dtd str = u'<!DOCTYPE %s>' % element docinfo root name rv append dtd str serialize Element element getroot elif ele...
2871
def tostring(element): rv = [] finalText = None def serializeElement(element): if (not hasattr(element, u'tag')): if element.docinfo.internalDTD: if element.docinfo.doctype: dtd_str = element.docinfo.doctype else: dtd_str = (u'<!DOCTYPE %s>' % element.docinfo.root_name) rv.append(dtd_str) ...
Serialize an element and its child nodes to a string
serialize an element and its child nodes to a string
Question: What does this function do? Code: def tostring(element): rv = [] finalText = None def serializeElement(element): if (not hasattr(element, u'tag')): if element.docinfo.internalDTD: if element.docinfo.doctype: dtd_str = element.docinfo.doctype else: dtd_str = (u'<!DOCTYPE %s>' % ele...
null
null
null
What does this function do?
def write(data, path, saltenv='base', index=0): if (saltenv not in __opts__['pillar_roots']): return 'Named environment {0} is not present'.format(saltenv) if (len(__opts__['pillar_roots'][saltenv]) <= index): return 'Specified index {0} in environment {1} is not present'.format(index, saltenv) if os.path.isabs(...
null
null
null
Write the named file, by default the first file found is written, but the index of the file can be specified to write to a lower priority file root
pcsd
def write data path saltenv='base' index=0 if saltenv not in opts ['pillar roots'] return 'Named environment {0} is not present' format saltenv if len opts ['pillar roots'][saltenv] <= index return 'Specified index {0} in environment {1} is not present' format index saltenv if os path isabs path return 'The path passed...
2878
def write(data, path, saltenv='base', index=0): if (saltenv not in __opts__['pillar_roots']): return 'Named environment {0} is not present'.format(saltenv) if (len(__opts__['pillar_roots'][saltenv]) <= index): return 'Specified index {0} in environment {1} is not present'.format(index, saltenv) if os.path.isabs(...
Write the named file, by default the first file found is written, but the index of the file can be specified to write to a lower priority file root
write the named file , by default the first file found is written , but the index of the file can be specified to write to a lower priority file root
Question: What does this function do? Code: def write(data, path, saltenv='base', index=0): if (saltenv not in __opts__['pillar_roots']): return 'Named environment {0} is not present'.format(saltenv) if (len(__opts__['pillar_roots'][saltenv]) <= index): return 'Specified index {0} in environment {1} is not pre...
null
null
null
What does this function do?
def safe_dump_all(documents, stream=None, **kwds): return dump_all(documents, stream, Dumper=SafeDumper, **kwds)
null
null
null
Serialize a sequence of Python objects into a YAML stream. Produce only basic YAML tags. If stream is None, return the produced string instead.
pcsd
def safe dump all documents stream=None **kwds return dump all documents stream Dumper=Safe Dumper **kwds
2880
def safe_dump_all(documents, stream=None, **kwds): return dump_all(documents, stream, Dumper=SafeDumper, **kwds)
Serialize a sequence of Python objects into a YAML stream. Produce only basic YAML tags. If stream is None, return the produced string instead.
serialize a sequence of python objects into a yaml stream .
Question: What does this function do? Code: def safe_dump_all(documents, stream=None, **kwds): return dump_all(documents, stream, Dumper=SafeDumper, **kwds)
null
null
null
What does this function do?
def list_apps(): if ((not request.vars.username) or (not request.vars.password)): raise HTTP(400) client = ServerProxy(('https://%(username)s:%(password)s@%(username)s.pythonanywhere.com/admin/webservices/call/jsonrpc' % request.vars)) regex = re.compile('^\\w+$') local = [f for f in os.listdir(apath(r=request)) ...
null
null
null
Get a list of apps both remote and local
pcsd
def list apps if not request vars username or not request vars password raise HTTP 400 client = Server Proxy 'https //% username s % password s@% username s pythonanywhere com/admin/webservices/call/jsonrpc' % request vars regex = re compile '^\\w+$' local = [f for f in os listdir apath r=request if regex match f ] try...
2896
def list_apps(): if ((not request.vars.username) or (not request.vars.password)): raise HTTP(400) client = ServerProxy(('https://%(username)s:%(password)s@%(username)s.pythonanywhere.com/admin/webservices/call/jsonrpc' % request.vars)) regex = re.compile('^\\w+$') local = [f for f in os.listdir(apath(r=request)) ...
Get a list of apps both remote and local
get a list of apps both remote and local
Question: What does this function do? Code: def list_apps(): if ((not request.vars.username) or (not request.vars.password)): raise HTTP(400) client = ServerProxy(('https://%(username)s:%(password)s@%(username)s.pythonanywhere.com/admin/webservices/call/jsonrpc' % request.vars)) regex = re.compile('^\\w+$') lo...
null
null
null
What does this function do?
def _link_active(kwargs): highlight_actions = kwargs.get('highlight_actions', kwargs.get('action', '')).split() return ((c.controller == kwargs.get('controller')) and (c.action in highlight_actions))
null
null
null
creates classes for the link_to calls
pcsd
def link active kwargs highlight actions = kwargs get 'highlight actions' kwargs get 'action' '' split return c controller == kwargs get 'controller' and c action in highlight actions
2906
def _link_active(kwargs): highlight_actions = kwargs.get('highlight_actions', kwargs.get('action', '')).split() return ((c.controller == kwargs.get('controller')) and (c.action in highlight_actions))
creates classes for the link_to calls
creates classes for the link _ to calls
Question: What does this function do? Code: def _link_active(kwargs): highlight_actions = kwargs.get('highlight_actions', kwargs.get('action', '')).split() return ((c.controller == kwargs.get('controller')) and (c.action in highlight_actions))
null
null
null
What does this function do?
@pytest.fixture(autouse=True) def init_fake_clipboard(quteproc): quteproc.send_cmd(':debug-set-fake-clipboard')
null
null
null
Make sure the fake clipboard will be used.
pcsd
@pytest fixture autouse=True def init fake clipboard quteproc quteproc send cmd ' debug-set-fake-clipboard'
2908
@pytest.fixture(autouse=True) def init_fake_clipboard(quteproc): quteproc.send_cmd(':debug-set-fake-clipboard')
Make sure the fake clipboard will be used.
make sure the fake clipboard will be used .
Question: What does this function do? Code: @pytest.fixture(autouse=True) def init_fake_clipboard(quteproc): quteproc.send_cmd(':debug-set-fake-clipboard')
null
null
null
What does this function do?
def _bgp_dispatcher(payload): cls = conf.raw_layer if (payload is None): cls = _get_cls('BGPHeader', conf.raw_layer) elif ((len(payload) >= _BGP_HEADER_SIZE) and (payload[:16] == _BGP_HEADER_MARKER)): message_type = struct.unpack('!B', payload[18])[0] if (message_type == 4): cls = _get_cls('BGPKeepAlive') ...
null
null
null
Returns the right class for a given BGP message.
pcsd
def bgp dispatcher payload cls = conf raw layer if payload is None cls = get cls 'BGP Header' conf raw layer elif len payload >= BGP HEADER SIZE and payload[ 16] == BGP HEADER MARKER message type = struct unpack '!B' payload[18] [0] if message type == 4 cls = get cls 'BGP Keep Alive' else cls = get cls 'BGP Header' ret...
2909
def _bgp_dispatcher(payload): cls = conf.raw_layer if (payload is None): cls = _get_cls('BGPHeader', conf.raw_layer) elif ((len(payload) >= _BGP_HEADER_SIZE) and (payload[:16] == _BGP_HEADER_MARKER)): message_type = struct.unpack('!B', payload[18])[0] if (message_type == 4): cls = _get_cls('BGPKeepAlive') ...
Returns the right class for a given BGP message.
returns the right class for a given bgp message .
Question: What does this function do? Code: def _bgp_dispatcher(payload): cls = conf.raw_layer if (payload is None): cls = _get_cls('BGPHeader', conf.raw_layer) elif ((len(payload) >= _BGP_HEADER_SIZE) and (payload[:16] == _BGP_HEADER_MARKER)): message_type = struct.unpack('!B', payload[18])[0] if (message_...
null
null
null
What does this function do?
def _dup_rr_trivial_gcd(f, g, K): if (not (f or g)): return ([], [], []) elif (not f): if K.is_nonnegative(dup_LC(g, K)): return (g, [], [K.one]) else: return (dup_neg(g, K), [], [(- K.one)]) elif (not g): if K.is_nonnegative(dup_LC(f, K)): return (f, [K.one], []) else: return (dup_neg(f, K), [...
null
null
null
Handle trivial cases in GCD algorithm over a ring.
pcsd
def dup rr trivial gcd f g K if not f or g return [] [] [] elif not f if K is nonnegative dup LC g K return g [] [K one] else return dup neg g K [] [ - K one ] elif not g if K is nonnegative dup LC f K return f [K one] [] else return dup neg f K [ - K one ] [] return None
2922
def _dup_rr_trivial_gcd(f, g, K): if (not (f or g)): return ([], [], []) elif (not f): if K.is_nonnegative(dup_LC(g, K)): return (g, [], [K.one]) else: return (dup_neg(g, K), [], [(- K.one)]) elif (not g): if K.is_nonnegative(dup_LC(f, K)): return (f, [K.one], []) else: return (dup_neg(f, K), [...
Handle trivial cases in GCD algorithm over a ring.
handle trivial cases in gcd algorithm over a ring .
Question: What does this function do? Code: def _dup_rr_trivial_gcd(f, g, K): if (not (f or g)): return ([], [], []) elif (not f): if K.is_nonnegative(dup_LC(g, K)): return (g, [], [K.one]) else: return (dup_neg(g, K), [], [(- K.one)]) elif (not g): if K.is_nonnegative(dup_LC(f, K)): return (f, [...
null
null
null
What does this function do?
def _get_cols_m2m(cls, k, child, fk_left_col_name, fk_right_col_name, fk_left_deferrable, fk_left_initially, fk_right_deferrable, fk_right_initially, fk_left_ondelete, fk_left_onupdate, fk_right_ondelete, fk_right_onupdate): (col_info, left_col) = _get_col_o2m(cls, fk_left_col_name, ondelete=fk_left_ondelete, onupdate...
null
null
null
Gets the parent and child classes and returns foreign keys to both tables. These columns can be used to create a relation table.
pcsd
def get cols m2m cls k child fk left col name fk right col name fk left deferrable fk left initially fk right deferrable fk right initially fk left ondelete fk left onupdate fk right ondelete fk right onupdate col info left col = get col o2m cls fk left col name ondelete=fk left ondelete onupdate=fk left onupdate defer...
2923
def _get_cols_m2m(cls, k, child, fk_left_col_name, fk_right_col_name, fk_left_deferrable, fk_left_initially, fk_right_deferrable, fk_right_initially, fk_left_ondelete, fk_left_onupdate, fk_right_ondelete, fk_right_onupdate): (col_info, left_col) = _get_col_o2m(cls, fk_left_col_name, ondelete=fk_left_ondelete, onupdate...
Gets the parent and child classes and returns foreign keys to both tables. These columns can be used to create a relation table.
gets the parent and child classes and returns foreign keys to both tables .
Question: What does this function do? Code: def _get_cols_m2m(cls, k, child, fk_left_col_name, fk_right_col_name, fk_left_deferrable, fk_left_initially, fk_right_deferrable, fk_right_initially, fk_left_ondelete, fk_left_onupdate, fk_right_ondelete, fk_right_onupdate): (col_info, left_col) = _get_col_o2m(cls, fk_lef...
null
null
null
What does this function do?
def _calculate_score_for_modules(user_id, course, modules): modules = [m for m in modules] locations = [(BlockUsageLocator(course_key=course.id, block_type=module.location.block_type, block_id=module.location.block_id) if (isinstance(module.location, BlockUsageLocator) and module.location.version) else module.locatio...
null
null
null
Calculates the cumulative score (percent) of the given modules
pcsd
def calculate score for modules user id course modules modules = [m for m in modules] locations = [ Block Usage Locator course key=course id block type=module location block type block id=module location block id if isinstance module location Block Usage Locator and module location version else module location for modu...
2927
def _calculate_score_for_modules(user_id, course, modules): modules = [m for m in modules] locations = [(BlockUsageLocator(course_key=course.id, block_type=module.location.block_type, block_id=module.location.block_id) if (isinstance(module.location, BlockUsageLocator) and module.location.version) else module.locatio...
Calculates the cumulative score (percent) of the given modules
calculates the cumulative score of the given modules
Question: What does this function do? Code: def _calculate_score_for_modules(user_id, course, modules): modules = [m for m in modules] locations = [(BlockUsageLocator(course_key=course.id, block_type=module.location.block_type, block_id=module.location.block_id) if (isinstance(module.location, BlockUsageLocator) a...
null
null
null
What does this function do?
def set_global_options(options): global _global_options _global_options = dict(options)
null
null
null
Sets the global options used as defaults for web server execution.
pcsd
def set global options options global global options global options = dict options
2929
def set_global_options(options): global _global_options _global_options = dict(options)
Sets the global options used as defaults for web server execution.
sets the global options used as defaults for web server execution .
Question: What does this function do? Code: def set_global_options(options): global _global_options _global_options = dict(options)
null
null
null
What does this function do?
def _search(prefix='latest/'): ret = {} for line in http.query(os.path.join(HOST, prefix))['body'].split('\n'): if line.endswith('/'): ret[line[:(-1)]] = _search(prefix=os.path.join(prefix, line)) elif ('=' in line): (key, value) = line.split('=') ret[value] = _search(prefix=os.path.join(prefix, key)) ...
null
null
null
Recursively look up all grains in the metadata server
pcsd
def search prefix='latest/' ret = {} for line in http query os path join HOST prefix ['body'] split ' ' if line endswith '/' ret[line[ -1 ]] = search prefix=os path join prefix line elif '=' in line key value = line split '=' ret[value] = search prefix=os path join prefix key else ret[line] = http query os path join HO...
2933
def _search(prefix='latest/'): ret = {} for line in http.query(os.path.join(HOST, prefix))['body'].split('\n'): if line.endswith('/'): ret[line[:(-1)]] = _search(prefix=os.path.join(prefix, line)) elif ('=' in line): (key, value) = line.split('=') ret[value] = _search(prefix=os.path.join(prefix, key)) ...
Recursively look up all grains in the metadata server
recursively look up all grains in the metadata server
Question: What does this function do? Code: def _search(prefix='latest/'): ret = {} for line in http.query(os.path.join(HOST, prefix))['body'].split('\n'): if line.endswith('/'): ret[line[:(-1)]] = _search(prefix=os.path.join(prefix, line)) elif ('=' in line): (key, value) = line.split('=') ret[value]...
null
null
null
What does this function do?
def stats_aggregate(): return s3_rest_controller()
null
null
null
RESTful CRUD Controller
pcsd
def stats aggregate return s3 rest controller
2937
def stats_aggregate(): return s3_rest_controller()
RESTful CRUD Controller
restful crud controller
Question: What does this function do? Code: def stats_aggregate(): return s3_rest_controller()
null
null
null
What does this function do?
def render_constants(): generate_file('constant_enums.pxi', cython_enums, pjoin(root, 'zmq', 'backend', 'cython')) generate_file('constants.pxi', constants_pyx, pjoin(root, 'zmq', 'backend', 'cython')) generate_file('zmq_constants.h', ifndefs, pjoin(root, 'zmq', 'utils'))
null
null
null
render generated constant files from templates
pcsd
def render constants generate file 'constant enums pxi' cython enums pjoin root 'zmq' 'backend' 'cython' generate file 'constants pxi' constants pyx pjoin root 'zmq' 'backend' 'cython' generate file 'zmq constants h' ifndefs pjoin root 'zmq' 'utils'
2939
def render_constants(): generate_file('constant_enums.pxi', cython_enums, pjoin(root, 'zmq', 'backend', 'cython')) generate_file('constants.pxi', constants_pyx, pjoin(root, 'zmq', 'backend', 'cython')) generate_file('zmq_constants.h', ifndefs, pjoin(root, 'zmq', 'utils'))
render generated constant files from templates
render generated constant files from templates
Question: What does this function do? Code: def render_constants(): generate_file('constant_enums.pxi', cython_enums, pjoin(root, 'zmq', 'backend', 'cython')) generate_file('constants.pxi', constants_pyx, pjoin(root, 'zmq', 'backend', 'cython')) generate_file('zmq_constants.h', ifndefs, pjoin(root, 'zmq', 'utils'...
null
null
null
What does this function do?
def float_format(number): return ('%.3f' % number).rstrip('0').rstrip('.')
null
null
null
Format a float to a precision of 3, without zeroes or dots
pcsd
def float format number return '% 3f' % number rstrip '0' rstrip ' '
2947
def float_format(number): return ('%.3f' % number).rstrip('0').rstrip('.')
Format a float to a precision of 3, without zeroes or dots
format a float to a precision of 3 , without zeroes or dots
Question: What does this function do? Code: def float_format(number): return ('%.3f' % number).rstrip('0').rstrip('.')
null
null
null
What does this function do?
def showHttpErrorCodes(): if kb.httpErrorCodes: warnMsg = 'HTTP error codes detected during run:\n' warnMsg += ', '.join((('%d (%s) - %d times' % (code, (httplib.responses[code] if (code in httplib.responses) else '?'), count)) for (code, count) in kb.httpErrorCodes.items())) logger.warn(warnMsg) if any((((str...
null
null
null
Shows all HTTP error codes raised till now
pcsd
def show Http Error Codes if kb http Error Codes warn Msg = 'HTTP error codes detected during run ' warn Msg += ' ' join '%d %s - %d times' % code httplib responses[code] if code in httplib responses else '?' count for code count in kb http Error Codes items logger warn warn Msg if any str startswith '4' or str startsw...
2974
def showHttpErrorCodes(): if kb.httpErrorCodes: warnMsg = 'HTTP error codes detected during run:\n' warnMsg += ', '.join((('%d (%s) - %d times' % (code, (httplib.responses[code] if (code in httplib.responses) else '?'), count)) for (code, count) in kb.httpErrorCodes.items())) logger.warn(warnMsg) if any((((str...
Shows all HTTP error codes raised till now
shows all http error codes raised till now
Question: What does this function do? Code: def showHttpErrorCodes(): if kb.httpErrorCodes: warnMsg = 'HTTP error codes detected during run:\n' warnMsg += ', '.join((('%d (%s) - %d times' % (code, (httplib.responses[code] if (code in httplib.responses) else '?'), count)) for (code, count) in kb.httpErrorCodes.i...
null
null
null
What does this function do?
def assert_equal_in(logical_line): res = (asse_equal_in_start_with_true_or_false_re.search(logical_line) or asse_equal_in_end_with_true_or_false_re.search(logical_line)) if res: (yield (0, 'N338: Use assertIn/NotIn(A, B) rather than assertEqual(A in B, True/False) when checking collection contents.'))
null
null
null
Check for assertEqual(A in B, True), assertEqual(True, A in B), assertEqual(A in B, False) or assertEqual(False, A in B) sentences N338
pcsd
def assert equal in logical line res = asse equal in start with true or false re search logical line or asse equal in end with true or false re search logical line if res yield 0 'N338 Use assert In/Not In A B rather than assert Equal A in B True/False when checking collection contents '
2978
def assert_equal_in(logical_line): res = (asse_equal_in_start_with_true_or_false_re.search(logical_line) or asse_equal_in_end_with_true_or_false_re.search(logical_line)) if res: (yield (0, 'N338: Use assertIn/NotIn(A, B) rather than assertEqual(A in B, True/False) when checking collection contents.'))
Check for assertEqual(A in B, True), assertEqual(True, A in B), assertEqual(A in B, False) or assertEqual(False, A in B) sentences N338
check for assertequal , assertequal , assertequal or assertequal sentences
Question: What does this function do? Code: def assert_equal_in(logical_line): res = (asse_equal_in_start_with_true_or_false_re.search(logical_line) or asse_equal_in_end_with_true_or_false_re.search(logical_line)) if res: (yield (0, 'N338: Use assertIn/NotIn(A, B) rather than assertEqual(A in B, True/False) when...
null
null
null
What does this function do?
def serialized(function): function.STRING = True return function
null
null
null
Decorator for benchmarks that require serialized XML data
pcsd
def serialized function function STRING = True return function
2979
def serialized(function): function.STRING = True return function
Decorator for benchmarks that require serialized XML data
decorator for benchmarks that require serialized xml data
Question: What does this function do? Code: def serialized(function): function.STRING = True return function
null
null
null
What does this function do?
def open(filename, mode='rb'): if ('r' in mode.lower()): return BgzfReader(filename, mode) elif (('w' in mode.lower()) or ('a' in mode.lower())): return BgzfWriter(filename, mode) else: raise ValueError(('Bad mode %r' % mode))
null
null
null
Open a BGZF file for reading, writing or appending.
pcsd
def open filename mode='rb' if 'r' in mode lower return Bgzf Reader filename mode elif 'w' in mode lower or 'a' in mode lower return Bgzf Writer filename mode else raise Value Error 'Bad mode %r' % mode
2986
def open(filename, mode='rb'): if ('r' in mode.lower()): return BgzfReader(filename, mode) elif (('w' in mode.lower()) or ('a' in mode.lower())): return BgzfWriter(filename, mode) else: raise ValueError(('Bad mode %r' % mode))
Open a BGZF file for reading, writing or appending.
open a bgzf file for reading , writing or appending .
Question: What does this function do? Code: def open(filename, mode='rb'): if ('r' in mode.lower()): return BgzfReader(filename, mode) elif (('w' in mode.lower()) or ('a' in mode.lower())): return BgzfWriter(filename, mode) else: raise ValueError(('Bad mode %r' % mode))
null
null
null
What does this function do?
def _yield_all_instances(emr_conn, cluster_id, *args, **kwargs): for resp in _repeat(emr_conn.list_instances, cluster_id, *args, **kwargs): for instance in getattr(resp, 'instances', []): (yield instance)
null
null
null
Get information about all instances for the given cluster.
pcsd
def yield all instances emr conn cluster id *args **kwargs for resp in repeat emr conn list instances cluster id *args **kwargs for instance in getattr resp 'instances' [] yield instance
2988
def _yield_all_instances(emr_conn, cluster_id, *args, **kwargs): for resp in _repeat(emr_conn.list_instances, cluster_id, *args, **kwargs): for instance in getattr(resp, 'instances', []): (yield instance)
Get information about all instances for the given cluster.
get information about all instances for the given cluster .
Question: What does this function do? Code: def _yield_all_instances(emr_conn, cluster_id, *args, **kwargs): for resp in _repeat(emr_conn.list_instances, cluster_id, *args, **kwargs): for instance in getattr(resp, 'instances', []): (yield instance)
null
null
null
What does this function do?
def _prepare_report_dir(dir_name): dir_name.rmtree_p() dir_name.mkdir_p()
null
null
null
Sets a given directory to a created, but empty state
pcsd
def prepare report dir dir name dir name rmtree p dir name mkdir p
2993
def _prepare_report_dir(dir_name): dir_name.rmtree_p() dir_name.mkdir_p()
Sets a given directory to a created, but empty state
sets a given directory to a created , but empty state
Question: What does this function do? Code: def _prepare_report_dir(dir_name): dir_name.rmtree_p() dir_name.mkdir_p()
null
null
null
What does this function do?
def _create_transport_endpoint(reactor, endpoint_config): if IStreamClientEndpoint.providedBy(endpoint_config): endpoint = IStreamClientEndpoint(endpoint_config) elif (endpoint_config['type'] == 'tcp'): version = int(endpoint_config.get('version', 4)) host = str(endpoint_config['host']) port = int(endpoint_co...
null
null
null
Create a Twisted client endpoint for a WAMP-over-XXX transport.
pcsd
def create transport endpoint reactor endpoint config if I Stream Client Endpoint provided By endpoint config endpoint = I Stream Client Endpoint endpoint config elif endpoint config['type'] == 'tcp' version = int endpoint config get 'version' 4 host = str endpoint config['host'] port = int endpoint config['port'] time...
3003
def _create_transport_endpoint(reactor, endpoint_config): if IStreamClientEndpoint.providedBy(endpoint_config): endpoint = IStreamClientEndpoint(endpoint_config) elif (endpoint_config['type'] == 'tcp'): version = int(endpoint_config.get('version', 4)) host = str(endpoint_config['host']) port = int(endpoint_co...
Create a Twisted client endpoint for a WAMP-over-XXX transport.
create a twisted client endpoint for a wamp - over - xxx transport .
Question: What does this function do? Code: def _create_transport_endpoint(reactor, endpoint_config): if IStreamClientEndpoint.providedBy(endpoint_config): endpoint = IStreamClientEndpoint(endpoint_config) elif (endpoint_config['type'] == 'tcp'): version = int(endpoint_config.get('version', 4)) host = str(en...
null
null
null
What does this function do?
def main(cmd, fn_pos=1): logging.basicConfig(stream=sys.stderr, level=logging.INFO) try: runner = dict(search='main_search', dryrun='main_dryrun', plot_history='main_plot_history')[cmd] except KeyError: logger.error(('Command not recognized: %s' % cmd)) sys.exit(1) try: argv1 = sys.argv[fn_pos] except Inde...
null
null
null
Entry point for bin/* scripts XXX
pcsd
def main cmd fn pos=1 logging basic Config stream=sys stderr level=logging INFO try runner = dict search='main search' dryrun='main dryrun' plot history='main plot history' [cmd] except Key Error logger error 'Command not recognized %s' % cmd sys exit 1 try argv1 = sys argv[fn pos] except Index Error logger error 'Modu...
3007
def main(cmd, fn_pos=1): logging.basicConfig(stream=sys.stderr, level=logging.INFO) try: runner = dict(search='main_search', dryrun='main_dryrun', plot_history='main_plot_history')[cmd] except KeyError: logger.error(('Command not recognized: %s' % cmd)) sys.exit(1) try: argv1 = sys.argv[fn_pos] except Inde...
Entry point for bin/* scripts XXX
entry point for bin / * scripts
Question: What does this function do? Code: def main(cmd, fn_pos=1): logging.basicConfig(stream=sys.stderr, level=logging.INFO) try: runner = dict(search='main_search', dryrun='main_dryrun', plot_history='main_plot_history')[cmd] except KeyError: logger.error(('Command not recognized: %s' % cmd)) sys.exit(1...
null
null
null
What does this function do?
def win_handle_is_a_console(handle): from ctypes import byref, POINTER, windll, WINFUNCTYPE from ctypes.wintypes import BOOL, DWORD, HANDLE FILE_TYPE_CHAR = 2 FILE_TYPE_REMOTE = 32768 INVALID_HANDLE_VALUE = DWORD((-1)).value GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(('GetConsoleMode', windll.kern...
null
null
null
Returns True if a Windows file handle is a handle to a console.
pcsd
def win handle is a console handle from ctypes import byref POINTER windll WINFUNCTYPE from ctypes wintypes import BOOL DWORD HANDLE FILE TYPE CHAR = 2 FILE TYPE REMOTE = 32768 INVALID HANDLE VALUE = DWORD -1 value Get Console Mode = WINFUNCTYPE BOOL HANDLE POINTER DWORD 'Get Console Mode' windll kernel32 Get File Type...
3009
def win_handle_is_a_console(handle): from ctypes import byref, POINTER, windll, WINFUNCTYPE from ctypes.wintypes import BOOL, DWORD, HANDLE FILE_TYPE_CHAR = 2 FILE_TYPE_REMOTE = 32768 INVALID_HANDLE_VALUE = DWORD((-1)).value GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(('GetConsoleMode', windll.kern...
Returns True if a Windows file handle is a handle to a console.
returns true if a windows file handle is a handle to a console .
Question: What does this function do? Code: def win_handle_is_a_console(handle): from ctypes import byref, POINTER, windll, WINFUNCTYPE from ctypes.wintypes import BOOL, DWORD, HANDLE FILE_TYPE_CHAR = 2 FILE_TYPE_REMOTE = 32768 INVALID_HANDLE_VALUE = DWORD((-1)).value GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE,...
null
null
null
What does this function do?
def pull(): print green(('%s: Upgrading code' % env.host)) with cd('/home/web2py/applications/eden/'): try: print green(('%s: Upgrading to version %i' % (env.host, env.revno))) run(('bzr pull -r %i' % env.revno), pty=True) except: if (not env.tested): print green(('%s: Upgrading to current Trunk' % e...
null
null
null
Upgrade the Eden code
pcsd
def pull print green '%s Upgrading code' % env host with cd '/home/web2py/applications/eden/' try print green '%s Upgrading to version %i' % env host env revno run 'bzr pull -r %i' % env revno pty=True except if not env tested print green '%s Upgrading to current Trunk' % env host run 'bzr pull' pty=True else print gre...
3011
def pull(): print green(('%s: Upgrading code' % env.host)) with cd('/home/web2py/applications/eden/'): try: print green(('%s: Upgrading to version %i' % (env.host, env.revno))) run(('bzr pull -r %i' % env.revno), pty=True) except: if (not env.tested): print green(('%s: Upgrading to current Trunk' % e...
Upgrade the Eden code
upgrade the eden code
Question: What does this function do? Code: def pull(): print green(('%s: Upgrading code' % env.host)) with cd('/home/web2py/applications/eden/'): try: print green(('%s: Upgrading to version %i' % (env.host, env.revno))) run(('bzr pull -r %i' % env.revno), pty=True) except: if (not env.tested): pr...
null
null
null
What does this function do?
def flush(bank, key=None): if (key is None): c_key = bank else: c_key = '{0}/{1}'.format(bank, key) try: return api.kv.delete(c_key, recurse=(key is None)) except Exception as exc: raise SaltCacheError('There was an error removing the key, {0}: {1}'.format(c_key, exc))
null
null
null
Remove the key from the cache bank with all the key content.
pcsd
def flush bank key=None if key is None c key = bank else c key = '{0}/{1}' format bank key try return api kv delete c key recurse= key is None except Exception as exc raise Salt Cache Error 'There was an error removing the key {0} {1}' format c key exc
3024
def flush(bank, key=None): if (key is None): c_key = bank else: c_key = '{0}/{1}'.format(bank, key) try: return api.kv.delete(c_key, recurse=(key is None)) except Exception as exc: raise SaltCacheError('There was an error removing the key, {0}: {1}'.format(c_key, exc))
Remove the key from the cache bank with all the key content.
remove the key from the cache bank with all the key content .
Question: What does this function do? Code: def flush(bank, key=None): if (key is None): c_key = bank else: c_key = '{0}/{1}'.format(bank, key) try: return api.kv.delete(c_key, recurse=(key is None)) except Exception as exc: raise SaltCacheError('There was an error removing the key, {0}: {1}'.format(c_ke...
null
null
null
What does this function do?
@treeio_login_required @handle_response_format def report_edit(request, report_id=None, response_format='html'): report = get_object_or_404(Report, pk=report_id) if (not request.user.profile.has_permission(report, mode='w')): return user_denied(request, message="You don't have access to edit this Report") model = ...
null
null
null
Create new report based on user choice
pcsd
@treeio login required @handle response format def report edit request report id=None response format='html' report = get object or 404 Report pk=report id if not request user profile has permission report mode='w' return user denied request message="You don't have access to edit this Report" model = loads report model...
3031
@treeio_login_required @handle_response_format def report_edit(request, report_id=None, response_format='html'): report = get_object_or_404(Report, pk=report_id) if (not request.user.profile.has_permission(report, mode='w')): return user_denied(request, message="You don't have access to edit this Report") model = ...
Create new report based on user choice
create new report based on user choice
Question: What does this function do? Code: @treeio_login_required @handle_response_format def report_edit(request, report_id=None, response_format='html'): report = get_object_or_404(Report, pk=report_id) if (not request.user.profile.has_permission(report, mode='w')): return user_denied(request, message="You do...
null
null
null
What does this function do?
def scan_company_names(name_list, name1, results=0, ro_thresold=None): if (ro_thresold is not None): RO_THRESHOLD = ro_thresold else: RO_THRESHOLD = 0.6 sm1 = SequenceMatcher() sm1.set_seq1(name1.lower()) resd = {} withoutCountry = (not name1.endswith(']')) for (i, n) in name_list: if isinstance(n, str): ...
null
null
null
Scan a list of company names, searching for best matches against the given name. Notice that this function takes a list of strings, and not a list of dictionaries.
pcsd
def scan company names name list name1 results=0 ro thresold=None if ro thresold is not None RO THRESHOLD = ro thresold else RO THRESHOLD = 0 6 sm1 = Sequence Matcher sm1 set seq1 name1 lower resd = {} without Country = not name1 endswith ']' for i n in name list if isinstance n str n = unicode n 'latin1' 'ignore' o na...
3033
def scan_company_names(name_list, name1, results=0, ro_thresold=None): if (ro_thresold is not None): RO_THRESHOLD = ro_thresold else: RO_THRESHOLD = 0.6 sm1 = SequenceMatcher() sm1.set_seq1(name1.lower()) resd = {} withoutCountry = (not name1.endswith(']')) for (i, n) in name_list: if isinstance(n, str): ...
Scan a list of company names, searching for best matches against the given name. Notice that this function takes a list of strings, and not a list of dictionaries.
scan a list of company names , searching for best matches against the given name .
Question: What does this function do? Code: def scan_company_names(name_list, name1, results=0, ro_thresold=None): if (ro_thresold is not None): RO_THRESHOLD = ro_thresold else: RO_THRESHOLD = 0.6 sm1 = SequenceMatcher() sm1.set_seq1(name1.lower()) resd = {} withoutCountry = (not name1.endswith(']')) for ...
null
null
null
What does this function do?
def _expand_path(path): path = os.path.expandvars(path) path = os.path.expanduser(path) return path
null
null
null
Expand both environment variables and user home in the given path.
pcsd
def expand path path path = os path expandvars path path = os path expanduser path return path
3034
def _expand_path(path): path = os.path.expandvars(path) path = os.path.expanduser(path) return path
Expand both environment variables and user home in the given path.
expand both environment variables and user home in the given path .
Question: What does this function do? Code: def _expand_path(path): path = os.path.expandvars(path) path = os.path.expanduser(path) return path
null
null
null
What does this function do?
def parameter_banks(device, device_dict=DEVICE_DICT): if (device != None): if (device.class_name in device_dict.keys()): def names_to_params(bank): return map(partial(get_parameter_by_name, device), bank) return map(names_to_params, device_dict[device.class_name]) else: if (device.class_name in MAX_DE...
null
null
null
Determine the parameters to use for a device
pcsd
def parameter banks device device dict=DEVICE DICT if device != None if device class name in device dict keys def names to params bank return map partial get parameter by name device bank return map names to params device dict[device class name] else if device class name in MAX DEVICES try banks = device get bank count...
3038
def parameter_banks(device, device_dict=DEVICE_DICT): if (device != None): if (device.class_name in device_dict.keys()): def names_to_params(bank): return map(partial(get_parameter_by_name, device), bank) return map(names_to_params, device_dict[device.class_name]) else: if (device.class_name in MAX_DE...
Determine the parameters to use for a device
determine the parameters to use for a device
Question: What does this function do? Code: def parameter_banks(device, device_dict=DEVICE_DICT): if (device != None): if (device.class_name in device_dict.keys()): def names_to_params(bank): return map(partial(get_parameter_by_name, device), bank) return map(names_to_params, device_dict[device.class_na...
null
null
null
What does this function do?
def cluster_distance(cluster1, cluster2, distance_agg=min): return distance_agg([distance(input1, input2) for input1 in get_values(cluster1) for input2 in get_values(cluster2)])
null
null
null
finds the aggregate distance between elements of cluster1 and elements of cluster2
pcsd
def cluster distance cluster1 cluster2 distance agg=min return distance agg [distance input1 input2 for input1 in get values cluster1 for input2 in get values cluster2 ]
3039
def cluster_distance(cluster1, cluster2, distance_agg=min): return distance_agg([distance(input1, input2) for input1 in get_values(cluster1) for input2 in get_values(cluster2)])
finds the aggregate distance between elements of cluster1 and elements of cluster2
finds the aggregate distance between elements of cluster1 and elements of cluster2
Question: What does this function do? Code: def cluster_distance(cluster1, cluster2, distance_agg=min): return distance_agg([distance(input1, input2) for input1 in get_values(cluster1) for input2 in get_values(cluster2)])
null
null
null
What does this function do?
def settings_from_prefix(prefix=None, bundle_libzmq_dylib=False): settings = {} settings['libraries'] = [] settings['include_dirs'] = [] settings['library_dirs'] = [] settings['runtime_library_dirs'] = [] settings['extra_link_args'] = [] if sys.platform.startswith('win'): settings['libraries'].append(libzmq_na...
null
null
null
load appropriate library/include settings from ZMQ prefix
pcsd
def settings from prefix prefix=None bundle libzmq dylib=False settings = {} settings['libraries'] = [] settings['include dirs'] = [] settings['library dirs'] = [] settings['runtime library dirs'] = [] settings['extra link args'] = [] if sys platform startswith 'win' settings['libraries'] append libzmq name if prefix s...
3045
def settings_from_prefix(prefix=None, bundle_libzmq_dylib=False): settings = {} settings['libraries'] = [] settings['include_dirs'] = [] settings['library_dirs'] = [] settings['runtime_library_dirs'] = [] settings['extra_link_args'] = [] if sys.platform.startswith('win'): settings['libraries'].append(libzmq_na...
load appropriate library/include settings from ZMQ prefix
load appropriate library / include settings from zmq prefix
Question: What does this function do? Code: def settings_from_prefix(prefix=None, bundle_libzmq_dylib=False): settings = {} settings['libraries'] = [] settings['include_dirs'] = [] settings['library_dirs'] = [] settings['runtime_library_dirs'] = [] settings['extra_link_args'] = [] if sys.platform.startswith('...
null
null
null
What does this function do?
def summarize_exit_codes(exit_codes): for ec in exit_codes: if (ec != 0): return ec return 0
null
null
null
Take a list of exit codes, if at least one of them is not 0, then return that number.
pcsd
def summarize exit codes exit codes for ec in exit codes if ec != 0 return ec return 0
3046
def summarize_exit_codes(exit_codes): for ec in exit_codes: if (ec != 0): return ec return 0
Take a list of exit codes, if at least one of them is not 0, then return that number.
take a list of exit codes , if at least one of them is not 0 , then return that number .
Question: What does this function do? Code: def summarize_exit_codes(exit_codes): for ec in exit_codes: if (ec != 0): return ec return 0
null
null
null
What does this function do?
def get_drone(hostname): if (hostname == 'localhost'): return _LocalDrone() try: return _RemoteDrone(hostname) except DroneUnreachable: return None
null
null
null
Use this factory method to get drone objects.
pcsd
def get drone hostname if hostname == 'localhost' return Local Drone try return Remote Drone hostname except Drone Unreachable return None
3048
def get_drone(hostname): if (hostname == 'localhost'): return _LocalDrone() try: return _RemoteDrone(hostname) except DroneUnreachable: return None
Use this factory method to get drone objects.
use this factory method to get drone objects .
Question: What does this function do? Code: def get_drone(hostname): if (hostname == 'localhost'): return _LocalDrone() try: return _RemoteDrone(hostname) except DroneUnreachable: return None
null
null
null
What does this function do?
def remove_like(doctype, name): frappe.delete_doc(u'Communication', [c.name for c in frappe.get_all(u'Communication', filters={u'communication_type': u'Comment', u'reference_doctype': doctype, u'reference_name': name, u'owner': frappe.session.user, u'comment_type': u'Like'})], ignore_permissions=True)
null
null
null
Remove previous Like
pcsd
def remove like doctype name frappe delete doc u'Communication' [c name for c in frappe get all u'Communication' filters={u'communication type' u'Comment' u'reference doctype' doctype u'reference name' name u'owner' frappe session user u'comment type' u'Like'} ] ignore permissions=True
3049
def remove_like(doctype, name): frappe.delete_doc(u'Communication', [c.name for c in frappe.get_all(u'Communication', filters={u'communication_type': u'Comment', u'reference_doctype': doctype, u'reference_name': name, u'owner': frappe.session.user, u'comment_type': u'Like'})], ignore_permissions=True)
Remove previous Like
remove previous like
Question: What does this function do? Code: def remove_like(doctype, name): frappe.delete_doc(u'Communication', [c.name for c in frappe.get_all(u'Communication', filters={u'communication_type': u'Comment', u'reference_doctype': doctype, u'reference_name': name, u'owner': frappe.session.user, u'comment_type': u'Like...
null
null
null
What does this function do?
def get_legal(state): feature = np.zeros((1, state.size, state.size)) for (x, y) in state.get_legal_moves(): feature[(0, x, y)] = 1 return feature
null
null
null
Zero at all illegal moves, one at all legal moves. Unlike sensibleness, no eye check is done
pcsd
def get legal state feature = np zeros 1 state size state size for x y in state get legal moves feature[ 0 x y ] = 1 return feature
3052
def get_legal(state): feature = np.zeros((1, state.size, state.size)) for (x, y) in state.get_legal_moves(): feature[(0, x, y)] = 1 return feature
Zero at all illegal moves, one at all legal moves. Unlike sensibleness, no eye check is done
zero at all illegal moves , one at all legal moves .
Question: What does this function do? Code: def get_legal(state): feature = np.zeros((1, state.size, state.size)) for (x, y) in state.get_legal_moves(): feature[(0, x, y)] = 1 return feature
null
null
null
What does this function do?
def execute_without_nm(*cmd, **kwargs): funcs = {test_data.sensor_status_cmd: get_sensor_status_uninit, test_data.init_sensor_cmd: init_sensor_agent, test_data.sdr_dump_cmd: sdr_dump} return _execute(funcs, *cmd, **kwargs)
null
null
null
test version of execute on Non-Node Manager platform.
pcsd
def execute without nm *cmd **kwargs funcs = {test data sensor status cmd get sensor status uninit test data init sensor cmd init sensor agent test data sdr dump cmd sdr dump} return execute funcs *cmd **kwargs
3055
def execute_without_nm(*cmd, **kwargs): funcs = {test_data.sensor_status_cmd: get_sensor_status_uninit, test_data.init_sensor_cmd: init_sensor_agent, test_data.sdr_dump_cmd: sdr_dump} return _execute(funcs, *cmd, **kwargs)
test version of execute on Non-Node Manager platform.
test version of execute on non - node manager platform .
Question: What does this function do? Code: def execute_without_nm(*cmd, **kwargs): funcs = {test_data.sensor_status_cmd: get_sensor_status_uninit, test_data.init_sensor_cmd: init_sensor_agent, test_data.sdr_dump_cmd: sdr_dump} return _execute(funcs, *cmd, **kwargs)
null
null
null
What does this function do?
def prompt_for_clone(): (url, ok) = qtutils.prompt(N_(u'Path or URL to clone (Env. $VARS okay)')) url = utils.expandpath(url) if ((not ok) or (not url)): return None try: newurl = url.replace(u'\\', u'/').rstrip(u'/') default = newurl.rsplit(u'/', 1)[(-1)] if (default == u'.git'): default = os.path.basen...
null
null
null
Present a GUI for cloning a repository. Returns the target directory and URL
pcsd
def prompt for clone url ok = qtutils prompt N u'Path or URL to clone Env $VARS okay ' url = utils expandpath url if not ok or not url return None try newurl = url replace u'\\' u'/' rstrip u'/' default = newurl rsplit u'/' 1 [ -1 ] if default == u' git' default = os path basename os path dirname newurl if default ends...
3060
def prompt_for_clone(): (url, ok) = qtutils.prompt(N_(u'Path or URL to clone (Env. $VARS okay)')) url = utils.expandpath(url) if ((not ok) or (not url)): return None try: newurl = url.replace(u'\\', u'/').rstrip(u'/') default = newurl.rsplit(u'/', 1)[(-1)] if (default == u'.git'): default = os.path.basen...
Present a GUI for cloning a repository. Returns the target directory and URL
present a gui for cloning a repository .
Question: What does this function do? Code: def prompt_for_clone(): (url, ok) = qtutils.prompt(N_(u'Path or URL to clone (Env. $VARS okay)')) url = utils.expandpath(url) if ((not ok) or (not url)): return None try: newurl = url.replace(u'\\', u'/').rstrip(u'/') default = newurl.rsplit(u'/', 1)[(-1)] if (...
null
null
null
What does this function do?
def resource_id_from_record_tuple(record): return record[0]['resource_id']
null
null
null
Extract resource_id from HBase tuple record.
pcsd
def resource id from record tuple record return record[0]['resource id']
3064
def resource_id_from_record_tuple(record): return record[0]['resource_id']
Extract resource_id from HBase tuple record.
extract resource _ id from hbase tuple record .
Question: What does this function do? Code: def resource_id_from_record_tuple(record): return record[0]['resource_id']
null
null
null
What does this function do?
def ones_and_zeros(digits): return bin(random.getrandbits(digits)).lstrip('0b').zfill(digits)
null
null
null
Express `n` in at least `d` binary digits, with no special prefix.
pcsd
def ones and zeros digits return bin random getrandbits digits lstrip '0b' zfill digits
3069
def ones_and_zeros(digits): return bin(random.getrandbits(digits)).lstrip('0b').zfill(digits)
Express `n` in at least `d` binary digits, with no special prefix.
express n in at least d binary digits , with no special prefix .
Question: What does this function do? Code: def ones_and_zeros(digits): return bin(random.getrandbits(digits)).lstrip('0b').zfill(digits)
null
null
null
What does this function do?
def get_portable_base(): if isportable: return os.path.dirname(os.path.dirname(os.environ['CALIBRE_PORTABLE_BUILD']))
null
null
null
Return path to the directory that contains calibre-portable.exe or None
pcsd
def get portable base if isportable return os path dirname os path dirname os environ['CALIBRE PORTABLE BUILD']
3076
def get_portable_base(): if isportable: return os.path.dirname(os.path.dirname(os.environ['CALIBRE_PORTABLE_BUILD']))
Return path to the directory that contains calibre-portable.exe or None
return path to the directory that contains calibre - portable . exe or none
Question: What does this function do? Code: def get_portable_base(): if isportable: return os.path.dirname(os.path.dirname(os.environ['CALIBRE_PORTABLE_BUILD']))