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 assert_permissions(path, permission, log):
if (not check_permissions(util.syspath(path), permission)):
log.warning(u'could not set permissions on {}', util.displayable_path(path))
log.debug(u'set permissions to {}, but permissions are now {}', permission, (os.stat(util.syspath(path)).st_mode & 511))
| null | null | null | Check whether the file\'s permissions are as expected, otherwise,
log a warning message. Return a boolean indicating the match, like
`check_permissions`. | pcsd | def assert permissions path permission log if not check permissions util syspath path permission log warning u'could not set permissions on {}' util displayable path path log debug u'set permissions to {} but permissions are now {}' permission os stat util syspath path st mode & 511 | 897 | def assert_permissions(path, permission, log):
if (not check_permissions(util.syspath(path), permission)):
log.warning(u'could not set permissions on {}', util.displayable_path(path))
log.debug(u'set permissions to {}, but permissions are now {}', permission, (os.stat(util.syspath(path)).st_mode & 511))
| Check whether the file\'s permissions are as expected, otherwise,
log a warning message. Return a boolean indicating the match, like
`check_permissions`. | check whether the files permissions are as expected , otherwise , log a warning message . | Question:
What does this function do?
Code:
def assert_permissions(path, permission, log):
if (not check_permissions(util.syspath(path), permission)):
log.warning(u'could not set permissions on {}', util.displayable_path(path))
log.debug(u'set permissions to {}, but permissions are now {}', permission, (os.stat... |
null | null | null | What does this function do? | @get('/admin/<taskid>/flush')
def task_flush(taskid):
if is_admin(taskid):
DataStore.tasks = dict()
else:
for key in list(DataStore.tasks):
if (DataStore.tasks[key].remote_addr == request.remote_addr):
del DataStore.tasks[key]
logger.debug(('[%s] Flushed task pool (%s)' % (taskid, ('admin' if is_admin(tas... | null | null | null | Flush task spool (delete all tasks) | pcsd | @get '/admin/<taskid>/flush' def task flush taskid if is admin taskid Data Store tasks = dict else for key in list Data Store tasks if Data Store tasks[key] remote addr == request remote addr del Data Store tasks[key] logger debug '[%s] Flushed task pool %s ' % taskid 'admin' if is admin taskid else request remote addr... | 898 | @get('/admin/<taskid>/flush')
def task_flush(taskid):
if is_admin(taskid):
DataStore.tasks = dict()
else:
for key in list(DataStore.tasks):
if (DataStore.tasks[key].remote_addr == request.remote_addr):
del DataStore.tasks[key]
logger.debug(('[%s] Flushed task pool (%s)' % (taskid, ('admin' if is_admin(tas... | Flush task spool (delete all tasks) | flush task spool | Question:
What does this function do?
Code:
@get('/admin/<taskid>/flush')
def task_flush(taskid):
if is_admin(taskid):
DataStore.tasks = dict()
else:
for key in list(DataStore.tasks):
if (DataStore.tasks[key].remote_addr == request.remote_addr):
del DataStore.tasks[key]
logger.debug(('[%s] Flushed task... |
null | null | null | What does this function do? | def _sphere_constraint(rd, r0, R_adj):
return (R_adj - np.sqrt(np.sum(((rd - r0) ** 2))))
| null | null | null | Sphere fitting constraint. | pcsd | def sphere constraint rd r0 R adj return R adj - np sqrt np sum rd - r0 ** 2 | 900 | def _sphere_constraint(rd, r0, R_adj):
return (R_adj - np.sqrt(np.sum(((rd - r0) ** 2))))
| Sphere fitting constraint. | sphere fitting constraint . | Question:
What does this function do?
Code:
def _sphere_constraint(rd, r0, R_adj):
return (R_adj - np.sqrt(np.sum(((rd - r0) ** 2))))
|
null | null | null | What does this function do? | def p_command_print_bad(p):
p[0] = 'MALFORMED PRINT STATEMENT'
| null | null | null | command : PRINT error | pcsd | def p command print bad p p[0] = 'MALFORMED PRINT STATEMENT' | 904 | def p_command_print_bad(p):
p[0] = 'MALFORMED PRINT STATEMENT'
| command : PRINT error | command : print error | Question:
What does this function do?
Code:
def p_command_print_bad(p):
p[0] = 'MALFORMED PRINT STATEMENT'
|
null | null | null | What does this function do? | @register.simple_tag
def disqus_id_for(obj):
return (u'%s-%s' % (obj._meta.object_name, obj.id))
| null | null | null | Returns a unique identifier for the object to be used in
DISQUS JavaScript. | pcsd | @register simple tag def disqus id for obj return u'%s-%s' % obj meta object name obj id | 912 | @register.simple_tag
def disqus_id_for(obj):
return (u'%s-%s' % (obj._meta.object_name, obj.id))
| Returns a unique identifier for the object to be used in
DISQUS JavaScript. | returns a unique identifier for the object to be used in | Question:
What does this function do?
Code:
@register.simple_tag
def disqus_id_for(obj):
return (u'%s-%s' % (obj._meta.object_name, obj.id))
|
null | null | null | What does this function do? | @with_setup(step_runner_environ)
def test_skipped_steps_can_be_retrieved_as_steps():
f = Feature.from_string(FEATURE1)
feature_result = f.run()
scenario_result = feature_result.scenario_results[0]
for step in scenario_result.steps_skipped:
assert_equals(type(step), Step)
| null | null | null | Skipped steps can be retrieved as steps | pcsd | @with setup step runner environ def test skipped steps can be retrieved as steps f = Feature from string FEATURE1 feature result = f run scenario result = feature result scenario results[0] for step in scenario result steps skipped assert equals type step Step | 913 | @with_setup(step_runner_environ)
def test_skipped_steps_can_be_retrieved_as_steps():
f = Feature.from_string(FEATURE1)
feature_result = f.run()
scenario_result = feature_result.scenario_results[0]
for step in scenario_result.steps_skipped:
assert_equals(type(step), Step)
| Skipped steps can be retrieved as steps | skipped steps can be retrieved as steps | Question:
What does this function do?
Code:
@with_setup(step_runner_environ)
def test_skipped_steps_can_be_retrieved_as_steps():
f = Feature.from_string(FEATURE1)
feature_result = f.run()
scenario_result = feature_result.scenario_results[0]
for step in scenario_result.steps_skipped:
assert_equals(type(step), S... |
null | null | null | What does this function do? | def yum_install(args, package_manager='yum', sudo=False):
return _from_args(sudo)(([package_manager, 'install', '-y'] + args))
| null | null | null | Install a package with ``yum`` or a ``yum``-like package manager. | pcsd | def yum install args package manager='yum' sudo=False return from args sudo [package manager 'install' '-y'] + args | 919 | def yum_install(args, package_manager='yum', sudo=False):
return _from_args(sudo)(([package_manager, 'install', '-y'] + args))
| Install a package with ``yum`` or a ``yum``-like package manager. | install a package with yum or a yum - like package manager . | Question:
What does this function do?
Code:
def yum_install(args, package_manager='yum', sudo=False):
return _from_args(sudo)(([package_manager, 'install', '-y'] + args))
|
null | null | null | What does this function do? | def get_engine_status(engine):
global_tests = ['time()-engine.start_time', 'engine.has_capacity()', 'engine.downloader.is_idle()', 'len(engine.downloader.slots)', 'len(engine.downloader.active)', 'engine.scraper.is_idle()', 'len(engine.scraper.slots)']
spider_tests = ['engine.spider_is_idle(spider)', 'engine.slots[sp... | null | null | null | Return a report of the current engine status | pcsd | def get engine status engine global tests = ['time -engine start time' 'engine has capacity ' 'engine downloader is idle ' 'len engine downloader slots ' 'len engine downloader active ' 'engine scraper is idle ' 'len engine scraper slots '] spider tests = ['engine spider is idle spider ' 'engine slots[spider] closing' ... | 921 | def get_engine_status(engine):
global_tests = ['time()-engine.start_time', 'engine.has_capacity()', 'engine.downloader.is_idle()', 'len(engine.downloader.slots)', 'len(engine.downloader.active)', 'engine.scraper.is_idle()', 'len(engine.scraper.slots)']
spider_tests = ['engine.spider_is_idle(spider)', 'engine.slots[sp... | Return a report of the current engine status | return a report of the current engine status | Question:
What does this function do?
Code:
def get_engine_status(engine):
global_tests = ['time()-engine.start_time', 'engine.has_capacity()', 'engine.downloader.is_idle()', 'len(engine.downloader.slots)', 'len(engine.downloader.active)', 'engine.scraper.is_idle()', 'len(engine.scraper.slots)']
spider_tests = ['e... |
null | null | null | What does this function do? | def _transaction_summary(tx_uuid):
contrib = get_object_or_404(Contribution, uuid=tx_uuid)
contrib_id = contrib.transaction_id
refund_contribs = contrib.get_refund_contribs()
refund_contrib = (refund_contribs[0] if refund_contribs.exists() else None)
lookup = {'status': True, 'transaction': True}
pay = {}
try:
... | null | null | null | Get transaction details from Solitude API. | pcsd | def transaction summary tx uuid contrib = get object or 404 Contribution uuid=tx uuid contrib id = contrib transaction id refund contribs = contrib get refund contribs refund contrib = refund contribs[0] if refund contribs exists else None lookup = {'status' True 'transaction' True} pay = {} try pay = client api generi... | 930 | def _transaction_summary(tx_uuid):
contrib = get_object_or_404(Contribution, uuid=tx_uuid)
contrib_id = contrib.transaction_id
refund_contribs = contrib.get_refund_contribs()
refund_contrib = (refund_contribs[0] if refund_contribs.exists() else None)
lookup = {'status': True, 'transaction': True}
pay = {}
try:
... | Get transaction details from Solitude API. | get transaction details from solitude api . | Question:
What does this function do?
Code:
def _transaction_summary(tx_uuid):
contrib = get_object_or_404(Contribution, uuid=tx_uuid)
contrib_id = contrib.transaction_id
refund_contribs = contrib.get_refund_contribs()
refund_contrib = (refund_contribs[0] if refund_contribs.exists() else None)
lookup = {'status... |
null | null | null | What does this function do? | @contextmanager
def nested(*managers):
exits = []
vars = []
exc = (None, None, None)
try:
try:
for mgr in managers:
exit = mgr.__exit__
enter = mgr.__enter__
vars.append(enter())
exits.append(exit)
(yield vars)
except:
exc = sys.exc_info()
finally:
while exits:
exit = exits.pop... | null | null | null | Nest context managers. | pcsd | @contextmanager def nested *managers exits = [] vars = [] exc = None None None try try for mgr in managers exit = mgr exit enter = mgr enter vars append enter exits append exit yield vars except exc = sys exc info finally while exits exit = exits pop try if exit *exc exc = None None None except exc = sys exc info if ex... | 931 | @contextmanager
def nested(*managers):
exits = []
vars = []
exc = (None, None, None)
try:
try:
for mgr in managers:
exit = mgr.__exit__
enter = mgr.__enter__
vars.append(enter())
exits.append(exit)
(yield vars)
except:
exc = sys.exc_info()
finally:
while exits:
exit = exits.pop... | Nest context managers. | nest context managers . | Question:
What does this function do?
Code:
@contextmanager
def nested(*managers):
exits = []
vars = []
exc = (None, None, None)
try:
try:
for mgr in managers:
exit = mgr.__exit__
enter = mgr.__enter__
vars.append(enter())
exits.append(exit)
(yield vars)
except:
exc = sys.exc_info()
... |
null | null | null | What does this function do? | def setIntegerValueToString(integerSetting, valueString):
dotIndex = valueString.find('.')
if (dotIndex > (-1)):
valueString = valueString[:dotIndex]
try:
integerSetting.value = int(valueString)
return
except:
print ((('Warning, can not read integer ' + integerSetting.name) + ' ') + valueString)
print 'Wi... | null | null | null | Set the integer to the string. | pcsd | def set Integer Value To String integer Setting value String dot Index = value String find ' ' if dot Index > -1 value String = value String[ dot Index] try integer Setting value = int value String return except print 'Warning can not read integer ' + integer Setting name + ' ' + value String print 'Will try reading as... | 933 | def setIntegerValueToString(integerSetting, valueString):
dotIndex = valueString.find('.')
if (dotIndex > (-1)):
valueString = valueString[:dotIndex]
try:
integerSetting.value = int(valueString)
return
except:
print ((('Warning, can not read integer ' + integerSetting.name) + ' ') + valueString)
print 'Wi... | Set the integer to the string. | set the integer to the string . | Question:
What does this function do?
Code:
def setIntegerValueToString(integerSetting, valueString):
dotIndex = valueString.find('.')
if (dotIndex > (-1)):
valueString = valueString[:dotIndex]
try:
integerSetting.value = int(valueString)
return
except:
print ((('Warning, can not read integer ' + integer... |
null | null | null | What does this function do? | @tasklets.tasklet
def create_upload_url_async(success_path, max_bytes_per_blob=None, max_bytes_total=None, **options):
rpc = blobstore.create_rpc(**options)
rpc = blobstore.create_upload_url_async(success_path, max_bytes_per_blob=max_bytes_per_blob, max_bytes_total=max_bytes_total, rpc=rpc)
result = (yield rpc)
rai... | null | null | null | Async version of create_upload_url(). | pcsd | @tasklets tasklet def create upload url async success path max bytes per blob=None max bytes total=None **options rpc = blobstore create rpc **options rpc = blobstore create upload url async success path max bytes per blob=max bytes per blob max bytes total=max bytes total rpc=rpc result = yield rpc raise tasklets Retu... | 941 | @tasklets.tasklet
def create_upload_url_async(success_path, max_bytes_per_blob=None, max_bytes_total=None, **options):
rpc = blobstore.create_rpc(**options)
rpc = blobstore.create_upload_url_async(success_path, max_bytes_per_blob=max_bytes_per_blob, max_bytes_total=max_bytes_total, rpc=rpc)
result = (yield rpc)
rai... | Async version of create_upload_url(). | async version of create _ upload _ url ( ) . | Question:
What does this function do?
Code:
@tasklets.tasklet
def create_upload_url_async(success_path, max_bytes_per_blob=None, max_bytes_total=None, **options):
rpc = blobstore.create_rpc(**options)
rpc = blobstore.create_upload_url_async(success_path, max_bytes_per_blob=max_bytes_per_blob, max_bytes_total=max_b... |
null | null | null | What does this function do? | def maybe_convert_ix(*args):
ixify = True
for arg in args:
if (not isinstance(arg, (np.ndarray, list, ABCSeries, Index))):
ixify = False
if ixify:
return np.ix_(*args)
else:
return args
| null | null | null | We likely want to take the cross-product | pcsd | def maybe convert ix *args ixify = True for arg in args if not isinstance arg np ndarray list ABC Series Index ixify = False if ixify return np ix *args else return args | 944 | def maybe_convert_ix(*args):
ixify = True
for arg in args:
if (not isinstance(arg, (np.ndarray, list, ABCSeries, Index))):
ixify = False
if ixify:
return np.ix_(*args)
else:
return args
| We likely want to take the cross-product | we likely want to take the cross - product | Question:
What does this function do?
Code:
def maybe_convert_ix(*args):
ixify = True
for arg in args:
if (not isinstance(arg, (np.ndarray, list, ABCSeries, Index))):
ixify = False
if ixify:
return np.ix_(*args)
else:
return args
|
null | null | null | What does this function do? | def sublime_format_path(pth):
m = re.match('^([A-Za-z]{1}):(?:/|\\\\)(.*)', pth)
if ((sublime.platform() == 'windows') and (m is not None)):
pth = ((m.group(1) + '/') + m.group(2))
return pth.replace('\\', '/')
| null | null | null | Format path for Sublime internally. | pcsd | def sublime format path pth m = re match '^ [A-Za-z]{1} ? /|\\\\ * ' pth if sublime platform == 'windows' and m is not None pth = m group 1 + '/' + m group 2 return pth replace '\\' '/' | 947 | def sublime_format_path(pth):
m = re.match('^([A-Za-z]{1}):(?:/|\\\\)(.*)', pth)
if ((sublime.platform() == 'windows') and (m is not None)):
pth = ((m.group(1) + '/') + m.group(2))
return pth.replace('\\', '/')
| Format path for Sublime internally. | format path for sublime internally . | Question:
What does this function do?
Code:
def sublime_format_path(pth):
m = re.match('^([A-Za-z]{1}):(?:/|\\\\)(.*)', pth)
if ((sublime.platform() == 'windows') and (m is not None)):
pth = ((m.group(1) + '/') + m.group(2))
return pth.replace('\\', '/')
|
null | null | null | What does this function do? | @image_comparison(baseline_images=[u'EventCollection_plot__set_positions'])
def test__EventCollection__set_positions():
(splt, coll, props) = generate_EventCollection_plot()
new_positions = np.hstack([props[u'positions'], props[u'extra_positions']])
coll.set_positions(new_positions)
np.testing.assert_array_equal(ne... | null | null | null | check to make sure set_positions works properly | pcsd | @image comparison baseline images=[u'Event Collection plot set positions'] def test Event Collection set positions splt coll props = generate Event Collection plot new positions = np hstack [props[u'positions'] props[u'extra positions']] coll set positions new positions np testing assert array equal new positions coll ... | 953 | @image_comparison(baseline_images=[u'EventCollection_plot__set_positions'])
def test__EventCollection__set_positions():
(splt, coll, props) = generate_EventCollection_plot()
new_positions = np.hstack([props[u'positions'], props[u'extra_positions']])
coll.set_positions(new_positions)
np.testing.assert_array_equal(ne... | check to make sure set_positions works properly | check to make sure set _ positions works properly | Question:
What does this function do?
Code:
@image_comparison(baseline_images=[u'EventCollection_plot__set_positions'])
def test__EventCollection__set_positions():
(splt, coll, props) = generate_EventCollection_plot()
new_positions = np.hstack([props[u'positions'], props[u'extra_positions']])
coll.set_positions(n... |
null | null | null | What does this function do? | def delete_course_and_groups(course_key, user_id):
module_store = modulestore()
with module_store.bulk_operations(course_key):
module_store.delete_course(course_key, user_id)
print 'removing User permissions from course....'
try:
remove_all_instructors(course_key)
except Exception as err:
log.error('Err... | null | null | null | This deletes the courseware associated with a course_key as well as cleaning update_item
the various user table stuff (groups, permissions, etc.) | pcsd | def delete course and groups course key user id module store = modulestore with module store bulk operations course key module store delete course course key user id print 'removing User permissions from course ' try remove all instructors course key except Exception as err log error 'Error in deleting course groups fo... | 956 | def delete_course_and_groups(course_key, user_id):
module_store = modulestore()
with module_store.bulk_operations(course_key):
module_store.delete_course(course_key, user_id)
print 'removing User permissions from course....'
try:
remove_all_instructors(course_key)
except Exception as err:
log.error('Err... | This deletes the courseware associated with a course_key as well as cleaning update_item
the various user table stuff (groups, permissions, etc.) | this deletes the courseware associated with a course _ key as well as cleaning update _ item the various user table stuff | Question:
What does this function do?
Code:
def delete_course_and_groups(course_key, user_id):
module_store = modulestore()
with module_store.bulk_operations(course_key):
module_store.delete_course(course_key, user_id)
print 'removing User permissions from course....'
try:
remove_all_instructors(course_ke... |
null | null | null | What does this function do? | def export_set(dataset):
stream = StringIO()
if is_py3:
_csv = csv.writer(stream)
else:
_csv = csv.writer(stream, encoding=DEFAULT_ENCODING)
for row in dataset._package(dicts=False):
_csv.writerow(row)
return stream.getvalue()
| null | null | null | Returns CSV representation of Dataset. | pcsd | def export set dataset stream = String IO if is py3 csv = csv writer stream else csv = csv writer stream encoding=DEFAULT ENCODING for row in dataset package dicts=False csv writerow row return stream getvalue | 960 | def export_set(dataset):
stream = StringIO()
if is_py3:
_csv = csv.writer(stream)
else:
_csv = csv.writer(stream, encoding=DEFAULT_ENCODING)
for row in dataset._package(dicts=False):
_csv.writerow(row)
return stream.getvalue()
| Returns CSV representation of Dataset. | returns csv representation of dataset . | Question:
What does this function do?
Code:
def export_set(dataset):
stream = StringIO()
if is_py3:
_csv = csv.writer(stream)
else:
_csv = csv.writer(stream, encoding=DEFAULT_ENCODING)
for row in dataset._package(dicts=False):
_csv.writerow(row)
return stream.getvalue()
|
null | null | null | What does this function do? | def xy_to_array_origin(image):
return rgb_transpose(image[:, ::(-1)])
| null | null | null | Return view of image transformed from Cartesian to array origin. | pcsd | def xy to array origin image return rgb transpose image[ -1 ] | 967 | def xy_to_array_origin(image):
return rgb_transpose(image[:, ::(-1)])
| Return view of image transformed from Cartesian to array origin. | return view of image transformed from cartesian to array origin . | Question:
What does this function do?
Code:
def xy_to_array_origin(image):
return rgb_transpose(image[:, ::(-1)])
|
null | null | null | What does this function do? | def plot_models(x, y, models, fname, mx=None, ymax=None, xmin=None):
plt.figure(num=None, figsize=(8, 6))
plt.clf()
plt.scatter(x, y, s=10)
plt.title('Web traffic over the last month')
plt.xlabel('Time')
plt.ylabel('Hits/hour')
plt.xticks([((w * 7) * 24) for w in range(10)], [('week %i' % w) for w in range(10)])... | null | null | null | plot input data | pcsd | def plot models x y models fname mx=None ymax=None xmin=None plt figure num=None figsize= 8 6 plt clf plt scatter x y s=10 plt title 'Web traffic over the last month' plt xlabel 'Time' plt ylabel 'Hits/hour' plt xticks [ w * 7 * 24 for w in range 10 ] [ 'week %i' % w for w in range 10 ] if models if mx is None mx = sp ... | 973 | def plot_models(x, y, models, fname, mx=None, ymax=None, xmin=None):
plt.figure(num=None, figsize=(8, 6))
plt.clf()
plt.scatter(x, y, s=10)
plt.title('Web traffic over the last month')
plt.xlabel('Time')
plt.ylabel('Hits/hour')
plt.xticks([((w * 7) * 24) for w in range(10)], [('week %i' % w) for w in range(10)])... | plot input data | plot input data | Question:
What does this function do?
Code:
def plot_models(x, y, models, fname, mx=None, ymax=None, xmin=None):
plt.figure(num=None, figsize=(8, 6))
plt.clf()
plt.scatter(x, y, s=10)
plt.title('Web traffic over the last month')
plt.xlabel('Time')
plt.ylabel('Hits/hour')
plt.xticks([((w * 7) * 24) for w in ra... |
null | null | null | What does this function do? | def _execute5(*args, **kargs):
cmd = (args[1:(-3)] if (args[0] == 'raidcom') else args)
result = EXECUTE_TABLE5.get(cmd, CMD_SUCCEED)
return result
| null | null | null | Return predefined results based on EXECUTE_TABLE5. | pcsd | def execute5 *args **kargs cmd = args[1 -3 ] if args[0] == 'raidcom' else args result = EXECUTE TABLE5 get cmd CMD SUCCEED return result | 975 | def _execute5(*args, **kargs):
cmd = (args[1:(-3)] if (args[0] == 'raidcom') else args)
result = EXECUTE_TABLE5.get(cmd, CMD_SUCCEED)
return result
| Return predefined results based on EXECUTE_TABLE5. | return predefined results based on execute _ table5 . | Question:
What does this function do?
Code:
def _execute5(*args, **kargs):
cmd = (args[1:(-3)] if (args[0] == 'raidcom') else args)
result = EXECUTE_TABLE5.get(cmd, CMD_SUCCEED)
return result
|
null | null | null | What does this function do? | def _get_cart_quotation(party=None):
if (not party):
party = get_party()
quotation = frappe.get_all(u'Quotation', fields=[u'name'], filters={party.doctype.lower(): party.name, u'order_type': u'Shopping Cart', u'docstatus': 0}, order_by=u'modified desc', limit_page_length=1)
if quotation:
qdoc = frappe.get_doc(u'... | null | null | null | Return the open Quotation of type "Shopping Cart" or make a new one | pcsd | def get cart quotation party=None if not party party = get party quotation = frappe get all u'Quotation' fields=[u'name'] filters={party doctype lower party name u'order type' u'Shopping Cart' u'docstatus' 0} order by=u'modified desc' limit page length=1 if quotation qdoc = frappe get doc u'Quotation' quotation[0] name... | 977 | def _get_cart_quotation(party=None):
if (not party):
party = get_party()
quotation = frappe.get_all(u'Quotation', fields=[u'name'], filters={party.doctype.lower(): party.name, u'order_type': u'Shopping Cart', u'docstatus': 0}, order_by=u'modified desc', limit_page_length=1)
if quotation:
qdoc = frappe.get_doc(u'... | Return the open Quotation of type "Shopping Cart" or make a new one | return the open quotation of type " shopping cart " or make a new one | Question:
What does this function do?
Code:
def _get_cart_quotation(party=None):
if (not party):
party = get_party()
quotation = frappe.get_all(u'Quotation', fields=[u'name'], filters={party.doctype.lower(): party.name, u'order_type': u'Shopping Cart', u'docstatus': 0}, order_by=u'modified desc', limit_page_leng... |
null | null | null | What does this function do? | def deploy_response_select_mission(r, **attr):
message_id = (r.record.message_id if r.record else None)
if ((r.representation not in ('html', 'aadata')) or (not message_id) or (not r.component)):
r.error(405, current.ERROR.BAD_METHOD)
T = current.T
db = current.db
s3db = current.s3db
atable = s3db.msg_attachmen... | null | null | null | Custom method to Link a Response to a Mission &/or Human Resource | pcsd | def deploy response select mission r **attr message id = r record message id if r record else None if r representation not in 'html' 'aadata' or not message id or not r component r error 405 current ERROR BAD METHOD T = current T db = current db s3db = current s3db atable = s3db msg attachment dtable = db doc document ... | 982 | def deploy_response_select_mission(r, **attr):
message_id = (r.record.message_id if r.record else None)
if ((r.representation not in ('html', 'aadata')) or (not message_id) or (not r.component)):
r.error(405, current.ERROR.BAD_METHOD)
T = current.T
db = current.db
s3db = current.s3db
atable = s3db.msg_attachmen... | Custom method to Link a Response to a Mission &/or Human Resource | custom method to link a response to a mission & / or human resource | Question:
What does this function do?
Code:
def deploy_response_select_mission(r, **attr):
message_id = (r.record.message_id if r.record else None)
if ((r.representation not in ('html', 'aadata')) or (not message_id) or (not r.component)):
r.error(405, current.ERROR.BAD_METHOD)
T = current.T
db = current.db
s... |
null | null | null | What does this function do? | def get_language_bidi():
return (gettext.language_dir(translation.get_language()) == 'rtl')
| null | null | null | Override for Django\'s get_language_bidi that\'s aware of more RTL
languages. | pcsd | def get language bidi return gettext language dir translation get language == 'rtl' | 984 | def get_language_bidi():
return (gettext.language_dir(translation.get_language()) == 'rtl')
| Override for Django\'s get_language_bidi that\'s aware of more RTL
languages. | override for djangos get _ language _ bidi thats aware of more rtl languages . | Question:
What does this function do?
Code:
def get_language_bidi():
return (gettext.language_dir(translation.get_language()) == 'rtl')
|
null | null | null | What does this function do? | @with_open_mode('r')
@with_sizes('medium')
def seek_forward_bytewise(f):
f.seek(0, 2)
size = f.tell()
f.seek(0, 0)
for i in xrange(0, (size - 1)):
f.seek(i, 0)
| null | null | null | seek forward one unit at a time | pcsd | @with open mode 'r' @with sizes 'medium' def seek forward bytewise f f seek 0 2 size = f tell f seek 0 0 for i in xrange 0 size - 1 f seek i 0 | 986 | @with_open_mode('r')
@with_sizes('medium')
def seek_forward_bytewise(f):
f.seek(0, 2)
size = f.tell()
f.seek(0, 0)
for i in xrange(0, (size - 1)):
f.seek(i, 0)
| seek forward one unit at a time | seek forward one unit at a time | Question:
What does this function do?
Code:
@with_open_mode('r')
@with_sizes('medium')
def seek_forward_bytewise(f):
f.seek(0, 2)
size = f.tell()
f.seek(0, 0)
for i in xrange(0, (size - 1)):
f.seek(i, 0)
|
null | null | null | What does this function do? | def safe_iterator(node, tag=None):
if (node is None):
return []
if hasattr(node, 'iter'):
return node.iter(tag)
else:
return node.getiterator(tag)
| null | null | null | Return an iterator that is compatible with Python 2.6 | pcsd | def safe iterator node tag=None if node is None return [] if hasattr node 'iter' return node iter tag else return node getiterator tag | 994 | def safe_iterator(node, tag=None):
if (node is None):
return []
if hasattr(node, 'iter'):
return node.iter(tag)
else:
return node.getiterator(tag)
| Return an iterator that is compatible with Python 2.6 | return an iterator that is compatible with python 2 . 6 | Question:
What does this function do?
Code:
def safe_iterator(node, tag=None):
if (node is None):
return []
if hasattr(node, 'iter'):
return node.iter(tag)
else:
return node.getiterator(tag)
|
null | null | null | What does this function do? | def getNewDerivation(elementNode, prefix, sideLength):
return OverhangDerivation(elementNode, prefix)
| null | null | null | Get new derivation. | pcsd | def get New Derivation element Node prefix side Length return Overhang Derivation element Node prefix | 997 | def getNewDerivation(elementNode, prefix, sideLength):
return OverhangDerivation(elementNode, prefix)
| Get new derivation. | get new derivation . | Question:
What does this function do?
Code:
def getNewDerivation(elementNode, prefix, sideLength):
return OverhangDerivation(elementNode, prefix)
|
null | null | null | What does this function do? | def stored_cookie_messages_count(storage, response):
cookie = response.cookies.get(storage.cookie_name)
if ((not cookie) or (cookie['max-age'] == 0)):
return 0
data = storage._decode(cookie.value)
if (not data):
return 0
if (data[(-1)] == CookieStorage.not_finished):
data.pop()
return len(data)
| null | null | null | Return an integer containing the number of messages stored. | pcsd | def stored cookie messages count storage response cookie = response cookies get storage cookie name if not cookie or cookie['max-age'] == 0 return 0 data = storage decode cookie value if not data return 0 if data[ -1 ] == Cookie Storage not finished data pop return len data | 1021 | def stored_cookie_messages_count(storage, response):
cookie = response.cookies.get(storage.cookie_name)
if ((not cookie) or (cookie['max-age'] == 0)):
return 0
data = storage._decode(cookie.value)
if (not data):
return 0
if (data[(-1)] == CookieStorage.not_finished):
data.pop()
return len(data)
| Return an integer containing the number of messages stored. | return an integer containing the number of messages stored . | Question:
What does this function do?
Code:
def stored_cookie_messages_count(storage, response):
cookie = response.cookies.get(storage.cookie_name)
if ((not cookie) or (cookie['max-age'] == 0)):
return 0
data = storage._decode(cookie.value)
if (not data):
return 0
if (data[(-1)] == CookieStorage.not_finishe... |
null | null | null | What does this function do? | def load():
config = load_default()
config.update(load_user())
return config
| null | null | null | Read default and user config files and return them as a dict. | pcsd | def load config = load default config update load user return config | 1027 | def load():
config = load_default()
config.update(load_user())
return config
| Read default and user config files and return them as a dict. | read default and user config files and return them as a dict . | Question:
What does this function do?
Code:
def load():
config = load_default()
config.update(load_user())
return config
|
null | null | null | What does this function do? | def safe_int(val, allow_zero=True):
try:
ret = int(val)
except ValueError:
print(("Sorry, '%s' is not a valid integer." % val))
return False
if ((not allow_zero) and (ret == 0)):
print('Please enter a non-zero integer.')
return False
return ret
| null | null | null | This function converts the six.moves.input values to integers. It handles
invalid entries, and optionally forbids values of zero. | pcsd | def safe int val allow zero=True try ret = int val except Value Error print "Sorry '%s' is not a valid integer " % val return False if not allow zero and ret == 0 print 'Please enter a non-zero integer ' return False return ret | 1043 | def safe_int(val, allow_zero=True):
try:
ret = int(val)
except ValueError:
print(("Sorry, '%s' is not a valid integer." % val))
return False
if ((not allow_zero) and (ret == 0)):
print('Please enter a non-zero integer.')
return False
return ret
| This function converts the six.moves.input values to integers. It handles
invalid entries, and optionally forbids values of zero. | this function converts the six . moves . input values to integers . | Question:
What does this function do?
Code:
def safe_int(val, allow_zero=True):
try:
ret = int(val)
except ValueError:
print(("Sorry, '%s' is not a valid integer." % val))
return False
if ((not allow_zero) and (ret == 0)):
print('Please enter a non-zero integer.')
return False
return ret
|
null | null | null | What does this function do? | def download_and_extract(URL):
if (URL == None):
logger.warning('Please provide URL')
return None
tmpdir = tempfile.mkdtemp()
filename = os.path.basename(URL)
path = ((tmpdir + '/') + filename)
zdata = urllib2.urlopen(URL)
print 'Saving file to disk please wait....'
with open(path, 'wb') as local_file:
loc... | null | null | null | This function takes in a URL for a zip file, extracts it and returns
the temporary path it was extracted to | pcsd | def download and extract URL if URL == None logger warning 'Please provide URL' return None tmpdir = tempfile mkdtemp filename = os path basename URL path = tmpdir + '/' + filename zdata = urllib2 urlopen URL print 'Saving file to disk please wait ' with open path 'wb' as local file local file write zdata read zfile = ... | 1051 | def download_and_extract(URL):
if (URL == None):
logger.warning('Please provide URL')
return None
tmpdir = tempfile.mkdtemp()
filename = os.path.basename(URL)
path = ((tmpdir + '/') + filename)
zdata = urllib2.urlopen(URL)
print 'Saving file to disk please wait....'
with open(path, 'wb') as local_file:
loc... | This function takes in a URL for a zip file, extracts it and returns
the temporary path it was extracted to | this function takes in a url for a zip file , extracts it and returns the temporary path it was extracted to | Question:
What does this function do?
Code:
def download_and_extract(URL):
if (URL == None):
logger.warning('Please provide URL')
return None
tmpdir = tempfile.mkdtemp()
filename = os.path.basename(URL)
path = ((tmpdir + '/') + filename)
zdata = urllib2.urlopen(URL)
print 'Saving file to disk please wait..... |
null | null | null | What does this function do? | def index():
module_name = settings.modules[module].name_nice
response.title = module_name
height = get_vars.get('height', None)
width = get_vars.get('width', None)
toolbar = get_vars.get('toolbar', None)
if (toolbar is None):
toolbar = settings.get_gis_toolbar()
elif (toolbar == '0'):
toolbar = False
else:... | null | null | null | Module\'s Home Page: Show the Main map | pcsd | def index module name = settings modules[module] name nice response title = module name height = get vars get 'height' None width = get vars get 'width' None toolbar = get vars get 'toolbar' None if toolbar is None toolbar = settings get gis toolbar elif toolbar == '0' toolbar = False else toolbar = True collapsed = ge... | 1060 | def index():
module_name = settings.modules[module].name_nice
response.title = module_name
height = get_vars.get('height', None)
width = get_vars.get('width', None)
toolbar = get_vars.get('toolbar', None)
if (toolbar is None):
toolbar = settings.get_gis_toolbar()
elif (toolbar == '0'):
toolbar = False
else:... | Module\'s Home Page: Show the Main map | modules home page : show the main map | Question:
What does this function do?
Code:
def index():
module_name = settings.modules[module].name_nice
response.title = module_name
height = get_vars.get('height', None)
width = get_vars.get('width', None)
toolbar = get_vars.get('toolbar', None)
if (toolbar is None):
toolbar = settings.get_gis_toolbar()
... |
null | null | null | What does this function do? | def abs__file__():
for m in sys.modules.values():
if hasattr(m, '__loader__'):
continue
try:
m.__file__ = os.path.abspath(m.__file__)
except AttributeError:
continue
| null | null | null | Set all module __file__ attribute to an absolute path | pcsd | def abs file for m in sys modules values if hasattr m ' loader ' continue try m file = os path abspath m file except Attribute Error continue | 1069 | def abs__file__():
for m in sys.modules.values():
if hasattr(m, '__loader__'):
continue
try:
m.__file__ = os.path.abspath(m.__file__)
except AttributeError:
continue
| Set all module __file__ attribute to an absolute path | set all module _ _ file _ _ attribute to an absolute path | Question:
What does this function do?
Code:
def abs__file__():
for m in sys.modules.values():
if hasattr(m, '__loader__'):
continue
try:
m.__file__ = os.path.abspath(m.__file__)
except AttributeError:
continue
|
null | null | null | What does this function do? | def _key_press(event, params):
if (event.key == 'left'):
params['pause'] = True
params['frame'] = max((params['frame'] - 1), 0)
elif (event.key == 'right'):
params['pause'] = True
params['frame'] = min((params['frame'] + 1), (len(params['frames']) - 1))
| null | null | null | Function for handling key presses for the animation. | pcsd | def key press event params if event key == 'left' params['pause'] = True params['frame'] = max params['frame'] - 1 0 elif event key == 'right' params['pause'] = True params['frame'] = min params['frame'] + 1 len params['frames'] - 1 | 1076 | def _key_press(event, params):
if (event.key == 'left'):
params['pause'] = True
params['frame'] = max((params['frame'] - 1), 0)
elif (event.key == 'right'):
params['pause'] = True
params['frame'] = min((params['frame'] + 1), (len(params['frames']) - 1))
| Function for handling key presses for the animation. | function for handling key presses for the animation . | Question:
What does this function do?
Code:
def _key_press(event, params):
if (event.key == 'left'):
params['pause'] = True
params['frame'] = max((params['frame'] - 1), 0)
elif (event.key == 'right'):
params['pause'] = True
params['frame'] = min((params['frame'] + 1), (len(params['frames']) - 1))
|
null | null | null | What does this function do? | def wait_for_fun(fun, timeout=900, **kwargs):
start = time.time()
log.debug('Attempting function {0}'.format(fun))
trycount = 0
while True:
trycount += 1
try:
response = fun(**kwargs)
if (not isinstance(response, bool)):
return response
except Exception as exc:
log.debug('Caught exception in wait... | null | null | null | Wait until a function finishes, or times out | pcsd | def wait for fun fun timeout=900 **kwargs start = time time log debug 'Attempting function {0}' format fun trycount = 0 while True trycount += 1 try response = fun **kwargs if not isinstance response bool return response except Exception as exc log debug 'Caught exception in wait for fun {0}' format exc time sleep 1 lo... | 1078 | def wait_for_fun(fun, timeout=900, **kwargs):
start = time.time()
log.debug('Attempting function {0}'.format(fun))
trycount = 0
while True:
trycount += 1
try:
response = fun(**kwargs)
if (not isinstance(response, bool)):
return response
except Exception as exc:
log.debug('Caught exception in wait... | Wait until a function finishes, or times out | wait until a function finishes , or times out | Question:
What does this function do?
Code:
def wait_for_fun(fun, timeout=900, **kwargs):
start = time.time()
log.debug('Attempting function {0}'.format(fun))
trycount = 0
while True:
trycount += 1
try:
response = fun(**kwargs)
if (not isinstance(response, bool)):
return response
except Exception... |
null | null | null | What does this function do? | def _createEncoder():
encoder = MultiEncoder()
encoder.addMultipleEncoders({'timestamp': dict(fieldname='timestamp', type='DateEncoder', timeOfDay=(5, 5), forced=True), 'attendeeCount': dict(fieldname='attendeeCount', type='ScalarEncoder', name='attendeeCount', minval=0, maxval=270, clipInput=True, w=5, resolution=10... | null | null | null | Create the encoder instance for our test and return it. | pcsd | def create Encoder encoder = Multi Encoder encoder add Multiple Encoders {'timestamp' dict fieldname='timestamp' type='Date Encoder' time Of Day= 5 5 forced=True 'attendee Count' dict fieldname='attendee Count' type='Scalar Encoder' name='attendee Count' minval=0 maxval=270 clip Input=True w=5 resolution=10 forced=True... | 1079 | def _createEncoder():
encoder = MultiEncoder()
encoder.addMultipleEncoders({'timestamp': dict(fieldname='timestamp', type='DateEncoder', timeOfDay=(5, 5), forced=True), 'attendeeCount': dict(fieldname='attendeeCount', type='ScalarEncoder', name='attendeeCount', minval=0, maxval=270, clipInput=True, w=5, resolution=10... | Create the encoder instance for our test and return it. | create the encoder instance for our test and return it . | Question:
What does this function do?
Code:
def _createEncoder():
encoder = MultiEncoder()
encoder.addMultipleEncoders({'timestamp': dict(fieldname='timestamp', type='DateEncoder', timeOfDay=(5, 5), forced=True), 'attendeeCount': dict(fieldname='attendeeCount', type='ScalarEncoder', name='attendeeCount', minval=0,... |
null | null | null | What does this function do? | def compile_templates(root):
re_start = re_compile('^', re.M)
for (dirpath, dirnames, filenames) in os.walk(root):
filenames = [f for f in filenames if ((not f.startswith('.')) and (not f.endswith('~')) and (not f.startswith('__init__.py')))]
for d in dirnames[:]:
if d.startswith('.'):
dirnames.remove(d)
... | null | null | null | Compiles templates to python code. | pcsd | def compile templates root re start = re compile '^' re M for dirpath dirnames filenames in os walk root filenames = [f for f in filenames if not f startswith ' ' and not f endswith '~' and not f startswith ' init py' ] for d in dirnames[ ] if d startswith ' ' dirnames remove d out = open os path join dirpath ' init py... | 1086 | def compile_templates(root):
re_start = re_compile('^', re.M)
for (dirpath, dirnames, filenames) in os.walk(root):
filenames = [f for f in filenames if ((not f.startswith('.')) and (not f.endswith('~')) and (not f.startswith('__init__.py')))]
for d in dirnames[:]:
if d.startswith('.'):
dirnames.remove(d)
... | Compiles templates to python code. | compiles templates to python code . | Question:
What does this function do?
Code:
def compile_templates(root):
re_start = re_compile('^', re.M)
for (dirpath, dirnames, filenames) in os.walk(root):
filenames = [f for f in filenames if ((not f.startswith('.')) and (not f.endswith('~')) and (not f.startswith('__init__.py')))]
for d in dirnames[:]:
... |
null | null | null | What does this function do? | @treeio_login_required
def ajax_ticket_lookup(request, response_format='html'):
tickets = []
if (request.GET and ('term' in request.GET)):
tickets = Ticket.objects.filter(name__icontains=request.GET['term'])[:10]
return render_to_response('services/ajax_ticket_lookup', {'tickets': tickets}, context_instance=Reques... | null | null | null | Returns a list of matching tickets | pcsd | @treeio login required def ajax ticket lookup request response format='html' tickets = [] if request GET and 'term' in request GET tickets = Ticket objects filter name icontains=request GET['term'] [ 10] return render to response 'services/ajax ticket lookup' {'tickets' tickets} context instance=Request Context request... | 1092 | @treeio_login_required
def ajax_ticket_lookup(request, response_format='html'):
tickets = []
if (request.GET and ('term' in request.GET)):
tickets = Ticket.objects.filter(name__icontains=request.GET['term'])[:10]
return render_to_response('services/ajax_ticket_lookup', {'tickets': tickets}, context_instance=Reques... | Returns a list of matching tickets | returns a list of matching tickets | Question:
What does this function do?
Code:
@treeio_login_required
def ajax_ticket_lookup(request, response_format='html'):
tickets = []
if (request.GET and ('term' in request.GET)):
tickets = Ticket.objects.filter(name__icontains=request.GET['term'])[:10]
return render_to_response('services/ajax_ticket_lookup'... |
null | null | null | What does this function do? | def _htmldecode(text):
if isinstance(text, str):
uchr = chr
else:
def uchr(value):
(((value > 127) and chr(value)) or chr(value))
def entitydecode(match, uchr=uchr):
entity = match.group(1)
if entity.startswith(u'#x'):
return uchr(int(entity[2:], 16))
elif entity.startswith(u'#'):
return uchr(int(... | null | null | null | Decode HTML entities in the given text. | pcsd | def htmldecode text if isinstance text str uchr = chr else def uchr value value > 127 and chr value or chr value def entitydecode match uchr=uchr entity = match group 1 if entity startswith u'#x' return uchr int entity[2 ] 16 elif entity startswith u'#' return uchr int entity[1 ] elif entity in name2codepoint return uc... | 1096 | def _htmldecode(text):
if isinstance(text, str):
uchr = chr
else:
def uchr(value):
(((value > 127) and chr(value)) or chr(value))
def entitydecode(match, uchr=uchr):
entity = match.group(1)
if entity.startswith(u'#x'):
return uchr(int(entity[2:], 16))
elif entity.startswith(u'#'):
return uchr(int(... | Decode HTML entities in the given text. | decode html entities in the given text . | Question:
What does this function do?
Code:
def _htmldecode(text):
if isinstance(text, str):
uchr = chr
else:
def uchr(value):
(((value > 127) and chr(value)) or chr(value))
def entitydecode(match, uchr=uchr):
entity = match.group(1)
if entity.startswith(u'#x'):
return uchr(int(entity[2:], 16))
el... |
null | null | null | What does this function do? | def generate_jwt(service_account_file):
credentials = ServiceAccountCredentials.from_json_keyfile_name(service_account_file)
now = int(time.time())
payload = {'iat': now, 'exp': (now + credentials.MAX_TOKEN_LIFETIME_SECS), 'aud': 'echo.endpoints.sample.google.com', 'iss': 'jwt-client.endpoints.sample.google.com', 's... | null | null | null | Generates a signed JSON Web Token using a Google API Service Account. | pcsd | def generate jwt service account file credentials = Service Account Credentials from json keyfile name service account file now = int time time payload = {'iat' now 'exp' now + credentials MAX TOKEN LIFETIME SECS 'aud' 'echo endpoints sample google com' 'iss' 'jwt-client endpoints sample google com' 'sub' '12345678' 'e... | 1099 | def generate_jwt(service_account_file):
credentials = ServiceAccountCredentials.from_json_keyfile_name(service_account_file)
now = int(time.time())
payload = {'iat': now, 'exp': (now + credentials.MAX_TOKEN_LIFETIME_SECS), 'aud': 'echo.endpoints.sample.google.com', 'iss': 'jwt-client.endpoints.sample.google.com', 's... | Generates a signed JSON Web Token using a Google API Service Account. | generates a signed json web token using a google api service account . | Question:
What does this function do?
Code:
def generate_jwt(service_account_file):
credentials = ServiceAccountCredentials.from_json_keyfile_name(service_account_file)
now = int(time.time())
payload = {'iat': now, 'exp': (now + credentials.MAX_TOKEN_LIFETIME_SECS), 'aud': 'echo.endpoints.sample.google.com', 'iss... |
null | null | null | What does this function do? | def _connection_checker(func):
@functools.wraps(func)
def inner_connection_checker(self, *args, **kwargs):
LOG.debug('in _connection_checker')
for attempts in range(5):
try:
return func(self, *args, **kwargs)
except exception.VolumeBackendAPIException as e:
pattern = re.compile('.*Session id expired... | null | null | null | Decorator to check session has expired or not. | pcsd | def connection checker func @functools wraps func def inner connection checker self *args **kwargs LOG debug 'in connection checker' for attempts in range 5 try return func self *args **kwargs except exception Volume Backend API Exception as e pattern = re compile ' *Session id expired$' matches = pattern match six tex... | 1101 | def _connection_checker(func):
@functools.wraps(func)
def inner_connection_checker(self, *args, **kwargs):
LOG.debug('in _connection_checker')
for attempts in range(5):
try:
return func(self, *args, **kwargs)
except exception.VolumeBackendAPIException as e:
pattern = re.compile('.*Session id expired... | Decorator to check session has expired or not. | decorator to check session has expired or not . | Question:
What does this function do?
Code:
def _connection_checker(func):
@functools.wraps(func)
def inner_connection_checker(self, *args, **kwargs):
LOG.debug('in _connection_checker')
for attempts in range(5):
try:
return func(self, *args, **kwargs)
except exception.VolumeBackendAPIException as e:... |
null | null | null | What does this function do? | def delete_snapshot(kwargs=None, call=None):
if (call != 'function'):
log.error('The delete_snapshot function must be called with -f or --function.')
return False
if ('snapshot_id' not in kwargs):
log.error('A snapshot_id must be specified to delete a snapshot.')
return False
params = {'Action': 'DeleteSnaps... | null | null | null | Delete a snapshot | pcsd | def delete snapshot kwargs=None call=None if call != 'function' log error 'The delete snapshot function must be called with -f or --function ' return False if 'snapshot id' not in kwargs log error 'A snapshot id must be specified to delete a snapshot ' return False params = {'Action' 'Delete Snapshot'} if 'snapshot id'... | 1108 | def delete_snapshot(kwargs=None, call=None):
if (call != 'function'):
log.error('The delete_snapshot function must be called with -f or --function.')
return False
if ('snapshot_id' not in kwargs):
log.error('A snapshot_id must be specified to delete a snapshot.')
return False
params = {'Action': 'DeleteSnaps... | Delete a snapshot | delete a snapshot | Question:
What does this function do?
Code:
def delete_snapshot(kwargs=None, call=None):
if (call != 'function'):
log.error('The delete_snapshot function must be called with -f or --function.')
return False
if ('snapshot_id' not in kwargs):
log.error('A snapshot_id must be specified to delete a snapshot.')
... |
null | null | null | What does this function do? | @with_setup(step_runner_environ)
def test_failing_behave_as_step_fails():
runnable_step = Step.from_string('Given I have a step which calls the "other step fails" step with behave_as')
try:
runnable_step.run(True)
except:
pass
assert runnable_step.failed
| null | null | null | When a step definition calls another (failing) step definition with behave_as, that step should be marked a failure. | pcsd | @with setup step runner environ def test failing behave as step fails runnable step = Step from string 'Given I have a step which calls the "other step fails" step with behave as' try runnable step run True except pass assert runnable step failed | 1111 | @with_setup(step_runner_environ)
def test_failing_behave_as_step_fails():
runnable_step = Step.from_string('Given I have a step which calls the "other step fails" step with behave_as')
try:
runnable_step.run(True)
except:
pass
assert runnable_step.failed
| When a step definition calls another (failing) step definition with behave_as, that step should be marked a failure. | when a step definition calls another step definition with behave _ as , that step should be marked a failure . | Question:
What does this function do?
Code:
@with_setup(step_runner_environ)
def test_failing_behave_as_step_fails():
runnable_step = Step.from_string('Given I have a step which calls the "other step fails" step with behave_as')
try:
runnable_step.run(True)
except:
pass
assert runnable_step.failed
|
null | null | null | What does this function do? | def get_service(hass, config, discovery_info=None):
url = '{}:{}'.format(config.get(CONF_HOST), config.get(CONF_PORT))
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
if (username is not None):
auth = (username, password)
else:
auth = None
return KODINotificationService(url, auth)
| null | null | null | Return the notify service. | pcsd | def get service hass config discovery info=None url = '{} {}' format config get CONF HOST config get CONF PORT username = config get CONF USERNAME password = config get CONF PASSWORD if username is not None auth = username password else auth = None return KODI Notification Service url auth | 1114 | def get_service(hass, config, discovery_info=None):
url = '{}:{}'.format(config.get(CONF_HOST), config.get(CONF_PORT))
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
if (username is not None):
auth = (username, password)
else:
auth = None
return KODINotificationService(url, auth)
| Return the notify service. | return the notify service . | Question:
What does this function do?
Code:
def get_service(hass, config, discovery_info=None):
url = '{}:{}'.format(config.get(CONF_HOST), config.get(CONF_PORT))
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
if (username is not None):
auth = (username, password)
else:
auth = Non... |
null | null | null | What does this function do? | def event_return(events):
opts = _get_options({})
opts['skip'] = True
for event in events:
log.trace('Carbon returner received event: {0}'.format(event))
metric_base = event['tag']
saltdata = event['data'].get('data')
_send(saltdata, metric_base, opts)
| null | null | null | Return event data to remote carbon server
Provide a list of events to be stored in carbon | pcsd | def event return events opts = get options {} opts['skip'] = True for event in events log trace 'Carbon returner received event {0}' format event metric base = event['tag'] saltdata = event['data'] get 'data' send saltdata metric base opts | 1118 | def event_return(events):
opts = _get_options({})
opts['skip'] = True
for event in events:
log.trace('Carbon returner received event: {0}'.format(event))
metric_base = event['tag']
saltdata = event['data'].get('data')
_send(saltdata, metric_base, opts)
| Return event data to remote carbon server
Provide a list of events to be stored in carbon | return event data to remote carbon server | Question:
What does this function do?
Code:
def event_return(events):
opts = _get_options({})
opts['skip'] = True
for event in events:
log.trace('Carbon returner received event: {0}'.format(event))
metric_base = event['tag']
saltdata = event['data'].get('data')
_send(saltdata, metric_base, opts)
|
null | null | null | What does this function do? | def get_ranges(headervalue, content_length):
if (not headervalue):
return None
result = []
try:
(bytesunit, byteranges) = headervalue.split(u'=', 1)
except Exception:
return None
if (bytesunit.strip() != u'bytes'):
return None
for brange in byteranges.split(u','):
(start, stop) = [x.strip() for x in bra... | null | null | null | Return a list of ranges from the Range header. If this function returns
an empty list, it indicates no valid range was found. | pcsd | def get ranges headervalue content length if not headervalue return None result = [] try bytesunit byteranges = headervalue split u'=' 1 except Exception return None if bytesunit strip != u'bytes' return None for brange in byteranges split u' ' start stop = [x strip for x in brange split u'-' 1 ] if start if not stop s... | 1122 | def get_ranges(headervalue, content_length):
if (not headervalue):
return None
result = []
try:
(bytesunit, byteranges) = headervalue.split(u'=', 1)
except Exception:
return None
if (bytesunit.strip() != u'bytes'):
return None
for brange in byteranges.split(u','):
(start, stop) = [x.strip() for x in bra... | Return a list of ranges from the Range header. If this function returns
an empty list, it indicates no valid range was found. | return a list of ranges from the range header . | Question:
What does this function do?
Code:
def get_ranges(headervalue, content_length):
if (not headervalue):
return None
result = []
try:
(bytesunit, byteranges) = headervalue.split(u'=', 1)
except Exception:
return None
if (bytesunit.strip() != u'bytes'):
return None
for brange in byteranges.split(u... |
null | null | null | What does this function do? | def get_images_table(meta):
images = Table('images', meta, Column('id', Integer(), primary_key=True, nullable=False), Column('name', String(255)), Column('disk_format', String(20)), Column('container_format', String(20)), Column('size', Integer()), Column('status', String(30), nullable=False), Column('is_public', Bool... | null | null | null | Returns the Table object for the images table that
corresponds to the images table definition of this version. | pcsd | def get images table meta images = Table 'images' meta Column 'id' Integer primary key=True nullable=False Column 'name' String 255 Column 'disk format' String 20 Column 'container format' String 20 Column 'size' Integer Column 'status' String 30 nullable=False Column 'is public' Boolean nullable=False default=False in... | 1125 | def get_images_table(meta):
images = Table('images', meta, Column('id', Integer(), primary_key=True, nullable=False), Column('name', String(255)), Column('disk_format', String(20)), Column('container_format', String(20)), Column('size', Integer()), Column('status', String(30), nullable=False), Column('is_public', Bool... | Returns the Table object for the images table that
corresponds to the images table definition of this version. | returns the table object for the images table that corresponds to the images table definition of this version . | Question:
What does this function do?
Code:
def get_images_table(meta):
images = Table('images', meta, Column('id', Integer(), primary_key=True, nullable=False), Column('name', String(255)), Column('disk_format', String(20)), Column('container_format', String(20)), Column('size', Integer()), Column('status', String... |
null | null | null | What does this function do? | @step((STEP_PREFIX + 'sending email does not work'))
def email_broken(step):
mail.EmailMessage.send = broken_send
| null | null | null | Break email sending | pcsd | @step STEP PREFIX + 'sending email does not work' def email broken step mail Email Message send = broken send | 1126 | @step((STEP_PREFIX + 'sending email does not work'))
def email_broken(step):
mail.EmailMessage.send = broken_send
| Break email sending | break email sending | Question:
What does this function do?
Code:
@step((STEP_PREFIX + 'sending email does not work'))
def email_broken(step):
mail.EmailMessage.send = broken_send
|
null | null | null | What does this function do? | def delete_files_for_obj(sender, **kwargs):
obj = kwargs.pop('instance')
for field_name in sender._meta.get_all_field_names():
if (not hasattr(obj, field_name)):
continue
try:
field_class = sender._meta.get_field(field_name)
except models.FieldDoesNotExist:
continue
field_value = getattr(obj, field_n... | null | null | null | Signal receiver of a model class and instance. Deletes its files. | pcsd | def delete files for obj sender **kwargs obj = kwargs pop 'instance' for field name in sender meta get all field names if not hasattr obj field name continue try field class = sender meta get field field name except models Field Does Not Exist continue field value = getattr obj field name if isinstance field class mode... | 1127 | def delete_files_for_obj(sender, **kwargs):
obj = kwargs.pop('instance')
for field_name in sender._meta.get_all_field_names():
if (not hasattr(obj, field_name)):
continue
try:
field_class = sender._meta.get_field(field_name)
except models.FieldDoesNotExist:
continue
field_value = getattr(obj, field_n... | Signal receiver of a model class and instance. Deletes its files. | signal receiver of a model class and instance . | Question:
What does this function do?
Code:
def delete_files_for_obj(sender, **kwargs):
obj = kwargs.pop('instance')
for field_name in sender._meta.get_all_field_names():
if (not hasattr(obj, field_name)):
continue
try:
field_class = sender._meta.get_field(field_name)
except models.FieldDoesNotExist:
... |
null | null | null | What does this function do? | def run():
_task()
| null | null | null | Mark mobile-compatible apps as compatible for Firefox OS as well. | pcsd | def run task | 1130 | def run():
_task()
| Mark mobile-compatible apps as compatible for Firefox OS as well. | mark mobile - compatible apps as compatible for firefox os as well . | Question:
What does this function do?
Code:
def run():
_task()
|
null | null | null | What does this function do? | def templates_for_host(templates):
if (not isinstance(templates, (list, tuple))):
templates = [templates]
theme_dir = host_theme_path()
host_templates = []
if theme_dir:
for template in templates:
host_templates.append((u'%s/templates/%s' % (theme_dir, template)))
host_templates.append(template)
return ... | null | null | null | Given a template name (or list of them), returns the template names
as a list, with each name prefixed with the device directory
inserted into the front of the list. | pcsd | def templates for host templates if not isinstance templates list tuple templates = [templates] theme dir = host theme path host templates = [] if theme dir for template in templates host templates append u'%s/templates/%s' % theme dir template host templates append template return host templates return templates | 1131 | def templates_for_host(templates):
if (not isinstance(templates, (list, tuple))):
templates = [templates]
theme_dir = host_theme_path()
host_templates = []
if theme_dir:
for template in templates:
host_templates.append((u'%s/templates/%s' % (theme_dir, template)))
host_templates.append(template)
return ... | Given a template name (or list of them), returns the template names
as a list, with each name prefixed with the device directory
inserted into the front of the list. | given a template name , returns the template names as a list , with each name prefixed with the device directory inserted into the front of the list . | Question:
What does this function do?
Code:
def templates_for_host(templates):
if (not isinstance(templates, (list, tuple))):
templates = [templates]
theme_dir = host_theme_path()
host_templates = []
if theme_dir:
for template in templates:
host_templates.append((u'%s/templates/%s' % (theme_dir, template)... |
null | null | null | What does this function do? | def _check_binary_probabilistic_predictions(y_true, y_prob):
check_consistent_length(y_true, y_prob)
labels = np.unique(y_true)
if (len(labels) > 2):
raise ValueError(('Only binary classification is supported. Provided labels %s.' % labels))
if (y_prob.max() > 1):
raise ValueError('y_prob contains values greate... | null | null | null | Check that y_true is binary and y_prob contains valid probabilities | pcsd | def check binary probabilistic predictions y true y prob check consistent length y true y prob labels = np unique y true if len labels > 2 raise Value Error 'Only binary classification is supported Provided labels %s ' % labels if y prob max > 1 raise Value Error 'y prob contains values greater than 1 ' if y prob min <... | 1133 | def _check_binary_probabilistic_predictions(y_true, y_prob):
check_consistent_length(y_true, y_prob)
labels = np.unique(y_true)
if (len(labels) > 2):
raise ValueError(('Only binary classification is supported. Provided labels %s.' % labels))
if (y_prob.max() > 1):
raise ValueError('y_prob contains values greate... | Check that y_true is binary and y_prob contains valid probabilities | check that y _ true is binary and y _ prob contains valid probabilities | Question:
What does this function do?
Code:
def _check_binary_probabilistic_predictions(y_true, y_prob):
check_consistent_length(y_true, y_prob)
labels = np.unique(y_true)
if (len(labels) > 2):
raise ValueError(('Only binary classification is supported. Provided labels %s.' % labels))
if (y_prob.max() > 1):
... |
null | null | null | What does this function do? | def ebSentMessage(err):
err.printTraceback()
reactor.stop()
| null | null | null | Called if the message cannot be sent.
Report the failure to the user and then stop the reactor. | pcsd | def eb Sent Message err err print Traceback reactor stop | 1139 | def ebSentMessage(err):
err.printTraceback()
reactor.stop()
| Called if the message cannot be sent.
Report the failure to the user and then stop the reactor. | called if the message cannot be sent . | Question:
What does this function do?
Code:
def ebSentMessage(err):
err.printTraceback()
reactor.stop()
|
null | null | null | What does this function do? | def get_volume_drivers():
_ensure_loaded('cinder/volume/drivers')
return [DriverInfo(x) for x in interface._volume_register]
| null | null | null | Get a list of all volume drivers. | pcsd | def get volume drivers ensure loaded 'cinder/volume/drivers' return [Driver Info x for x in interface volume register] | 1144 | def get_volume_drivers():
_ensure_loaded('cinder/volume/drivers')
return [DriverInfo(x) for x in interface._volume_register]
| Get a list of all volume drivers. | get a list of all volume drivers . | Question:
What does this function do?
Code:
def get_volume_drivers():
_ensure_loaded('cinder/volume/drivers')
return [DriverInfo(x) for x in interface._volume_register]
|
null | null | null | What does this function do? | @cors_api_view(['POST'], headers=('content-type', 'accept', 'x-fxpay-version'))
@permission_classes((AllowAny,))
def reissue(request):
raw = request.read()
verify = Verify(raw, request.META)
output = verify.check_full()
if (output['status'] != 'expired'):
log.info('Receipt not expired returned: {0}'.format(output... | null | null | null | Reissues an existing receipt, provided from the client. Will only do
so if the receipt is a full receipt and expired. | pcsd | @cors api view ['POST'] headers= 'content-type' 'accept' 'x-fxpay-version' @permission classes Allow Any def reissue request raw = request read verify = Verify raw request META output = verify check full if output['status'] != 'expired' log info 'Receipt not expired returned {0}' format output receipt cef log request r... | 1154 | @cors_api_view(['POST'], headers=('content-type', 'accept', 'x-fxpay-version'))
@permission_classes((AllowAny,))
def reissue(request):
raw = request.read()
verify = Verify(raw, request.META)
output = verify.check_full()
if (output['status'] != 'expired'):
log.info('Receipt not expired returned: {0}'.format(output... | Reissues an existing receipt, provided from the client. Will only do
so if the receipt is a full receipt and expired. | reissues an existing receipt , provided from the client . | Question:
What does this function do?
Code:
@cors_api_view(['POST'], headers=('content-type', 'accept', 'x-fxpay-version'))
@permission_classes((AllowAny,))
def reissue(request):
raw = request.read()
verify = Verify(raw, request.META)
output = verify.check_full()
if (output['status'] != 'expired'):
log.info('R... |
null | null | null | What does this function do? | def metric_cleanup():
try:
nvmlShutdown()
except NVMLError as err:
print 'Error shutting down NVML:', str(err)
return 1
| null | null | null | Clean up the metric module. | pcsd | def metric cleanup try nvml Shutdown except NVML Error as err print 'Error shutting down NVML ' str err return 1 | 1156 | def metric_cleanup():
try:
nvmlShutdown()
except NVMLError as err:
print 'Error shutting down NVML:', str(err)
return 1
| Clean up the metric module. | clean up the metric module . | Question:
What does this function do?
Code:
def metric_cleanup():
try:
nvmlShutdown()
except NVMLError as err:
print 'Error shutting down NVML:', str(err)
return 1
|
null | null | null | What does this function do? | def _mouse_click(event, params):
if (event.inaxes is None):
if (params['butterfly'] or (not params['settings'][0])):
return
ax = params['ax']
ylim = ax.get_ylim()
pos = ax.transData.inverted().transform((event.x, event.y))
if ((pos[0] > 0) or (pos[1] < 0) or (pos[1] > ylim[0])):
return
if (event.butt... | null | null | null | Handle mouse click events. | pcsd | def mouse click event params if event inaxes is None if params['butterfly'] or not params['settings'][0] return ax = params['ax'] ylim = ax get ylim pos = ax trans Data inverted transform event x event y if pos[0] > 0 or pos[1] < 0 or pos[1] > ylim[0] return if event button == 1 params['label click fun'] pos elif event... | 1157 | def _mouse_click(event, params):
if (event.inaxes is None):
if (params['butterfly'] or (not params['settings'][0])):
return
ax = params['ax']
ylim = ax.get_ylim()
pos = ax.transData.inverted().transform((event.x, event.y))
if ((pos[0] > 0) or (pos[1] < 0) or (pos[1] > ylim[0])):
return
if (event.butt... | Handle mouse click events. | handle mouse click events . | Question:
What does this function do?
Code:
def _mouse_click(event, params):
if (event.inaxes is None):
if (params['butterfly'] or (not params['settings'][0])):
return
ax = params['ax']
ylim = ax.get_ylim()
pos = ax.transData.inverted().transform((event.x, event.y))
if ((pos[0] > 0) or (pos[1] < 0) or ... |
null | null | null | What does this function do? | def _getFullPolicyName(policy_item, policy_name, return_full_policy_names, adml_data):
if (policy_name in adm_policy_name_map[return_full_policy_names]):
return adm_policy_name_map[return_full_policy_names][policy_name]
if (return_full_policy_names and ('displayName' in policy_item.attrib)):
fullPolicyName = _get... | null | null | null | helper function to retrieve the full policy name if needed | pcsd | def get Full Policy Name policy item policy name return full policy names adml data if policy name in adm policy name map[return full policy names] return adm policy name map[return full policy names][policy name] if return full policy names and 'display Name' in policy item attrib full Policy Name = get Adml Display N... | 1161 | def _getFullPolicyName(policy_item, policy_name, return_full_policy_names, adml_data):
if (policy_name in adm_policy_name_map[return_full_policy_names]):
return adm_policy_name_map[return_full_policy_names][policy_name]
if (return_full_policy_names and ('displayName' in policy_item.attrib)):
fullPolicyName = _get... | helper function to retrieve the full policy name if needed | helper function to retrieve the full policy name if needed | Question:
What does this function do?
Code:
def _getFullPolicyName(policy_item, policy_name, return_full_policy_names, adml_data):
if (policy_name in adm_policy_name_map[return_full_policy_names]):
return adm_policy_name_map[return_full_policy_names][policy_name]
if (return_full_policy_names and ('displayName' i... |
null | null | null | What does this function do? | def cleanse_setting(key, value):
try:
if HIDDEN_SETTINGS.search(key):
cleansed = CLEANSED_SUBSTITUTE
elif isinstance(value, dict):
cleansed = dict(((k, cleanse_setting(k, v)) for (k, v) in value.items()))
else:
cleansed = value
except TypeError:
cleansed = value
return cleansed
| null | null | null | Cleanse an individual setting key/value of sensitive content.
If the value is a dictionary, recursively cleanse the keys in
that dictionary. | pcsd | def cleanse setting key value try if HIDDEN SETTINGS search key cleansed = CLEANSED SUBSTITUTE elif isinstance value dict cleansed = dict k cleanse setting k v for k v in value items else cleansed = value except Type Error cleansed = value return cleansed | 1164 | def cleanse_setting(key, value):
try:
if HIDDEN_SETTINGS.search(key):
cleansed = CLEANSED_SUBSTITUTE
elif isinstance(value, dict):
cleansed = dict(((k, cleanse_setting(k, v)) for (k, v) in value.items()))
else:
cleansed = value
except TypeError:
cleansed = value
return cleansed
| Cleanse an individual setting key/value of sensitive content.
If the value is a dictionary, recursively cleanse the keys in
that dictionary. | cleanse an individual setting key / value of sensitive content . | Question:
What does this function do?
Code:
def cleanse_setting(key, value):
try:
if HIDDEN_SETTINGS.search(key):
cleansed = CLEANSED_SUBSTITUTE
elif isinstance(value, dict):
cleansed = dict(((k, cleanse_setting(k, v)) for (k, v) in value.items()))
else:
cleansed = value
except TypeError:
cleansed... |
null | null | null | What does this function do? | def get_version_number():
config_parser = ConfigParser.RawConfigParser()
config_file = os.path.join(os.path.dirname(__file__), os.pardir, 'res', 'roboto.cfg')
config_parser.read(config_file)
version_number = config_parser.get('main', 'version')
assert re.match('[0-9]+\\.[0-9]{3}', version_number)
return version_n... | null | null | null | Returns the version number as a string. | pcsd | def get version number config parser = Config Parser Raw Config Parser config file = os path join os path dirname file os pardir 'res' 'roboto cfg' config parser read config file version number = config parser get 'main' 'version' assert re match '[0-9]+\\ [0-9]{3}' version number return version number | 1169 | def get_version_number():
config_parser = ConfigParser.RawConfigParser()
config_file = os.path.join(os.path.dirname(__file__), os.pardir, 'res', 'roboto.cfg')
config_parser.read(config_file)
version_number = config_parser.get('main', 'version')
assert re.match('[0-9]+\\.[0-9]{3}', version_number)
return version_n... | Returns the version number as a string. | returns the version number as a string . | Question:
What does this function do?
Code:
def get_version_number():
config_parser = ConfigParser.RawConfigParser()
config_file = os.path.join(os.path.dirname(__file__), os.pardir, 'res', 'roboto.cfg')
config_parser.read(config_file)
version_number = config_parser.get('main', 'version')
assert re.match('[0-9]+... |
null | null | null | What does this function do? | def DeleteCommitInformation(rebalance):
loc = data_store.DB.Location()
if (not os.path.exists(loc)):
return False
if (not os.path.isdir(loc)):
return False
tempdir = _GetTransactionDirectory(loc, rebalance.id)
tempfile = utils.JoinPath(tempdir, constants.TRANSACTION_FILENAME)
try:
os.unlink(tempfile)
excep... | null | null | null | Remove file with rebalance information. | pcsd | def Delete Commit Information rebalance loc = data store DB Location if not os path exists loc return False if not os path isdir loc return False tempdir = Get Transaction Directory loc rebalance id tempfile = utils Join Path tempdir constants TRANSACTION FILENAME try os unlink tempfile except OS Error pass return True | 1170 | def DeleteCommitInformation(rebalance):
loc = data_store.DB.Location()
if (not os.path.exists(loc)):
return False
if (not os.path.isdir(loc)):
return False
tempdir = _GetTransactionDirectory(loc, rebalance.id)
tempfile = utils.JoinPath(tempdir, constants.TRANSACTION_FILENAME)
try:
os.unlink(tempfile)
excep... | Remove file with rebalance information. | remove file with rebalance information . | Question:
What does this function do?
Code:
def DeleteCommitInformation(rebalance):
loc = data_store.DB.Location()
if (not os.path.exists(loc)):
return False
if (not os.path.isdir(loc)):
return False
tempdir = _GetTransactionDirectory(loc, rebalance.id)
tempfile = utils.JoinPath(tempdir, constants.TRANSACTI... |
null | null | null | What does this function do? | def wait_for_free_port(host, port):
if (not host):
raise ValueError("Host values of '' or None are not allowed.")
for trial in range(50):
try:
check_port(host, port, timeout=0.1)
except IOError:
time.sleep(0.1)
else:
return
raise IOError(('Port %r not free on %r' % (port, host)))
| null | null | null | Wait for the specified port to become free (drop requests). | pcsd | def wait for free port host port if not host raise Value Error "Host values of '' or None are not allowed " for trial in range 50 try check port host port timeout=0 1 except IO Error time sleep 0 1 else return raise IO Error 'Port %r not free on %r' % port host | 1172 | def wait_for_free_port(host, port):
if (not host):
raise ValueError("Host values of '' or None are not allowed.")
for trial in range(50):
try:
check_port(host, port, timeout=0.1)
except IOError:
time.sleep(0.1)
else:
return
raise IOError(('Port %r not free on %r' % (port, host)))
| Wait for the specified port to become free (drop requests). | wait for the specified port to become free . | Question:
What does this function do?
Code:
def wait_for_free_port(host, port):
if (not host):
raise ValueError("Host values of '' or None are not allowed.")
for trial in range(50):
try:
check_port(host, port, timeout=0.1)
except IOError:
time.sleep(0.1)
else:
return
raise IOError(('Port %r not f... |
null | null | null | What does this function do? | def migrate_admission_plugin_facts(facts):
if ('master' in facts):
if ('kube_admission_plugin_config' in facts['master']):
if ('admission_plugin_config' not in facts['master']):
facts['master']['admission_plugin_config'] = dict()
facts['master']['admission_plugin_config'] = merge_facts(facts['master']['adm... | null | null | null | Apply migrations for admission plugin facts | pcsd | def migrate admission plugin facts facts if 'master' in facts if 'kube admission plugin config' in facts['master'] if 'admission plugin config' not in facts['master'] facts['master']['admission plugin config'] = dict facts['master']['admission plugin config'] = merge facts facts['master']['admission plugin config'] fac... | 1177 | def migrate_admission_plugin_facts(facts):
if ('master' in facts):
if ('kube_admission_plugin_config' in facts['master']):
if ('admission_plugin_config' not in facts['master']):
facts['master']['admission_plugin_config'] = dict()
facts['master']['admission_plugin_config'] = merge_facts(facts['master']['adm... | Apply migrations for admission plugin facts | apply migrations for admission plugin facts | Question:
What does this function do?
Code:
def migrate_admission_plugin_facts(facts):
if ('master' in facts):
if ('kube_admission_plugin_config' in facts['master']):
if ('admission_plugin_config' not in facts['master']):
facts['master']['admission_plugin_config'] = dict()
facts['master']['admission_plu... |
null | null | null | What does this function do? | def _is_namespace_visible(context, namespace, status=None):
if context.is_admin:
return True
if (namespace['owner'] is None):
return True
if ('visibility' in namespace):
if (namespace['visibility'] == 'public'):
return True
if (context.owner is not None):
if (context.owner == namespace['owner']):
retu... | null | null | null | Return True if the namespace is visible in this context. | pcsd | def is namespace visible context namespace status=None if context is admin return True if namespace['owner'] is None return True if 'visibility' in namespace if namespace['visibility'] == 'public' return True if context owner is not None if context owner == namespace['owner'] return True return False | 1178 | def _is_namespace_visible(context, namespace, status=None):
if context.is_admin:
return True
if (namespace['owner'] is None):
return True
if ('visibility' in namespace):
if (namespace['visibility'] == 'public'):
return True
if (context.owner is not None):
if (context.owner == namespace['owner']):
retu... | Return True if the namespace is visible in this context. | return true if the namespace is visible in this context . | Question:
What does this function do?
Code:
def _is_namespace_visible(context, namespace, status=None):
if context.is_admin:
return True
if (namespace['owner'] is None):
return True
if ('visibility' in namespace):
if (namespace['visibility'] == 'public'):
return True
if (context.owner is not None):
if... |
null | null | null | What does this function do? | def words(count, common=True):
word_list = (list(COMMON_WORDS) if common else [])
c = len(word_list)
if (count > c):
count -= c
while (count > 0):
c = min(count, len(WORDS))
count -= c
word_list += random.sample(WORDS, c)
else:
word_list = word_list[:count]
return ' '.join(word_list)
| null | null | null | Returns a string of `count` lorem ipsum words separated by a single space.
If `common` is True, then the first 19 words will be the standard
\'lorem ipsum\' words. Otherwise, all words will be selected randomly. | pcsd | def words count common=True word list = list COMMON WORDS if common else [] c = len word list if count > c count -= c while count > 0 c = min count len WORDS count -= c word list += random sample WORDS c else word list = word list[ count] return ' ' join word list | 1180 | def words(count, common=True):
word_list = (list(COMMON_WORDS) if common else [])
c = len(word_list)
if (count > c):
count -= c
while (count > 0):
c = min(count, len(WORDS))
count -= c
word_list += random.sample(WORDS, c)
else:
word_list = word_list[:count]
return ' '.join(word_list)
| Returns a string of `count` lorem ipsum words separated by a single space.
If `common` is True, then the first 19 words will be the standard
\'lorem ipsum\' words. Otherwise, all words will be selected randomly. | returns a string of count lorem ipsum words separated by a single space . | Question:
What does this function do?
Code:
def words(count, common=True):
word_list = (list(COMMON_WORDS) if common else [])
c = len(word_list)
if (count > c):
count -= c
while (count > 0):
c = min(count, len(WORDS))
count -= c
word_list += random.sample(WORDS, c)
else:
word_list = word_list[:cou... |
null | null | null | What does this function do? | @hgcommand
def sync(ui, repo, **opts):
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
if (not opts['local']):
if hg_incoming(ui, repo):
err = hg_pull(ui, repo, update=True)
else:
err = hg_update(ui, repo)
if err:
return err
sync_changes(ui, repo)
| null | null | null | synchronize with remote repository
Incorporates recent changes from the remote repository
into the local repository. | pcsd | @hgcommand def sync ui repo **opts if codereview disabled raise hg util Abort codereview disabled if not opts['local'] if hg incoming ui repo err = hg pull ui repo update=True else err = hg update ui repo if err return err sync changes ui repo | 1183 | @hgcommand
def sync(ui, repo, **opts):
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
if (not opts['local']):
if hg_incoming(ui, repo):
err = hg_pull(ui, repo, update=True)
else:
err = hg_update(ui, repo)
if err:
return err
sync_changes(ui, repo)
| synchronize with remote repository
Incorporates recent changes from the remote repository
into the local repository. | synchronize with remote repository | Question:
What does this function do?
Code:
@hgcommand
def sync(ui, repo, **opts):
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
if (not opts['local']):
if hg_incoming(ui, repo):
err = hg_pull(ui, repo, update=True)
else:
err = hg_update(ui, repo)
if err:
return err
sync_change... |
null | null | null | What does this function do? | def history_remove_completed():
logging.info('Scheduled removal of all completed jobs')
history_db = HistoryDB()
history_db.remove_completed()
history_db.close()
del history_db
| null | null | null | Remove all completed jobs from history | pcsd | def history remove completed logging info 'Scheduled removal of all completed jobs' history db = History DB history db remove completed history db close del history db | 1185 | def history_remove_completed():
logging.info('Scheduled removal of all completed jobs')
history_db = HistoryDB()
history_db.remove_completed()
history_db.close()
del history_db
| Remove all completed jobs from history | remove all completed jobs from history | Question:
What does this function do?
Code:
def history_remove_completed():
logging.info('Scheduled removal of all completed jobs')
history_db = HistoryDB()
history_db.remove_completed()
history_db.close()
del history_db
|
null | null | null | What does this function do? | def DEFINE_multichoice(name, default, choices, help):
CONFIG.AddOption(type_info.MultiChoice(name=name, default=default, choices=choices, description=help))
| null | null | null | Choose multiple options from a list. | pcsd | def DEFINE multichoice name default choices help CONFIG Add Option type info Multi Choice name=name default=default choices=choices description=help | 1191 | def DEFINE_multichoice(name, default, choices, help):
CONFIG.AddOption(type_info.MultiChoice(name=name, default=default, choices=choices, description=help))
| Choose multiple options from a list. | choose multiple options from a list . | Question:
What does this function do?
Code:
def DEFINE_multichoice(name, default, choices, help):
CONFIG.AddOption(type_info.MultiChoice(name=name, default=default, choices=choices, description=help))
|
null | null | null | What does this function do? | def register():
capabilities.register(driver.init_handler, constants.AGENT_TYPE_LINUXBRIDGE)
| null | null | null | Register Linux Bridge capabilities. | pcsd | def register capabilities register driver init handler constants AGENT TYPE LINUXBRIDGE | 1192 | def register():
capabilities.register(driver.init_handler, constants.AGENT_TYPE_LINUXBRIDGE)
| Register Linux Bridge capabilities. | register linux bridge capabilities . | Question:
What does this function do?
Code:
def register():
capabilities.register(driver.init_handler, constants.AGENT_TYPE_LINUXBRIDGE)
|
null | null | null | What does this function do? | def setup_hass_instance(emulated_hue_config):
hass = get_test_home_assistant()
run_coroutine_threadsafe(core_components.async_setup(hass, {core.DOMAIN: {}}), hass.loop).result()
bootstrap.setup_component(hass, http.DOMAIN, {http.DOMAIN: {http.CONF_SERVER_PORT: HTTP_SERVER_PORT}})
bootstrap.setup_component(hass, emu... | null | null | null | Set up the Home Assistant instance to test. | pcsd | def setup hass instance emulated hue config hass = get test home assistant run coroutine threadsafe core components async setup hass {core DOMAIN {}} hass loop result bootstrap setup component hass http DOMAIN {http DOMAIN {http CONF SERVER PORT HTTP SERVER PORT}} bootstrap setup component hass emulated hue DOMAIN emul... | 1200 | def setup_hass_instance(emulated_hue_config):
hass = get_test_home_assistant()
run_coroutine_threadsafe(core_components.async_setup(hass, {core.DOMAIN: {}}), hass.loop).result()
bootstrap.setup_component(hass, http.DOMAIN, {http.DOMAIN: {http.CONF_SERVER_PORT: HTTP_SERVER_PORT}})
bootstrap.setup_component(hass, emu... | Set up the Home Assistant instance to test. | set up the home assistant instance to test . | Question:
What does this function do?
Code:
def setup_hass_instance(emulated_hue_config):
hass = get_test_home_assistant()
run_coroutine_threadsafe(core_components.async_setup(hass, {core.DOMAIN: {}}), hass.loop).result()
bootstrap.setup_component(hass, http.DOMAIN, {http.DOMAIN: {http.CONF_SERVER_PORT: HTTP_SERV... |
null | null | null | What does this function do? | def RunInstaller():
try:
os.makedirs(os.path.dirname(config_lib.CONFIG['Installer.logfile']))
except OSError:
pass
handler = logging.FileHandler(config_lib.CONFIG['Installer.logfile'], mode='wb')
handler.setLevel(logging.DEBUG)
logging.getLogger().addHandler(handler)
config_lib.CONFIG.Initialize(filename=flag... | null | null | null | Run all registered installers.
Run all the current installers and then exit the process. | pcsd | def Run Installer try os makedirs os path dirname config lib CONFIG['Installer logfile'] except OS Error pass handler = logging File Handler config lib CONFIG['Installer logfile'] mode='wb' handler set Level logging DEBUG logging get Logger add Handler handler config lib CONFIG Initialize filename=flags FLAGS config re... | 1208 | def RunInstaller():
try:
os.makedirs(os.path.dirname(config_lib.CONFIG['Installer.logfile']))
except OSError:
pass
handler = logging.FileHandler(config_lib.CONFIG['Installer.logfile'], mode='wb')
handler.setLevel(logging.DEBUG)
logging.getLogger().addHandler(handler)
config_lib.CONFIG.Initialize(filename=flag... | Run all registered installers.
Run all the current installers and then exit the process. | run all registered installers . | Question:
What does this function do?
Code:
def RunInstaller():
try:
os.makedirs(os.path.dirname(config_lib.CONFIG['Installer.logfile']))
except OSError:
pass
handler = logging.FileHandler(config_lib.CONFIG['Installer.logfile'], mode='wb')
handler.setLevel(logging.DEBUG)
logging.getLogger().addHandler(handl... |
null | null | null | What does this function do? | @pytest.mark.parametrize('status, expected', [(usertypes.LoadStatus.success, url.UrlType.success), (usertypes.LoadStatus.success_https, url.UrlType.success_https), (usertypes.LoadStatus.error, url.UrlType.error), (usertypes.LoadStatus.warn, url.UrlType.warn), (usertypes.LoadStatus.loading, url.UrlType.normal), (usertyp... | null | null | null | Test text when status is changed. | pcsd | @pytest mark parametrize 'status expected' [ usertypes Load Status success url Url Type success usertypes Load Status success https url Url Type success https usertypes Load Status error url Url Type error usertypes Load Status warn url Url Type warn usertypes Load Status loading url Url Type normal usertypes Load Stat... | 1214 | @pytest.mark.parametrize('status, expected', [(usertypes.LoadStatus.success, url.UrlType.success), (usertypes.LoadStatus.success_https, url.UrlType.success_https), (usertypes.LoadStatus.error, url.UrlType.error), (usertypes.LoadStatus.warn, url.UrlType.warn), (usertypes.LoadStatus.loading, url.UrlType.normal), (usertyp... | Test text when status is changed. | test text when status is changed . | Question:
What does this function do?
Code:
@pytest.mark.parametrize('status, expected', [(usertypes.LoadStatus.success, url.UrlType.success), (usertypes.LoadStatus.success_https, url.UrlType.success_https), (usertypes.LoadStatus.error, url.UrlType.error), (usertypes.LoadStatus.warn, url.UrlType.warn), (usertypes.Lo... |
null | null | null | What does this function do? | def present(name, acl_type, acl_name='', perms='', recurse=False):
ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''}
_octal = {'r': 4, 'w': 2, 'x': 1, '-': 0}
if (not os.path.exists(name)):
ret['comment'] = '{0} does not exist'.format(name)
ret['result'] = False
return ret
__current_perms = _... | null | null | null | Ensure a Linux ACL is present | pcsd | def present name acl type acl name='' perms='' recurse=False ret = {'name' name 'result' True 'changes' {} 'comment' ''} octal = {'r' 4 'w' 2 'x' 1 '-' 0} if not os path exists name ret['comment'] = '{0} does not exist' format name ret['result'] = False return ret current perms = salt ['acl getfacl'] name if acl type s... | 1217 | def present(name, acl_type, acl_name='', perms='', recurse=False):
ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''}
_octal = {'r': 4, 'w': 2, 'x': 1, '-': 0}
if (not os.path.exists(name)):
ret['comment'] = '{0} does not exist'.format(name)
ret['result'] = False
return ret
__current_perms = _... | Ensure a Linux ACL is present | ensure a linux acl is present | Question:
What does this function do?
Code:
def present(name, acl_type, acl_name='', perms='', recurse=False):
ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''}
_octal = {'r': 4, 'w': 2, 'x': 1, '-': 0}
if (not os.path.exists(name)):
ret['comment'] = '{0} does not exist'.format(name)
ret['res... |
null | null | null | What does this function do? | @login_required
def display_person_edit_name_do(request):
user = request.user
new_first = request.POST['first_name']
new_last = request.POST['last_name']
user.first_name = new_first
user.last_name = new_last
user.save()
return HttpResponseRedirect(('/people/%s' % urllib.quote(user.username)))
| null | null | null | Take the new first name and last name out of the POST.
Jam them into the Django user model. | pcsd | @login required def display person edit name do request user = request user new first = request POST['first name'] new last = request POST['last name'] user first name = new first user last name = new last user save return Http Response Redirect '/people/%s' % urllib quote user username | 1219 | @login_required
def display_person_edit_name_do(request):
user = request.user
new_first = request.POST['first_name']
new_last = request.POST['last_name']
user.first_name = new_first
user.last_name = new_last
user.save()
return HttpResponseRedirect(('/people/%s' % urllib.quote(user.username)))
| Take the new first name and last name out of the POST.
Jam them into the Django user model. | take the new first name and last name out of the post . | Question:
What does this function do?
Code:
@login_required
def display_person_edit_name_do(request):
user = request.user
new_first = request.POST['first_name']
new_last = request.POST['last_name']
user.first_name = new_first
user.last_name = new_last
user.save()
return HttpResponseRedirect(('/people/%s' % ur... |
null | null | null | What does this function do? | def split_stem(sentence):
sentence = re.sub('([a-z])([A-Z])', u'\\1 \\2', sentence)
return sentence.split()
| null | null | null | Splits camel cased sentence into words | pcsd | def split stem sentence sentence = re sub ' [a-z] [A-Z] ' u'\\1 \\2' sentence return sentence split | 1236 | def split_stem(sentence):
sentence = re.sub('([a-z])([A-Z])', u'\\1 \\2', sentence)
return sentence.split()
| Splits camel cased sentence into words | splits camel cased sentence into words | Question:
What does this function do?
Code:
def split_stem(sentence):
sentence = re.sub('([a-z])([A-Z])', u'\\1 \\2', sentence)
return sentence.split()
|
null | null | null | What does this function do? | def insert(query, parameters=None):
global db
success = False
try:
cursor = db.connection.cursor()
if (parameters is None):
cursor.execute(query)
else:
cursor.execute(query, parameters)
db.connection.commit()
success = True
except:
success = False
return success
| null | null | null | Generic insert/create/update query against the loaded database. | pcsd | def insert query parameters=None global db success = False try cursor = db connection cursor if parameters is None cursor execute query else cursor execute query parameters db connection commit success = True except success = False return success | 1245 | def insert(query, parameters=None):
global db
success = False
try:
cursor = db.connection.cursor()
if (parameters is None):
cursor.execute(query)
else:
cursor.execute(query, parameters)
db.connection.commit()
success = True
except:
success = False
return success
| Generic insert/create/update query against the loaded database. | generic insert / create / update query against the loaded database . | Question:
What does this function do?
Code:
def insert(query, parameters=None):
global db
success = False
try:
cursor = db.connection.cursor()
if (parameters is None):
cursor.execute(query)
else:
cursor.execute(query, parameters)
db.connection.commit()
success = True
except:
success = False
re... |
null | null | null | What does this function do? | def distro_release_info():
return _distro.distro_release_info()
| null | null | null | Return a dictionary containing key-value pairs for the information items
from the distro release file data source of the current Linux distribution.
See `distro release file`_ for details about these information items. | pcsd | def distro release info return distro distro release info | 1248 | def distro_release_info():
return _distro.distro_release_info()
| Return a dictionary containing key-value pairs for the information items
from the distro release file data source of the current Linux distribution.
See `distro release file`_ for details about these information items. | return a dictionary containing key - value pairs for the information items from the distro release file data source of the current linux distribution . | Question:
What does this function do?
Code:
def distro_release_info():
return _distro.distro_release_info()
|
null | null | null | What does this function do? | def validate_float(s):
try:
return float(s)
except ValueError:
raise ValueError(('Could not convert "%s" to float' % s))
| null | null | null | convert s to float or raise | pcsd | def validate float s try return float s except Value Error raise Value Error 'Could not convert "%s" to float' % s | 1254 | def validate_float(s):
try:
return float(s)
except ValueError:
raise ValueError(('Could not convert "%s" to float' % s))
| convert s to float or raise | convert s to float or raise | Question:
What does this function do?
Code:
def validate_float(s):
try:
return float(s)
except ValueError:
raise ValueError(('Could not convert "%s" to float' % s))
|
null | null | null | What does this function do? | @library.global_function
def tags_to_text(tags):
return ','.join([t.slug for t in tags])
| null | null | null | Converts a list of tag objects into a comma-separated slug list. | pcsd | @library global function def tags to text tags return ' ' join [t slug for t in tags] | 1260 | @library.global_function
def tags_to_text(tags):
return ','.join([t.slug for t in tags])
| Converts a list of tag objects into a comma-separated slug list. | converts a list of tag objects into a comma - separated slug list . | Question:
What does this function do?
Code:
@library.global_function
def tags_to_text(tags):
return ','.join([t.slug for t in tags])
|
null | null | null | What does this function do? | def _process_wms_service(url, name, type, username, password, wms=None, owner=None, parent=None):
if (wms is None):
wms = WebMapService(url)
try:
base_url = _clean_url(wms.getOperationByName('GetMap').methods['Get']['url'])
if (base_url and (base_url != url)):
url = base_url
wms = WebMapService(base_url)
... | null | null | null | Create a new WMS/OWS service, cascade it if necessary (i.e. if Web Mercator not available) | pcsd | def process wms service url name type username password wms=None owner=None parent=None if wms is None wms = Web Map Service url try base url = clean url wms get Operation By Name 'Get Map' methods['Get']['url'] if base url and base url != url url = base url wms = Web Map Service base url except logger info 'Could not ... | 1261 | def _process_wms_service(url, name, type, username, password, wms=None, owner=None, parent=None):
if (wms is None):
wms = WebMapService(url)
try:
base_url = _clean_url(wms.getOperationByName('GetMap').methods['Get']['url'])
if (base_url and (base_url != url)):
url = base_url
wms = WebMapService(base_url)
... | Create a new WMS/OWS service, cascade it if necessary (i.e. if Web Mercator not available) | create a new wms / ows service , cascade it if necessary | Question:
What does this function do?
Code:
def _process_wms_service(url, name, type, username, password, wms=None, owner=None, parent=None):
if (wms is None):
wms = WebMapService(url)
try:
base_url = _clean_url(wms.getOperationByName('GetMap').methods['Get']['url'])
if (base_url and (base_url != url)):
u... |
null | null | null | What does this function do? | def coerce_core(result, dshape, odo_kwargs=None):
if iscoretype(result):
return result
elif isscalar(dshape):
result = coerce_scalar(result, dshape, odo_kwargs=odo_kwargs)
elif (istabular(dshape) and isrecord(dshape.measure)):
result = into(DataFrame, result, **(odo_kwargs or {}))
elif iscollection(dshape):
... | null | null | null | Coerce data to a core data type. | pcsd | def coerce core result dshape odo kwargs=None if iscoretype result return result elif isscalar dshape result = coerce scalar result dshape odo kwargs=odo kwargs elif istabular dshape and isrecord dshape measure result = into Data Frame result ** odo kwargs or {} elif iscollection dshape dim = dimensions dshape if dim =... | 1267 | def coerce_core(result, dshape, odo_kwargs=None):
if iscoretype(result):
return result
elif isscalar(dshape):
result = coerce_scalar(result, dshape, odo_kwargs=odo_kwargs)
elif (istabular(dshape) and isrecord(dshape.measure)):
result = into(DataFrame, result, **(odo_kwargs or {}))
elif iscollection(dshape):
... | Coerce data to a core data type. | coerce data to a core data type . | Question:
What does this function do?
Code:
def coerce_core(result, dshape, odo_kwargs=None):
if iscoretype(result):
return result
elif isscalar(dshape):
result = coerce_scalar(result, dshape, odo_kwargs=odo_kwargs)
elif (istabular(dshape) and isrecord(dshape.measure)):
result = into(DataFrame, result, **(o... |
null | null | null | What does this function do? | def binArr2int(arr):
from numpy import packbits
tmp2 = packbits(arr.astype(int))
return sum(((val * (256 ** i)) for (i, val) in enumerate(tmp2[::(-1)])))
| null | null | null | Convert a binary array into its (long) integer representation. | pcsd | def bin Arr2int arr from numpy import packbits tmp2 = packbits arr astype int return sum val * 256 ** i for i val in enumerate tmp2[ -1 ] | 1269 | def binArr2int(arr):
from numpy import packbits
tmp2 = packbits(arr.astype(int))
return sum(((val * (256 ** i)) for (i, val) in enumerate(tmp2[::(-1)])))
| Convert a binary array into its (long) integer representation. | convert a binary array into its integer representation . | Question:
What does this function do?
Code:
def binArr2int(arr):
from numpy import packbits
tmp2 = packbits(arr.astype(int))
return sum(((val * (256 ** i)) for (i, val) in enumerate(tmp2[::(-1)])))
|
null | null | null | What does this function do? | def template_funcs():
funcs = {}
for plugin in find_plugins():
if plugin.template_funcs:
funcs.update(plugin.template_funcs)
return funcs
| null | null | null | Get all the template functions declared by plugins as a
dictionary. | pcsd | def template funcs funcs = {} for plugin in find plugins if plugin template funcs funcs update plugin template funcs return funcs | 1271 | def template_funcs():
funcs = {}
for plugin in find_plugins():
if plugin.template_funcs:
funcs.update(plugin.template_funcs)
return funcs
| Get all the template functions declared by plugins as a
dictionary. | get all the template functions declared by plugins as a dictionary . | Question:
What does this function do?
Code:
def template_funcs():
funcs = {}
for plugin in find_plugins():
if plugin.template_funcs:
funcs.update(plugin.template_funcs)
return funcs
|
null | null | null | What does this function do? | def generate_anchors(base_size=16, ratios=[0.5, 1, 2], scales=(2 ** np.arange(3, 6))):
base_anchor = (np.array([1, 1, base_size, base_size]) - 1)
ratio_anchors = _ratio_enum(base_anchor, ratios)
anchors = np.vstack([_scale_enum(ratio_anchors[i, :], scales) for i in range(ratio_anchors.shape[0])])
return anchors
| null | null | null | Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window. | pcsd | def generate anchors base size=16 ratios=[0 5 1 2] scales= 2 ** np arange 3 6 base anchor = np array [1 1 base size base size] - 1 ratio anchors = ratio enum base anchor ratios anchors = np vstack [ scale enum ratio anchors[i ] scales for i in range ratio anchors shape[0] ] return anchors | 1273 | def generate_anchors(base_size=16, ratios=[0.5, 1, 2], scales=(2 ** np.arange(3, 6))):
base_anchor = (np.array([1, 1, base_size, base_size]) - 1)
ratio_anchors = _ratio_enum(base_anchor, ratios)
anchors = np.vstack([_scale_enum(ratio_anchors[i, :], scales) for i in range(ratio_anchors.shape[0])])
return anchors
| Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window. | generate anchor windows by enumerating aspect ratios x scales wrt a reference window . | Question:
What does this function do?
Code:
def generate_anchors(base_size=16, ratios=[0.5, 1, 2], scales=(2 ** np.arange(3, 6))):
base_anchor = (np.array([1, 1, base_size, base_size]) - 1)
ratio_anchors = _ratio_enum(base_anchor, ratios)
anchors = np.vstack([_scale_enum(ratio_anchors[i, :], scales) for i in rang... |
null | null | null | What does this function do? | def _get_cycles(graph_dict, path, visited, result, vertice):
if (vertice in path):
cycle = [vertice]
for node in path[::(-1)]:
if (node == vertice):
break
cycle.insert(0, node)
start_from = min(cycle)
index = cycle.index(start_from)
cycle = (cycle[index:] + cycle[0:index])
if (not (cycle in resul... | null | null | null | recursive function doing the real work for get_cycles | pcsd | def get cycles graph dict path visited result vertice if vertice in path cycle = [vertice] for node in path[ -1 ] if node == vertice break cycle insert 0 node start from = min cycle index = cycle index start from cycle = cycle[index ] + cycle[0 index] if not cycle in result result append cycle return path append vertic... | 1275 | def _get_cycles(graph_dict, path, visited, result, vertice):
if (vertice in path):
cycle = [vertice]
for node in path[::(-1)]:
if (node == vertice):
break
cycle.insert(0, node)
start_from = min(cycle)
index = cycle.index(start_from)
cycle = (cycle[index:] + cycle[0:index])
if (not (cycle in resul... | recursive function doing the real work for get_cycles | recursive function doing the real work for get _ cycles | Question:
What does this function do?
Code:
def _get_cycles(graph_dict, path, visited, result, vertice):
if (vertice in path):
cycle = [vertice]
for node in path[::(-1)]:
if (node == vertice):
break
cycle.insert(0, node)
start_from = min(cycle)
index = cycle.index(start_from)
cycle = (cycle[inde... |
null | null | null | What does this function do? | def cpu_count_physical():
mapping = {}
current_info = {}
with open_binary(('%s/cpuinfo' % get_procfs_path())) as f:
for line in f:
line = line.strip().lower()
if (not line):
if (('physical id' in current_info) and ('cpu cores' in current_info)):
mapping[current_info['physical id']] = current_info['c... | null | null | null | Return the number of physical cores in the system. | pcsd | def cpu count physical mapping = {} current info = {} with open binary '%s/cpuinfo' % get procfs path as f for line in f line = line strip lower if not line if 'physical id' in current info and 'cpu cores' in current info mapping[current info['physical id']] = current info['cpu cores'] current info = {} elif line start... | 1297 | def cpu_count_physical():
mapping = {}
current_info = {}
with open_binary(('%s/cpuinfo' % get_procfs_path())) as f:
for line in f:
line = line.strip().lower()
if (not line):
if (('physical id' in current_info) and ('cpu cores' in current_info)):
mapping[current_info['physical id']] = current_info['c... | Return the number of physical cores in the system. | return the number of physical cores in the system . | Question:
What does this function do?
Code:
def cpu_count_physical():
mapping = {}
current_info = {}
with open_binary(('%s/cpuinfo' % get_procfs_path())) as f:
for line in f:
line = line.strip().lower()
if (not line):
if (('physical id' in current_info) and ('cpu cores' in current_info)):
mapping... |
null | null | null | What does this function do? | def exc_message(exc_info):
exc = exc_info[1]
if (exc is None):
result = exc_info[0]
else:
try:
result = str(exc)
except UnicodeEncodeError:
try:
result = unicode(exc)
except UnicodeError:
result = exc.args[0]
result = force_unicode(result, 'UTF-8')
return xml_safe(result)
| null | null | null | Return the exception\'s message. | pcsd | def exc message exc info exc = exc info[1] if exc is None result = exc info[0] else try result = str exc except Unicode Encode Error try result = unicode exc except Unicode Error result = exc args[0] result = force unicode result 'UTF-8' return xml safe result | 1300 | def exc_message(exc_info):
exc = exc_info[1]
if (exc is None):
result = exc_info[0]
else:
try:
result = str(exc)
except UnicodeEncodeError:
try:
result = unicode(exc)
except UnicodeError:
result = exc.args[0]
result = force_unicode(result, 'UTF-8')
return xml_safe(result)
| Return the exception\'s message. | return the exceptions message . | Question:
What does this function do?
Code:
def exc_message(exc_info):
exc = exc_info[1]
if (exc is None):
result = exc_info[0]
else:
try:
result = str(exc)
except UnicodeEncodeError:
try:
result = unicode(exc)
except UnicodeError:
result = exc.args[0]
result = force_unicode(result, 'UTF-8... |
null | null | null | What does this function do? | @register.inclusion_tag('sponsors/templatetags/featured_sponsor_rotation.html')
def featured_sponsor_rotation():
return {'sponsors': Sponsor.objects.featured()}
| null | null | null | Retrieve featured Sponsors for rotation | pcsd | @register inclusion tag 'sponsors/templatetags/featured sponsor rotation html' def featured sponsor rotation return {'sponsors' Sponsor objects featured } | 1303 | @register.inclusion_tag('sponsors/templatetags/featured_sponsor_rotation.html')
def featured_sponsor_rotation():
return {'sponsors': Sponsor.objects.featured()}
| Retrieve featured Sponsors for rotation | retrieve featured sponsors for rotation | Question:
What does this function do?
Code:
@register.inclusion_tag('sponsors/templatetags/featured_sponsor_rotation.html')
def featured_sponsor_rotation():
return {'sponsors': Sponsor.objects.featured()}
|
null | null | null | What does this function do? | def set_config_defaults():
set_cors_middleware_defaults()
| null | null | null | This method updates all configuration default values. | pcsd | def set config defaults set cors middleware defaults | 1307 | def set_config_defaults():
set_cors_middleware_defaults()
| This method updates all configuration default values. | this method updates all configuration default values . | Question:
What does this function do?
Code:
def set_config_defaults():
set_cors_middleware_defaults()
|
null | null | null | What does this function do? | def get_price_list():
rate = {}
price_list = frappe.db.sql(u'select ip.item_code, ip.buying, ip.selling,\n DCTB DCTB concat(ifnull(cu.symbol,ip.currency), " ", round(ip.price_list_rate,2), " - ", ip.price_list) as price\n DCTB DCTB from `tabItem Price` ip, `tabPrice List` pl, `tabCurrency` cu\n DCTB DCTB where ip.... | null | null | null | Get selling & buying price list of every item | pcsd | def get price list rate = {} price list = frappe db sql u'select ip item code ip buying ip selling DCTB DCTB concat ifnull cu symbol ip currency " " round ip price list rate 2 " - " ip price list as price DCTB DCTB from `tab Item Price` ip `tab Price List` pl `tab Currency` cu DCTB DCTB where ip price list=pl name and ... | 1319 | def get_price_list():
rate = {}
price_list = frappe.db.sql(u'select ip.item_code, ip.buying, ip.selling,\n DCTB DCTB concat(ifnull(cu.symbol,ip.currency), " ", round(ip.price_list_rate,2), " - ", ip.price_list) as price\n DCTB DCTB from `tabItem Price` ip, `tabPrice List` pl, `tabCurrency` cu\n DCTB DCTB where ip.... | Get selling & buying price list of every item | get selling & buying price list of every item | Question:
What does this function do?
Code:
def get_price_list():
rate = {}
price_list = frappe.db.sql(u'select ip.item_code, ip.buying, ip.selling,\n DCTB DCTB concat(ifnull(cu.symbol,ip.currency), " ", round(ip.price_list_rate,2), " - ", ip.price_list) as price\n DCTB DCTB from `tabItem Price` ip, `tabPrice Li... |
null | null | null | What does this function do? | def _add_metaclass(metaclass):
def wrapper(cls):
orig_vars = cls.__dict__.copy()
slots = orig_vars.get('__slots__')
if (slots is not None):
if isinstance(slots, str):
slots = [slots]
for slots_var in slots:
orig_vars.pop(slots_var)
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', No... | null | null | null | Class decorator for creating a class with a metaclass. | pcsd | def add metaclass metaclass def wrapper cls orig vars = cls dict copy slots = orig vars get ' slots ' if slots is not None if isinstance slots str slots = [slots] for slots var in slots orig vars pop slots var orig vars pop ' dict ' None orig vars pop ' weakref ' None return metaclass cls name cls bases orig vars retur... | 1328 | def _add_metaclass(metaclass):
def wrapper(cls):
orig_vars = cls.__dict__.copy()
slots = orig_vars.get('__slots__')
if (slots is not None):
if isinstance(slots, str):
slots = [slots]
for slots_var in slots:
orig_vars.pop(slots_var)
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', No... | Class decorator for creating a class with a metaclass. | class decorator for creating a class with a metaclass . | Question:
What does this function do?
Code:
def _add_metaclass(metaclass):
def wrapper(cls):
orig_vars = cls.__dict__.copy()
slots = orig_vars.get('__slots__')
if (slots is not None):
if isinstance(slots, str):
slots = [slots]
for slots_var in slots:
orig_vars.pop(slots_var)
orig_vars.pop('__d... |
null | null | null | What does this function do? | def summary_str(meta, numeric_ids=False, classification=None, human_readable=False):
user_str = group_str = size_or_dev_str = '?'
symlink_target = None
if meta:
name = meta.path
mode_str = xstat.mode_str(meta.mode)
symlink_target = meta.symlink_target
mtime_secs = xstat.fstime_floor_secs(meta.mtime)
mtime_... | null | null | null | Return a string containing the "ls -l" style listing for meta.
Classification may be "all", "type", or None. | pcsd | def summary str meta numeric ids=False classification=None human readable=False user str = group str = size or dev str = '?' symlink target = None if meta name = meta path mode str = xstat mode str meta mode symlink target = meta symlink target mtime secs = xstat fstime floor secs meta mtime mtime str = time strftime '... | 1329 | def summary_str(meta, numeric_ids=False, classification=None, human_readable=False):
user_str = group_str = size_or_dev_str = '?'
symlink_target = None
if meta:
name = meta.path
mode_str = xstat.mode_str(meta.mode)
symlink_target = meta.symlink_target
mtime_secs = xstat.fstime_floor_secs(meta.mtime)
mtime_... | Return a string containing the "ls -l" style listing for meta.
Classification may be "all", "type", or None. | return a string containing the " ls - l " style listing for meta . | Question:
What does this function do?
Code:
def summary_str(meta, numeric_ids=False, classification=None, human_readable=False):
user_str = group_str = size_or_dev_str = '?'
symlink_target = None
if meta:
name = meta.path
mode_str = xstat.mode_str(meta.mode)
symlink_target = meta.symlink_target
mtime_secs... |
null | null | null | What does this function do? | @query.command()
@click.argument('metrics', nargs=(-1), type=click.Choice(['organization_total_received', 'organization_total_rejected', 'organization_total_blacklisted']))
@click.option('--since', callback=DateTimeParamType())
@click.option('--until', callback=DateTimeParamType())
@configuration
def organizations(metr... | null | null | null | Fetch metrics for organizations. | pcsd | @query command @click argument 'metrics' nargs= -1 type=click Choice ['organization total received' 'organization total rejected' 'organization total blacklisted'] @click option '--since' callback=Date Time Param Type @click option '--until' callback=Date Time Param Type @configuration def organizations metrics since u... | 1335 | @query.command()
@click.argument('metrics', nargs=(-1), type=click.Choice(['organization_total_received', 'organization_total_rejected', 'organization_total_blacklisted']))
@click.option('--since', callback=DateTimeParamType())
@click.option('--until', callback=DateTimeParamType())
@configuration
def organizations(metr... | Fetch metrics for organizations. | fetch metrics for organizations . | Question:
What does this function do?
Code:
@query.command()
@click.argument('metrics', nargs=(-1), type=click.Choice(['organization_total_received', 'organization_total_rejected', 'organization_total_blacklisted']))
@click.option('--since', callback=DateTimeParamType())
@click.option('--until', callback=DateTimePar... |
null | null | null | What does this function do? | @task
@timed
def install_node_prereqs():
if no_prereq_install():
print NO_PREREQ_MESSAGE
return
prereq_cache('Node prereqs', ['package.json'], node_prereqs_installation)
| null | null | null | Installs Node prerequisites | pcsd | @task @timed def install node prereqs if no prereq install print NO PREREQ MESSAGE return prereq cache 'Node prereqs' ['package json'] node prereqs installation | 1342 | @task
@timed
def install_node_prereqs():
if no_prereq_install():
print NO_PREREQ_MESSAGE
return
prereq_cache('Node prereqs', ['package.json'], node_prereqs_installation)
| Installs Node prerequisites | installs node prerequisites | Question:
What does this function do?
Code:
@task
@timed
def install_node_prereqs():
if no_prereq_install():
print NO_PREREQ_MESSAGE
return
prereq_cache('Node prereqs', ['package.json'], node_prereqs_installation)
|
null | null | null | What does this function do? | def asmodule(module):
if isinstance(module, types.ModuleType):
return module
elif isinstance(module, str):
return __import__(module, fromlist=[''])
else:
raise TypeError(type(module))
| null | null | null | Return the module references by `module` name. If `module` is
already an imported module instance, return it as is. | pcsd | def asmodule module if isinstance module types Module Type return module elif isinstance module str return import module fromlist=[''] else raise Type Error type module | 1352 | def asmodule(module):
if isinstance(module, types.ModuleType):
return module
elif isinstance(module, str):
return __import__(module, fromlist=[''])
else:
raise TypeError(type(module))
| Return the module references by `module` name. If `module` is
already an imported module instance, return it as is. | return the module references by module name . | Question:
What does this function do?
Code:
def asmodule(module):
if isinstance(module, types.ModuleType):
return module
elif isinstance(module, str):
return __import__(module, fromlist=[''])
else:
raise TypeError(type(module))
|
null | null | null | What does this function do? | def get_requests(name):
return reduce((lambda memo, obj: (memo + get_rate(('%srequests_%s_count' % (NAME_PREFIX, obj))))), ['DELETE', 'GET', 'POST', 'PUT'], 0)
| null | null | null | Return requests per second | pcsd | def get requests name return reduce lambda memo obj memo + get rate '%srequests %s count' % NAME PREFIX obj ['DELETE' 'GET' 'POST' 'PUT'] 0 | 1359 | def get_requests(name):
return reduce((lambda memo, obj: (memo + get_rate(('%srequests_%s_count' % (NAME_PREFIX, obj))))), ['DELETE', 'GET', 'POST', 'PUT'], 0)
| Return requests per second | return requests per second | Question:
What does this function do?
Code:
def get_requests(name):
return reduce((lambda memo, obj: (memo + get_rate(('%srequests_%s_count' % (NAME_PREFIX, obj))))), ['DELETE', 'GET', 'POST', 'PUT'], 0)
|
null | null | null | What does this function do? | def identity(obj):
return obj
| null | null | null | Returns directly the argument *obj*. | pcsd | def identity obj return obj | 1362 | def identity(obj):
return obj
| Returns directly the argument *obj*. | returns directly the argument * obj * . | Question:
What does this function do?
Code:
def identity(obj):
return obj
|
null | null | null | What does this function do? | def escape(pattern):
s = list(pattern)
alphanum = _alphanum
for i in range(len(pattern)):
c = pattern[i]
if (c not in alphanum):
if (c == '\x00'):
s[i] = '\\000'
else:
s[i] = ('\\' + c)
return pattern[:0].join(s)
| null | null | null | Escape all non-alphanumeric characters in pattern. | pcsd | def escape pattern s = list pattern alphanum = alphanum for i in range len pattern c = pattern[i] if c not in alphanum if c == '\x00' s[i] = '\\000' else s[i] = '\\' + c return pattern[ 0] join s | 1364 | def escape(pattern):
s = list(pattern)
alphanum = _alphanum
for i in range(len(pattern)):
c = pattern[i]
if (c not in alphanum):
if (c == '\x00'):
s[i] = '\\000'
else:
s[i] = ('\\' + c)
return pattern[:0].join(s)
| Escape all non-alphanumeric characters in pattern. | escape all non - alphanumeric characters in pattern . | Question:
What does this function do?
Code:
def escape(pattern):
s = list(pattern)
alphanum = _alphanum
for i in range(len(pattern)):
c = pattern[i]
if (c not in alphanum):
if (c == '\x00'):
s[i] = '\\000'
else:
s[i] = ('\\' + c)
return pattern[:0].join(s)
|
null | null | null | What does this function do? | def vol_service_record(r, **attr):
record = r.record
if (record.type != 2):
return None
T = current.T
db = current.db
settings = current.deployment_settings
ptable = db.pr_person
person_id = record.person_id
person = db((ptable.id == person_id)).select(ptable.pe_id, ptable.first_name, ptable.middle_name, ptab... | null | null | null | Generate a Volunteer Service Record | pcsd | def vol service record r **attr record = r record if record type != 2 return None T = current T db = current db settings = current deployment settings ptable = db pr person person id = record person id person = db ptable id == person id select ptable pe id ptable first name ptable middle name ptable last name ptable co... | 1368 | def vol_service_record(r, **attr):
record = r.record
if (record.type != 2):
return None
T = current.T
db = current.db
settings = current.deployment_settings
ptable = db.pr_person
person_id = record.person_id
person = db((ptable.id == person_id)).select(ptable.pe_id, ptable.first_name, ptable.middle_name, ptab... | Generate a Volunteer Service Record | generate a volunteer service record | Question:
What does this function do?
Code:
def vol_service_record(r, **attr):
record = r.record
if (record.type != 2):
return None
T = current.T
db = current.db
settings = current.deployment_settings
ptable = db.pr_person
person_id = record.person_id
person = db((ptable.id == person_id)).select(ptable.pe_... |
null | null | null | What does this function do? | def detect_encoding(filename):
try:
with open(filename, u'rb') as input_file:
from lib2to3.pgen2 import tokenize as lib2to3_tokenize
encoding = lib2to3_tokenize.detect_encoding(input_file.readline)[0]
with open_with_encoding(filename, encoding) as test_file:
test_file.read()
return encoding
except (Loo... | null | null | null | Return file encoding. | pcsd | def detect encoding filename try with open filename u'rb' as input file from lib2to3 pgen2 import tokenize as lib2to3 tokenize encoding = lib2to3 tokenize detect encoding input file readline [0] with open with encoding filename encoding as test file test file read return encoding except Lookup Error Syntax Error Unicod... | 1373 | def detect_encoding(filename):
try:
with open(filename, u'rb') as input_file:
from lib2to3.pgen2 import tokenize as lib2to3_tokenize
encoding = lib2to3_tokenize.detect_encoding(input_file.readline)[0]
with open_with_encoding(filename, encoding) as test_file:
test_file.read()
return encoding
except (Loo... | Return file encoding. | return file encoding . | Question:
What does this function do?
Code:
def detect_encoding(filename):
try:
with open(filename, u'rb') as input_file:
from lib2to3.pgen2 import tokenize as lib2to3_tokenize
encoding = lib2to3_tokenize.detect_encoding(input_file.readline)[0]
with open_with_encoding(filename, encoding) as test_file:
... |
null | null | null | What does this function do? | def list_folders(service_instance):
return list_objects(service_instance, vim.Folder)
| null | null | null | Returns a list of folders associated with a given service instance.
service_instance
The Service Instance Object from which to obtain folders. | pcsd | def list folders service instance return list objects service instance vim Folder | 1374 | def list_folders(service_instance):
return list_objects(service_instance, vim.Folder)
| Returns a list of folders associated with a given service instance.
service_instance
The Service Instance Object from which to obtain folders. | returns a list of folders associated with a given service instance . | Question:
What does this function do?
Code:
def list_folders(service_instance):
return list_objects(service_instance, vim.Folder)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.