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 split_title_year(title):
match = re.search(u'[\\s(]([12]\\d{3})\\)?$', title)
if match:
title = title[:match.start()].strip()
year = int(match.group(1))
else:
year = None
return (title, year)
| null | null | null | Splits title containing a year into a title, year pair. | pcsd | def split title year title match = re search u'[\\s ] [12]\\d{3} \\ ?$' title if match title = title[ match start ] strip year = int match group 1 else year = None return title year | 1382 | def split_title_year(title):
match = re.search(u'[\\s(]([12]\\d{3})\\)?$', title)
if match:
title = title[:match.start()].strip()
year = int(match.group(1))
else:
year = None
return (title, year)
| Splits title containing a year into a title, year pair. | splits title containing a year into a title , year pair . | Question:
What does this function do?
Code:
def split_title_year(title):
match = re.search(u'[\\s(]([12]\\d{3})\\)?$', title)
if match:
title = title[:match.start()].strip()
year = int(match.group(1))
else:
year = None
return (title, year)
|
null | null | null | What does this function do? | def encode_path(*components):
return (u'/' + u'/'.join((urlquote(x.encode(u'utf-8'), u'').decode(u'ascii') for x in components)))
| null | null | null | Encode the path specified as a list of path components using URL encoding | pcsd | def encode path *components return u'/' + u'/' join urlquote x encode u'utf-8' u'' decode u'ascii' for x in components | 1383 | def encode_path(*components):
return (u'/' + u'/'.join((urlquote(x.encode(u'utf-8'), u'').decode(u'ascii') for x in components)))
| Encode the path specified as a list of path components using URL encoding | encode the path specified as a list of path components using url encoding | Question:
What does this function do?
Code:
def encode_path(*components):
return (u'/' + u'/'.join((urlquote(x.encode(u'utf-8'), u'').decode(u'ascii') for x in components)))
|
null | null | null | What does this function do? | def validate_title(value):
if ((value is None) or (not value.strip())):
raise ValidationValueError('Title cannot be blank.')
value = sanitize.strip_html(value)
if ((value is None) or (not value.strip())):
raise ValidationValueError('Invalid title.')
if (len(value) > 200):
raise ValidationValueError('Title can... | null | null | null | Validator for Node#title. Makes sure that the value exists and is not
above 200 characters. | pcsd | def validate title value if value is None or not value strip raise Validation Value Error 'Title cannot be blank ' value = sanitize strip html value if value is None or not value strip raise Validation Value Error 'Invalid title ' if len value > 200 raise Validation Value Error 'Title cannot exceed 200 characters ' ret... | 1385 | def validate_title(value):
if ((value is None) or (not value.strip())):
raise ValidationValueError('Title cannot be blank.')
value = sanitize.strip_html(value)
if ((value is None) or (not value.strip())):
raise ValidationValueError('Invalid title.')
if (len(value) > 200):
raise ValidationValueError('Title can... | Validator for Node#title. Makes sure that the value exists and is not
above 200 characters. | validator for node # title . | Question:
What does this function do?
Code:
def validate_title(value):
if ((value is None) or (not value.strip())):
raise ValidationValueError('Title cannot be blank.')
value = sanitize.strip_html(value)
if ((value is None) or (not value.strip())):
raise ValidationValueError('Invalid title.')
if (len(value) ... |
null | null | null | What does this function do? | @tasklets.tasklet
def delete_multi_async(blob_keys, **options):
if isinstance(blob_keys, (basestring, BlobKey)):
raise TypeError(('Expected a list, got %r' % (blob_key,)))
rpc = blobstore.create_rpc(**options)
(yield blobstore.delete_async(blob_keys, rpc=rpc))
| null | null | null | Async version of delete_multi(). | pcsd | @tasklets tasklet def delete multi async blob keys **options if isinstance blob keys basestring Blob Key raise Type Error 'Expected a list got %r' % blob key rpc = blobstore create rpc **options yield blobstore delete async blob keys rpc=rpc | 1392 | @tasklets.tasklet
def delete_multi_async(blob_keys, **options):
if isinstance(blob_keys, (basestring, BlobKey)):
raise TypeError(('Expected a list, got %r' % (blob_key,)))
rpc = blobstore.create_rpc(**options)
(yield blobstore.delete_async(blob_keys, rpc=rpc))
| Async version of delete_multi(). | async version of delete _ multi ( ) . | Question:
What does this function do?
Code:
@tasklets.tasklet
def delete_multi_async(blob_keys, **options):
if isinstance(blob_keys, (basestring, BlobKey)):
raise TypeError(('Expected a list, got %r' % (blob_key,)))
rpc = blobstore.create_rpc(**options)
(yield blobstore.delete_async(blob_keys, rpc=rpc))
|
null | null | null | What does this function do? | def _annotation_ascii_FE_layer(overt, ni, feAbbrevs):
s1 = u''
s2 = u''
i = 0
for (j, k, fename) in overt:
s1 += ((u' ' * (j - i)) + ((u'^' if fename.islower() else u'-') * (k - j)))
short = fename[:(k - j)]
if (len(fename) > len(short)):
r = 0
while (short in feAbbrevs):
if (feAbbrevs[short] == fen... | null | null | null | Helper for _annotation_ascii_FEs(). | pcsd | def annotation ascii FE layer overt ni fe Abbrevs s1 = u'' s2 = u'' i = 0 for j k fename in overt s1 += u' ' * j - i + u'^' if fename islower else u'-' * k - j short = fename[ k - j ] if len fename > len short r = 0 while short in fe Abbrevs if fe Abbrevs[short] == fename break r += 1 short = fename[ k - j - 1 ] + str ... | 1398 | def _annotation_ascii_FE_layer(overt, ni, feAbbrevs):
s1 = u''
s2 = u''
i = 0
for (j, k, fename) in overt:
s1 += ((u' ' * (j - i)) + ((u'^' if fename.islower() else u'-') * (k - j)))
short = fename[:(k - j)]
if (len(fename) > len(short)):
r = 0
while (short in feAbbrevs):
if (feAbbrevs[short] == fen... | Helper for _annotation_ascii_FEs(). | helper for _ annotation _ ascii _ fes ( ) . | Question:
What does this function do?
Code:
def _annotation_ascii_FE_layer(overt, ni, feAbbrevs):
s1 = u''
s2 = u''
i = 0
for (j, k, fename) in overt:
s1 += ((u' ' * (j - i)) + ((u'^' if fename.islower() else u'-') * (k - j)))
short = fename[:(k - j)]
if (len(fename) > len(short)):
r = 0
while (short... |
null | null | null | What does this function do? | def validate_since():
response = cherrypy.serving.response
lastmod = response.headers.get('Last-Modified')
if lastmod:
(status, reason, msg) = _httputil.valid_status(response.status)
request = cherrypy.serving.request
since = request.headers.get('If-Unmodified-Since')
if (since and (since != lastmod)):
if... | null | null | null | Validate the current Last-Modified against If-Modified-Since headers.
If no code has set the Last-Modified response header, then no validation
will be performed. | pcsd | def validate since response = cherrypy serving response lastmod = response headers get 'Last-Modified' if lastmod status reason msg = httputil valid status response status request = cherrypy serving request since = request headers get 'If-Unmodified-Since' if since and since != lastmod if status >= 200 and status <= 29... | 1401 | def validate_since():
response = cherrypy.serving.response
lastmod = response.headers.get('Last-Modified')
if lastmod:
(status, reason, msg) = _httputil.valid_status(response.status)
request = cherrypy.serving.request
since = request.headers.get('If-Unmodified-Since')
if (since and (since != lastmod)):
if... | Validate the current Last-Modified against If-Modified-Since headers.
If no code has set the Last-Modified response header, then no validation
will be performed. | validate the current last - modified against if - modified - since headers . | Question:
What does this function do?
Code:
def validate_since():
response = cherrypy.serving.response
lastmod = response.headers.get('Last-Modified')
if lastmod:
(status, reason, msg) = _httputil.valid_status(response.status)
request = cherrypy.serving.request
since = request.headers.get('If-Unmodified-Sin... |
null | null | null | What does this function do? | def _read_tag_header(fid):
s = fid.read((4 * 4))
if (len(s) == 0):
return None
return Tag(*struct.unpack('>iIii', s))
| null | null | null | Read only the header of a Tag. | pcsd | def read tag header fid s = fid read 4 * 4 if len s == 0 return None return Tag *struct unpack '>i Iii' s | 1402 | def _read_tag_header(fid):
s = fid.read((4 * 4))
if (len(s) == 0):
return None
return Tag(*struct.unpack('>iIii', s))
| Read only the header of a Tag. | read only the header of a tag . | Question:
What does this function do?
Code:
def _read_tag_header(fid):
s = fid.read((4 * 4))
if (len(s) == 0):
return None
return Tag(*struct.unpack('>iIii', s))
|
null | null | null | What does this function do? | def get_unit_changes(request, unit_id):
unit = get_object_or_404(Unit, pk=int(unit_id))
unit.check_acl(request)
return render(request, 'js/changes.html', {'last_changes': unit.change_set.all()[:10], 'last_changes_url': urlencode(unit.translation.get_kwargs())})
| null | null | null | Returns unit\'s recent changes. | pcsd | def get unit changes request unit id unit = get object or 404 Unit pk=int unit id unit check acl request return render request 'js/changes html' {'last changes' unit change set all [ 10] 'last changes url' urlencode unit translation get kwargs } | 1403 | def get_unit_changes(request, unit_id):
unit = get_object_or_404(Unit, pk=int(unit_id))
unit.check_acl(request)
return render(request, 'js/changes.html', {'last_changes': unit.change_set.all()[:10], 'last_changes_url': urlencode(unit.translation.get_kwargs())})
| Returns unit\'s recent changes. | returns units recent changes . | Question:
What does this function do?
Code:
def get_unit_changes(request, unit_id):
unit = get_object_or_404(Unit, pk=int(unit_id))
unit.check_acl(request)
return render(request, 'js/changes.html', {'last_changes': unit.change_set.all()[:10], 'last_changes_url': urlencode(unit.translation.get_kwargs())})
|
null | null | null | What does this function do? | def read_tooltips(gui_name):
dirname = os.path.dirname(__file__)
help_path = os.path.join(dirname, 'help', (gui_name + '.json'))
with open(help_path) as fid:
raw_tooltips = json.load(fid)
format_ = TextWrapper(width=60, fix_sentence_endings=True).fill
return dict(((key, format_(text)) for (key, text) in raw_tool... | null | null | null | Read and format tooltips, return a dict. | pcsd | def read tooltips gui name dirname = os path dirname file help path = os path join dirname 'help' gui name + ' json' with open help path as fid raw tooltips = json load fid format = Text Wrapper width=60 fix sentence endings=True fill return dict key format text for key text in raw tooltips items | 1407 | def read_tooltips(gui_name):
dirname = os.path.dirname(__file__)
help_path = os.path.join(dirname, 'help', (gui_name + '.json'))
with open(help_path) as fid:
raw_tooltips = json.load(fid)
format_ = TextWrapper(width=60, fix_sentence_endings=True).fill
return dict(((key, format_(text)) for (key, text) in raw_tool... | Read and format tooltips, return a dict. | read and format tooltips , return a dict . | Question:
What does this function do?
Code:
def read_tooltips(gui_name):
dirname = os.path.dirname(__file__)
help_path = os.path.join(dirname, 'help', (gui_name + '.json'))
with open(help_path) as fid:
raw_tooltips = json.load(fid)
format_ = TextWrapper(width=60, fix_sentence_endings=True).fill
return dict(((... |
null | null | null | What does this function do? | def find_space(addr_space, procs, mod_base):
if addr_space.is_valid_address(mod_base):
return addr_space
for proc in procs:
ps_ad = proc.get_process_address_space()
if (ps_ad != None):
if ps_ad.is_valid_address(mod_base):
return ps_ad
return None
| null | null | null | Search for an address space (usually looking for a GUI process) | pcsd | def find space addr space procs mod base if addr space is valid address mod base return addr space for proc in procs ps ad = proc get process address space if ps ad != None if ps ad is valid address mod base return ps ad return None | 1409 | def find_space(addr_space, procs, mod_base):
if addr_space.is_valid_address(mod_base):
return addr_space
for proc in procs:
ps_ad = proc.get_process_address_space()
if (ps_ad != None):
if ps_ad.is_valid_address(mod_base):
return ps_ad
return None
| Search for an address space (usually looking for a GUI process) | search for an address space | Question:
What does this function do?
Code:
def find_space(addr_space, procs, mod_base):
if addr_space.is_valid_address(mod_base):
return addr_space
for proc in procs:
ps_ad = proc.get_process_address_space()
if (ps_ad != None):
if ps_ad.is_valid_address(mod_base):
return ps_ad
return None
|
null | null | null | What does this function do? | def align_left(text, length, left_edge='|', right_edge='|', text_length=None, left_padding=2):
if (text_length is None):
text_length = get_text_length(text)
computed_length = (((text_length + left_padding) + get_text_length(left_edge)) + get_text_length(right_edge))
if ((length - computed_length) >= 0):
padding ... | null | null | null | Left align text. | pcsd | def align left text length left edge='|' right edge='|' text length=None left padding=2 if text length is None text length = get text length text computed length = text length + left padding + get text length left edge + get text length right edge if length - computed length >= 0 padding = left padding else padding = 0... | 1413 | def align_left(text, length, left_edge='|', right_edge='|', text_length=None, left_padding=2):
if (text_length is None):
text_length = get_text_length(text)
computed_length = (((text_length + left_padding) + get_text_length(left_edge)) + get_text_length(right_edge))
if ((length - computed_length) >= 0):
padding ... | Left align text. | left align text . | Question:
What does this function do?
Code:
def align_left(text, length, left_edge='|', right_edge='|', text_length=None, left_padding=2):
if (text_length is None):
text_length = get_text_length(text)
computed_length = (((text_length + left_padding) + get_text_length(left_edge)) + get_text_length(right_edge))
i... |
null | null | null | What does this function do? | def label_dataset(dataset_id, label_key, label_value, project_id=None):
(credentials, default_project_id) = google.auth.default(scopes=['https://www.googleapis.com/auth/bigquery'])
session = google.auth.transport.requests.AuthorizedSession(credentials)
if (project_id is None):
project_id = default_project_id
url_... | null | null | null | Add or modify a label on a dataset. | pcsd | def label dataset dataset id label key label value project id=None credentials default project id = google auth default scopes=['https //www googleapis com/auth/bigquery'] session = google auth transport requests Authorized Session credentials if project id is None project id = default project id url format = 'https //... | 1422 | def label_dataset(dataset_id, label_key, label_value, project_id=None):
(credentials, default_project_id) = google.auth.default(scopes=['https://www.googleapis.com/auth/bigquery'])
session = google.auth.transport.requests.AuthorizedSession(credentials)
if (project_id is None):
project_id = default_project_id
url_... | Add or modify a label on a dataset. | add or modify a label on a dataset . | Question:
What does this function do?
Code:
def label_dataset(dataset_id, label_key, label_value, project_id=None):
(credentials, default_project_id) = google.auth.default(scopes=['https://www.googleapis.com/auth/bigquery'])
session = google.auth.transport.requests.AuthorizedSession(credentials)
if (project_id is... |
null | null | null | What does this function do? | def send_all():
EMAIL_BACKEND = getattr(settings, u'MAILER_EMAIL_BACKEND', u'django.core.mail.backends.smtp.EmailBackend')
(acquired, lock) = acquire_lock()
if (not acquired):
return
start_time = time.time()
deferred = 0
sent = 0
try:
connection = None
for message in prioritize():
try:
if (connectio... | null | null | null | Send all eligible messages in the queue. | pcsd | def send all EMAIL BACKEND = getattr settings u'MAILER EMAIL BACKEND' u'django core mail backends smtp Email Backend' acquired lock = acquire lock if not acquired return start time = time time deferred = 0 sent = 0 try connection = None for message in prioritize try if connection is None connection = get connection bac... | 1426 | def send_all():
EMAIL_BACKEND = getattr(settings, u'MAILER_EMAIL_BACKEND', u'django.core.mail.backends.smtp.EmailBackend')
(acquired, lock) = acquire_lock()
if (not acquired):
return
start_time = time.time()
deferred = 0
sent = 0
try:
connection = None
for message in prioritize():
try:
if (connectio... | Send all eligible messages in the queue. | send all eligible messages in the queue . | Question:
What does this function do?
Code:
def send_all():
EMAIL_BACKEND = getattr(settings, u'MAILER_EMAIL_BACKEND', u'django.core.mail.backends.smtp.EmailBackend')
(acquired, lock) = acquire_lock()
if (not acquired):
return
start_time = time.time()
deferred = 0
sent = 0
try:
connection = None
for mes... |
null | null | null | What does this function do? | def delocalize(string):
conv = localeconv()
ts = conv['thousands_sep']
if ts:
string = string.replace(ts, '')
dd = conv['decimal_point']
if dd:
string = string.replace(dd, '.')
return string
| null | null | null | Parses a string as a normalized number according to the locale settings. | pcsd | def delocalize string conv = localeconv ts = conv['thousands sep'] if ts string = string replace ts '' dd = conv['decimal point'] if dd string = string replace dd ' ' return string | 1428 | def delocalize(string):
conv = localeconv()
ts = conv['thousands_sep']
if ts:
string = string.replace(ts, '')
dd = conv['decimal_point']
if dd:
string = string.replace(dd, '.')
return string
| Parses a string as a normalized number according to the locale settings. | parses a string as a normalized number according to the locale settings . | Question:
What does this function do?
Code:
def delocalize(string):
conv = localeconv()
ts = conv['thousands_sep']
if ts:
string = string.replace(ts, '')
dd = conv['decimal_point']
if dd:
string = string.replace(dd, '.')
return string
|
null | null | null | What does this function do? | def function_simple(a, b, c):
return (a, b, c)
| null | null | null | A function which accepts several arguments. | pcsd | def function simple a b c return a b c | 1434 | def function_simple(a, b, c):
return (a, b, c)
| A function which accepts several arguments. | a function which accepts several arguments . | Question:
What does this function do?
Code:
def function_simple(a, b, c):
return (a, b, c)
|
null | null | null | What does this function do? | def set_vm_state_and_notify(context, instance_uuid, service, method, updates, ex, request_spec):
LOG.warning(_LW('Failed to %(service)s_%(method)s: %(ex)s'), {'service': service, 'method': method, 'ex': ex})
vm_state = updates['vm_state']
properties = request_spec.get('instance_properties', {})
notifier = rpc.get_n... | null | null | null | changes VM state and notifies. | pcsd | def set vm state and notify context instance uuid service method updates ex request spec LOG warning LW 'Failed to % service s % method s % ex s' {'service' service 'method' method 'ex' ex} vm state = updates['vm state'] properties = request spec get 'instance properties' {} notifier = rpc get notifier service state = ... | 1435 | def set_vm_state_and_notify(context, instance_uuid, service, method, updates, ex, request_spec):
LOG.warning(_LW('Failed to %(service)s_%(method)s: %(ex)s'), {'service': service, 'method': method, 'ex': ex})
vm_state = updates['vm_state']
properties = request_spec.get('instance_properties', {})
notifier = rpc.get_n... | changes VM state and notifies. | changes vm state and notifies . | Question:
What does this function do?
Code:
def set_vm_state_and_notify(context, instance_uuid, service, method, updates, ex, request_spec):
LOG.warning(_LW('Failed to %(service)s_%(method)s: %(ex)s'), {'service': service, 'method': method, 'ex': ex})
vm_state = updates['vm_state']
properties = request_spec.get('... |
null | null | null | What does this function do? | def _make_image_square(source_image, side=settings.THUMBNAIL_SIZE):
square_image = Image.new('RGBA', (side, side), (255, 255, 255, 0))
width = ((side - source_image.size[0]) / 2)
height = ((side - source_image.size[1]) / 2)
square_image.paste(source_image, (width, height))
return square_image
| null | null | null | Pads a rectangular image with transparency to make it square. | pcsd | def make image square source image side=settings THUMBNAIL SIZE square image = Image new 'RGBA' side side 255 255 255 0 width = side - source image size[0] / 2 height = side - source image size[1] / 2 square image paste source image width height return square image | 1437 | def _make_image_square(source_image, side=settings.THUMBNAIL_SIZE):
square_image = Image.new('RGBA', (side, side), (255, 255, 255, 0))
width = ((side - source_image.size[0]) / 2)
height = ((side - source_image.size[1]) / 2)
square_image.paste(source_image, (width, height))
return square_image
| Pads a rectangular image with transparency to make it square. | pads a rectangular image with transparency to make it square . | Question:
What does this function do?
Code:
def _make_image_square(source_image, side=settings.THUMBNAIL_SIZE):
square_image = Image.new('RGBA', (side, side), (255, 255, 255, 0))
width = ((side - source_image.size[0]) / 2)
height = ((side - source_image.size[1]) / 2)
square_image.paste(source_image, (width, heig... |
null | null | null | What does this function do? | def _length_hint(obj):
try:
return len(obj)
except (AttributeError, TypeError):
try:
get_hint = type(obj).__length_hint__
except AttributeError:
return None
try:
hint = get_hint(obj)
except TypeError:
return None
if ((hint is NotImplemented) or (not isinstance(hint, int_types)) or (hint < 0)):... | null | null | null | Returns the length hint of an object. | pcsd | def length hint obj try return len obj except Attribute Error Type Error try get hint = type obj length hint except Attribute Error return None try hint = get hint obj except Type Error return None if hint is Not Implemented or not isinstance hint int types or hint < 0 return None return hint | 1441 | def _length_hint(obj):
try:
return len(obj)
except (AttributeError, TypeError):
try:
get_hint = type(obj).__length_hint__
except AttributeError:
return None
try:
hint = get_hint(obj)
except TypeError:
return None
if ((hint is NotImplemented) or (not isinstance(hint, int_types)) or (hint < 0)):... | Returns the length hint of an object. | returns the length hint of an object . | Question:
What does this function do?
Code:
def _length_hint(obj):
try:
return len(obj)
except (AttributeError, TypeError):
try:
get_hint = type(obj).__length_hint__
except AttributeError:
return None
try:
hint = get_hint(obj)
except TypeError:
return None
if ((hint is NotImplemented) or (n... |
null | null | null | What does this function do? | def __virtual__():
return ('portage_config' if ('portage_config.get_missing_flags' in __salt__) else False)
| null | null | null | Only load if the portage_config module is available in __salt__ | pcsd | def virtual return 'portage config' if 'portage config get missing flags' in salt else False | 1446 | def __virtual__():
return ('portage_config' if ('portage_config.get_missing_flags' in __salt__) else False)
| Only load if the portage_config module is available in __salt__ | only load if the portage _ config module is available in _ _ salt _ _ | Question:
What does this function do?
Code:
def __virtual__():
return ('portage_config' if ('portage_config.get_missing_flags' in __salt__) else False)
|
null | null | null | What does this function do? | def StructureAttribute(struct_info):
cls_dict = dict(_Structure.__dict__)
cls = type(struct_info.name, _Structure.__bases__, cls_dict)
cls.__module__ = struct_info.namespace
cls.__gtype__ = PGType(struct_info.g_type)
cls._size = struct_info.size
cls._is_gtype_struct = struct_info.is_gtype_struct
for method_info ... | null | null | null | Creates a new struct class. | pcsd | def Structure Attribute struct info cls dict = dict Structure dict cls = type struct info name Structure bases cls dict cls module = struct info namespace cls gtype = PG Type struct info g type cls size = struct info size cls is gtype struct = struct info is gtype struct for method info in struct info get methods add m... | 1450 | def StructureAttribute(struct_info):
cls_dict = dict(_Structure.__dict__)
cls = type(struct_info.name, _Structure.__bases__, cls_dict)
cls.__module__ = struct_info.namespace
cls.__gtype__ = PGType(struct_info.g_type)
cls._size = struct_info.size
cls._is_gtype_struct = struct_info.is_gtype_struct
for method_info ... | Creates a new struct class. | creates a new struct class . | Question:
What does this function do?
Code:
def StructureAttribute(struct_info):
cls_dict = dict(_Structure.__dict__)
cls = type(struct_info.name, _Structure.__bases__, cls_dict)
cls.__module__ = struct_info.namespace
cls.__gtype__ = PGType(struct_info.g_type)
cls._size = struct_info.size
cls._is_gtype_struct ... |
null | null | null | What does this function do? | def _make_logpt(global_RVs, local_RVs, observed_RVs, potentials):
factors = ((([(c * v.logpt) for (v, c) in observed_RVs.items()] + [(c * v.logpt) for (v, c) in global_RVs.items()]) + [(c * v.logpt) for (v, (_, c)) in local_RVs.items()]) + potentials)
logpt = tt.add(*map(tt.sum, factors))
return logpt
| null | null | null | Return expression of log probability. | pcsd | def make logpt global R Vs local R Vs observed R Vs potentials factors = [ c * v logpt for v c in observed R Vs items ] + [ c * v logpt for v c in global R Vs items ] + [ c * v logpt for v c in local R Vs items ] + potentials logpt = tt add *map tt sum factors return logpt | 1462 | def _make_logpt(global_RVs, local_RVs, observed_RVs, potentials):
factors = ((([(c * v.logpt) for (v, c) in observed_RVs.items()] + [(c * v.logpt) for (v, c) in global_RVs.items()]) + [(c * v.logpt) for (v, (_, c)) in local_RVs.items()]) + potentials)
logpt = tt.add(*map(tt.sum, factors))
return logpt
| Return expression of log probability. | return expression of log probability . | Question:
What does this function do?
Code:
def _make_logpt(global_RVs, local_RVs, observed_RVs, potentials):
factors = ((([(c * v.logpt) for (v, c) in observed_RVs.items()] + [(c * v.logpt) for (v, c) in global_RVs.items()]) + [(c * v.logpt) for (v, (_, c)) in local_RVs.items()]) + potentials)
logpt = tt.add(*map... |
null | null | null | What does this function do? | def __clean_tmp(sfn):
if sfn.startswith(os.path.join(tempfile.gettempdir(), salt.utils.files.TEMPFILE_PREFIX)):
all_roots = itertools.chain.from_iterable(six.itervalues(__opts__['file_roots']))
in_roots = any((sfn.startswith(root) for root in all_roots))
if (os.path.exists(sfn) and (not in_roots)):
os.remove(... | null | null | null | Clean out a template temp file | pcsd | def clean tmp sfn if sfn startswith os path join tempfile gettempdir salt utils files TEMPFILE PREFIX all roots = itertools chain from iterable six itervalues opts ['file roots'] in roots = any sfn startswith root for root in all roots if os path exists sfn and not in roots os remove sfn | 1473 | def __clean_tmp(sfn):
if sfn.startswith(os.path.join(tempfile.gettempdir(), salt.utils.files.TEMPFILE_PREFIX)):
all_roots = itertools.chain.from_iterable(six.itervalues(__opts__['file_roots']))
in_roots = any((sfn.startswith(root) for root in all_roots))
if (os.path.exists(sfn) and (not in_roots)):
os.remove(... | Clean out a template temp file | clean out a template temp file | Question:
What does this function do?
Code:
def __clean_tmp(sfn):
if sfn.startswith(os.path.join(tempfile.gettempdir(), salt.utils.files.TEMPFILE_PREFIX)):
all_roots = itertools.chain.from_iterable(six.itervalues(__opts__['file_roots']))
in_roots = any((sfn.startswith(root) for root in all_roots))
if (os.path... |
null | null | null | What does this function do? | @task
def source_tarball():
with cd('/home/vagrant/repos/sympy'):
run('git clean -dfx')
run('./setup.py clean')
run('./setup.py sdist --keep-temp')
run('./setup.py bdist_wininst')
run('mv dist/{win32-orig} dist/{win32}'.format(**tarball_formatter()))
| null | null | null | Build the source tarball | pcsd | @task def source tarball with cd '/home/vagrant/repos/sympy' run 'git clean -dfx' run ' /setup py clean' run ' /setup py sdist --keep-temp' run ' /setup py bdist wininst' run 'mv dist/{win32-orig} dist/{win32}' format **tarball formatter | 1486 | @task
def source_tarball():
with cd('/home/vagrant/repos/sympy'):
run('git clean -dfx')
run('./setup.py clean')
run('./setup.py sdist --keep-temp')
run('./setup.py bdist_wininst')
run('mv dist/{win32-orig} dist/{win32}'.format(**tarball_formatter()))
| Build the source tarball | build the source tarball | Question:
What does this function do?
Code:
@task
def source_tarball():
with cd('/home/vagrant/repos/sympy'):
run('git clean -dfx')
run('./setup.py clean')
run('./setup.py sdist --keep-temp')
run('./setup.py bdist_wininst')
run('mv dist/{win32-orig} dist/{win32}'.format(**tarball_formatter()))
|
null | null | null | What does this function do? | def run_server(application, port):
sock = eventlet.listen(('0.0.0.0', port))
eventlet.wsgi.server(sock, application)
| null | null | null | Run a WSGI server with the given application. | pcsd | def run server application port sock = eventlet listen '0 0 0 0' port eventlet wsgi server sock application | 1503 | def run_server(application, port):
sock = eventlet.listen(('0.0.0.0', port))
eventlet.wsgi.server(sock, application)
| Run a WSGI server with the given application. | run a wsgi server with the given application . | Question:
What does this function do?
Code:
def run_server(application, port):
sock = eventlet.listen(('0.0.0.0', port))
eventlet.wsgi.server(sock, application)
|
null | null | null | What does this function do? | def fpart(x):
return math.modf(x)[0]
| null | null | null | Return fractional part of given number. | pcsd | def fpart x return math modf x [0] | 1507 | def fpart(x):
return math.modf(x)[0]
| Return fractional part of given number. | return fractional part of given number . | Question:
What does this function do?
Code:
def fpart(x):
return math.modf(x)[0]
|
null | null | null | What does this function do? | def load_byte(buf, pos):
end = (pos + 1)
if (end > len(buf)):
raise BadRarFile('cannot load byte')
return (S_BYTE.unpack_from(buf, pos)[0], end)
| null | null | null | Load single byte | pcsd | def load byte buf pos end = pos + 1 if end > len buf raise Bad Rar File 'cannot load byte' return S BYTE unpack from buf pos [0] end | 1508 | def load_byte(buf, pos):
end = (pos + 1)
if (end > len(buf)):
raise BadRarFile('cannot load byte')
return (S_BYTE.unpack_from(buf, pos)[0], end)
| Load single byte | load single byte | Question:
What does this function do?
Code:
def load_byte(buf, pos):
end = (pos + 1)
if (end > len(buf)):
raise BadRarFile('cannot load byte')
return (S_BYTE.unpack_from(buf, pos)[0], end)
|
null | null | null | What does this function do? | def create_instance(context, user_id='fake', project_id='fake', params=None):
flavor = flavors.get_flavor_by_name('m1.tiny')
net_info = model.NetworkInfo([])
info_cache = objects.InstanceInfoCache(network_info=net_info)
inst = objects.Instance(context=context, image_ref=uuids.fake_image_ref, reservation_id='r-faker... | null | null | null | Create a test instance. | pcsd | def create instance context user id='fake' project id='fake' params=None flavor = flavors get flavor by name 'm1 tiny' net info = model Network Info [] info cache = objects Instance Info Cache network info=net info inst = objects Instance context=context image ref=uuids fake image ref reservation id='r-fakeres' user id... | 1511 | def create_instance(context, user_id='fake', project_id='fake', params=None):
flavor = flavors.get_flavor_by_name('m1.tiny')
net_info = model.NetworkInfo([])
info_cache = objects.InstanceInfoCache(network_info=net_info)
inst = objects.Instance(context=context, image_ref=uuids.fake_image_ref, reservation_id='r-faker... | Create a test instance. | create a test instance . | Question:
What does this function do?
Code:
def create_instance(context, user_id='fake', project_id='fake', params=None):
flavor = flavors.get_flavor_by_name('m1.tiny')
net_info = model.NetworkInfo([])
info_cache = objects.InstanceInfoCache(network_info=net_info)
inst = objects.Instance(context=context, image_re... |
null | null | null | What does this function do? | def perceptron_output(weights, bias, x):
return step_function((dot(weights, x) + bias))
| null | null | null | returns 1 if the perceptron \'fires\', 0 if not | pcsd | def perceptron output weights bias x return step function dot weights x + bias | 1530 | def perceptron_output(weights, bias, x):
return step_function((dot(weights, x) + bias))
| returns 1 if the perceptron \'fires\', 0 if not | returns 1 if the perceptron fires , 0 if not | Question:
What does this function do?
Code:
def perceptron_output(weights, bias, x):
return step_function((dot(weights, x) + bias))
|
null | null | null | What does this function do? | def _OnScan(final_cb, client, count, scan_result):
max_count = int(options.options.limit)
(photos, last_key) = scan_result
if (options.options.limit and ((count + len(photos)) > max_count)):
photos = photos[:(max_count - count)]
logging.info(('processing next %d photos' % len(photos)))
count += len(photos)
obj_... | null | null | null | Processes each photo from scan. | pcsd | def On Scan final cb client count scan result max count = int options options limit photos last key = scan result if options options limit and count + len photos > max count photos = photos[ max count - count ] logging info 'processing next %d photos' % len photos count += len photos obj store = Object Store Get Instan... | 1539 | def _OnScan(final_cb, client, count, scan_result):
max_count = int(options.options.limit)
(photos, last_key) = scan_result
if (options.options.limit and ((count + len(photos)) > max_count)):
photos = photos[:(max_count - count)]
logging.info(('processing next %d photos' % len(photos)))
count += len(photos)
obj_... | Processes each photo from scan. | processes each photo from scan . | Question:
What does this function do?
Code:
def _OnScan(final_cb, client, count, scan_result):
max_count = int(options.options.limit)
(photos, last_key) = scan_result
if (options.options.limit and ((count + len(photos)) > max_count)):
photos = photos[:(max_count - count)]
logging.info(('processing next %d phot... |
null | null | null | What does this function do? | def _instance_overrides_method(base, instance, method_name):
bound_method = getattr(instance, method_name)
unbound_method = getattr(base, method_name)
return (six.get_unbound_function(unbound_method) != six.get_method_function(bound_method))
| null | null | null | Returns True if instance overrides a method (method_name)
inherited from base. | pcsd | def instance overrides method base instance method name bound method = getattr instance method name unbound method = getattr base method name return six get unbound function unbound method != six get method function bound method | 1541 | def _instance_overrides_method(base, instance, method_name):
bound_method = getattr(instance, method_name)
unbound_method = getattr(base, method_name)
return (six.get_unbound_function(unbound_method) != six.get_method_function(bound_method))
| Returns True if instance overrides a method (method_name)
inherited from base. | returns true if instance overrides a method inherited from base . | Question:
What does this function do?
Code:
def _instance_overrides_method(base, instance, method_name):
bound_method = getattr(instance, method_name)
unbound_method = getattr(base, method_name)
return (six.get_unbound_function(unbound_method) != six.get_method_function(bound_method))
|
null | null | null | What does this function do? | def _pair_iter(it):
it = iter(it)
prev = next(it)
for el in it:
(yield (prev, el))
prev = el
(yield (prev, None))
| null | null | null | Yields pairs of tokens from the given iterator such that each input
token will appear as the first element in a yielded tuple. The last
pair will have None as its second element. | pcsd | def pair iter it it = iter it prev = next it for el in it yield prev el prev = el yield prev None | 1554 | def _pair_iter(it):
it = iter(it)
prev = next(it)
for el in it:
(yield (prev, el))
prev = el
(yield (prev, None))
| Yields pairs of tokens from the given iterator such that each input
token will appear as the first element in a yielded tuple. The last
pair will have None as its second element. | yields pairs of tokens from the given iterator such that each input token will appear as the first element in a yielded tuple . | Question:
What does this function do?
Code:
def _pair_iter(it):
it = iter(it)
prev = next(it)
for el in it:
(yield (prev, el))
prev = el
(yield (prev, None))
|
null | null | null | What does this function do? | def move(source, destination, use_sudo=False):
func = ((use_sudo and run_as_root) or run)
func('/bin/mv {0} {1}'.format(quote(source), quote(destination)))
| null | null | null | Move a file or directory | pcsd | def move source destination use sudo=False func = use sudo and run as root or run func '/bin/mv {0} {1}' format quote source quote destination | 1573 | def move(source, destination, use_sudo=False):
func = ((use_sudo and run_as_root) or run)
func('/bin/mv {0} {1}'.format(quote(source), quote(destination)))
| Move a file or directory | move a file or directory | Question:
What does this function do?
Code:
def move(source, destination, use_sudo=False):
func = ((use_sudo and run_as_root) or run)
func('/bin/mv {0} {1}'.format(quote(source), quote(destination)))
|
null | null | null | What does this function do? | def libs_from_seqids(seq_ids, delim='_'):
all_libs = set([i.rsplit(delim, 1)[0] for i in seq_ids])
return all_libs
| null | null | null | Returns set of libraries. | pcsd | def libs from seqids seq ids delim=' ' all libs = set [i rsplit delim 1 [0] for i in seq ids] return all libs | 1574 | def libs_from_seqids(seq_ids, delim='_'):
all_libs = set([i.rsplit(delim, 1)[0] for i in seq_ids])
return all_libs
| Returns set of libraries. | returns set of libraries . | Question:
What does this function do?
Code:
def libs_from_seqids(seq_ids, delim='_'):
all_libs = set([i.rsplit(delim, 1)[0] for i in seq_ids])
return all_libs
|
null | null | null | What does this function do? | @pytest.mark.django_db
def test_admin_access(client):
client.login(username='admin', password='admin')
response = client.get(ADMIN_URL)
assert (response.status_code == 200)
| null | null | null | Tests that admin users can access the admin site. | pcsd | @pytest mark django db def test admin access client client login username='admin' password='admin' response = client get ADMIN URL assert response status code == 200 | 1579 | @pytest.mark.django_db
def test_admin_access(client):
client.login(username='admin', password='admin')
response = client.get(ADMIN_URL)
assert (response.status_code == 200)
| Tests that admin users can access the admin site. | tests that admin users can access the admin site . | Question:
What does this function do?
Code:
@pytest.mark.django_db
def test_admin_access(client):
client.login(username='admin', password='admin')
response = client.get(ADMIN_URL)
assert (response.status_code == 200)
|
null | null | null | What does this function do? | def build(config, live_server=False, dump_json=False, dirty=False):
if (not dirty):
log.info(u'Cleaning site directory')
utils.clean_directory(config[u'site_dir'])
else:
log.warning(u"A 'dirty' build is being performed, this will likely lead to inaccurate navigation and other links within your site. This option... | null | null | null | Perform a full site build. | pcsd | def build config live server=False dump json=False dirty=False if not dirty log info u'Cleaning site directory' utils clean directory config[u'site dir'] else log warning u"A 'dirty' build is being performed this will likely lead to inaccurate navigation and other links within your site This option is designed for site... | 1582 | def build(config, live_server=False, dump_json=False, dirty=False):
if (not dirty):
log.info(u'Cleaning site directory')
utils.clean_directory(config[u'site_dir'])
else:
log.warning(u"A 'dirty' build is being performed, this will likely lead to inaccurate navigation and other links within your site. This option... | Perform a full site build. | perform a full site build . | Question:
What does this function do?
Code:
def build(config, live_server=False, dump_json=False, dirty=False):
if (not dirty):
log.info(u'Cleaning site directory')
utils.clean_directory(config[u'site_dir'])
else:
log.warning(u"A 'dirty' build is being performed, this will likely lead to inaccurate navigatio... |
null | null | null | What does this function do? | def _dup_ff_trivial_gcd(f, g, K):
if (not (f or g)):
return ([], [], [])
elif (not f):
return (dup_monic(g, K), [], [dup_LC(g, K)])
elif (not g):
return (dup_monic(f, K), [dup_LC(f, K)], [])
else:
return None
| null | null | null | Handle trivial cases in GCD algorithm over a field. | pcsd | def dup ff trivial gcd f g K if not f or g return [] [] [] elif not f return dup monic g K [] [dup LC g K ] elif not g return dup monic f K [dup LC f K ] [] else return None | 1591 | def _dup_ff_trivial_gcd(f, g, K):
if (not (f or g)):
return ([], [], [])
elif (not f):
return (dup_monic(g, K), [], [dup_LC(g, K)])
elif (not g):
return (dup_monic(f, K), [dup_LC(f, K)], [])
else:
return None
| Handle trivial cases in GCD algorithm over a field. | handle trivial cases in gcd algorithm over a field . | Question:
What does this function do?
Code:
def _dup_ff_trivial_gcd(f, g, K):
if (not (f or g)):
return ([], [], [])
elif (not f):
return (dup_monic(g, K), [], [dup_LC(g, K)])
elif (not g):
return (dup_monic(f, K), [dup_LC(f, K)], [])
else:
return None
|
null | null | null | What does this function do? | def iterable(obj):
try:
len(obj)
except:
return False
return True
| null | null | null | return true if *obj* is iterable | pcsd | def iterable obj try len obj except return False return True | 1596 | def iterable(obj):
try:
len(obj)
except:
return False
return True
| return true if *obj* is iterable | return true if * obj * is iterable | Question:
What does this function do?
Code:
def iterable(obj):
try:
len(obj)
except:
return False
return True
|
null | null | null | What does this function do? | def _get_candidate_names():
global _name_sequence
if (_name_sequence is None):
_once_lock.acquire()
try:
if (_name_sequence is None):
_name_sequence = _RandomNameSequence()
finally:
_once_lock.release()
return _name_sequence
| null | null | null | Common setup sequence for all user-callable interfaces. | pcsd | def get candidate names global name sequence if name sequence is None once lock acquire try if name sequence is None name sequence = Random Name Sequence finally once lock release return name sequence | 1610 | def _get_candidate_names():
global _name_sequence
if (_name_sequence is None):
_once_lock.acquire()
try:
if (_name_sequence is None):
_name_sequence = _RandomNameSequence()
finally:
_once_lock.release()
return _name_sequence
| Common setup sequence for all user-callable interfaces. | common setup sequence for all user - callable interfaces . | Question:
What does this function do?
Code:
def _get_candidate_names():
global _name_sequence
if (_name_sequence is None):
_once_lock.acquire()
try:
if (_name_sequence is None):
_name_sequence = _RandomNameSequence()
finally:
_once_lock.release()
return _name_sequence
|
null | null | null | What does this function do? | def context_dict(revision, ready_for_l10n=False, revision_approved=False):
diff = ''
l10n = revision.document.revisions.filter(is_ready_for_localization=True)
approved = revision.document.revisions.filter(is_approved=True)
if (ready_for_l10n and (l10n.count() > 1)):
old_rev = l10n.order_by('-created')[1]
diff =... | null | null | null | Return a dict that fills in the blanks in KB notification templates. | pcsd | def context dict revision ready for l10n=False revision approved=False diff = '' l10n = revision document revisions filter is ready for localization=True approved = revision document revisions filter is approved=True if ready for l10n and l10n count > 1 old rev = l10n order by '-created' [1] diff = get diff for revisio... | 1611 | def context_dict(revision, ready_for_l10n=False, revision_approved=False):
diff = ''
l10n = revision.document.revisions.filter(is_ready_for_localization=True)
approved = revision.document.revisions.filter(is_approved=True)
if (ready_for_l10n and (l10n.count() > 1)):
old_rev = l10n.order_by('-created')[1]
diff =... | Return a dict that fills in the blanks in KB notification templates. | return a dict that fills in the blanks in kb notification templates . | Question:
What does this function do?
Code:
def context_dict(revision, ready_for_l10n=False, revision_approved=False):
diff = ''
l10n = revision.document.revisions.filter(is_ready_for_localization=True)
approved = revision.document.revisions.filter(is_approved=True)
if (ready_for_l10n and (l10n.count() > 1)):
... |
null | null | null | What does this function do? | def color_dict_to_objects(d, colorspace='hsv'):
result = {}
for (k, v) in d.items():
result[k] = Color(k, v, colorspace)
return result
| null | null | null | Converts color dict to dict of Color objects | pcsd | def color dict to objects d colorspace='hsv' result = {} for k v in d items result[k] = Color k v colorspace return result | 1613 | def color_dict_to_objects(d, colorspace='hsv'):
result = {}
for (k, v) in d.items():
result[k] = Color(k, v, colorspace)
return result
| Converts color dict to dict of Color objects | converts color dict to dict of color objects | Question:
What does this function do?
Code:
def color_dict_to_objects(d, colorspace='hsv'):
result = {}
for (k, v) in d.items():
result[k] = Color(k, v, colorspace)
return result
|
null | null | null | What does this function do? | def AutoLegend(chart):
chart._show_legend = False
labels = []
for series in chart.data:
if (series.label is None):
labels.append('')
else:
labels.append(series.label)
chart._show_legend = True
if chart._show_legend:
chart._legend_labels = labels
| null | null | null | Automatically fill out the legend based on series labels. This will only
fill out the legend if is at least one series with a label. | pcsd | def Auto Legend chart chart show legend = False labels = [] for series in chart data if series label is None labels append '' else labels append series label chart show legend = True if chart show legend chart legend labels = labels | 1620 | def AutoLegend(chart):
chart._show_legend = False
labels = []
for series in chart.data:
if (series.label is None):
labels.append('')
else:
labels.append(series.label)
chart._show_legend = True
if chart._show_legend:
chart._legend_labels = labels
| Automatically fill out the legend based on series labels. This will only
fill out the legend if is at least one series with a label. | automatically fill out the legend based on series labels . | Question:
What does this function do?
Code:
def AutoLegend(chart):
chart._show_legend = False
labels = []
for series in chart.data:
if (series.label is None):
labels.append('')
else:
labels.append(series.label)
chart._show_legend = True
if chart._show_legend:
chart._legend_labels = labels
|
null | null | null | What does this function do? | def append_domain():
grain = {}
if salt.utils.is_proxy():
return grain
if ('append_domain' in __opts__):
grain['append_domain'] = __opts__['append_domain']
return grain
| null | null | null | Return append_domain if set | pcsd | def append domain grain = {} if salt utils is proxy return grain if 'append domain' in opts grain['append domain'] = opts ['append domain'] return grain | 1623 | def append_domain():
grain = {}
if salt.utils.is_proxy():
return grain
if ('append_domain' in __opts__):
grain['append_domain'] = __opts__['append_domain']
return grain
| Return append_domain if set | return append _ domain if set | Question:
What does this function do?
Code:
def append_domain():
grain = {}
if salt.utils.is_proxy():
return grain
if ('append_domain' in __opts__):
grain['append_domain'] = __opts__['append_domain']
return grain
|
null | null | null | What does this function do? | def _status_query(query, hostname, enumerate=None, service=None):
config = _config()
data = None
params = {'hostname': hostname, 'query': query}
ret = {'result': False}
if enumerate:
params['formatoptions'] = 'enumerate'
if service:
params['servicedescription'] = service
if (config['username'] and (config['p... | null | null | null | Send query along to Nagios. | pcsd | def status query query hostname enumerate=None service=None config = config data = None params = {'hostname' hostname 'query' query} ret = {'result' False} if enumerate params['formatoptions'] = 'enumerate' if service params['servicedescription'] = service if config['username'] and config['password'] is not None auth =... | 1625 | def _status_query(query, hostname, enumerate=None, service=None):
config = _config()
data = None
params = {'hostname': hostname, 'query': query}
ret = {'result': False}
if enumerate:
params['formatoptions'] = 'enumerate'
if service:
params['servicedescription'] = service
if (config['username'] and (config['p... | Send query along to Nagios. | send query along to nagios . | Question:
What does this function do?
Code:
def _status_query(query, hostname, enumerate=None, service=None):
config = _config()
data = None
params = {'hostname': hostname, 'query': query}
ret = {'result': False}
if enumerate:
params['formatoptions'] = 'enumerate'
if service:
params['servicedescription'] =... |
null | null | null | What does this function do? | def open_project_with_extensions(path, extensions):
if (not os.path.exists(path)):
raise NinjaIOException(u'The folder does not exist')
valid_extensions = [ext.lower() for ext in extensions if (not ext.startswith(u'-'))]
d = {}
for (root, dirs, files) in os.walk(path, followlinks=True):
for f in files:
ext =... | null | null | null | Return a dict structure containing the info inside a folder.
This function uses the extensions specified by each project. | pcsd | def open project with extensions path extensions if not os path exists path raise Ninja IO Exception u'The folder does not exist' valid extensions = [ext lower for ext in extensions if not ext startswith u'-' ] d = {} for root dirs files in os walk path followlinks=True for f in files ext = os path splitext f lower [ -... | 1626 | def open_project_with_extensions(path, extensions):
if (not os.path.exists(path)):
raise NinjaIOException(u'The folder does not exist')
valid_extensions = [ext.lower() for ext in extensions if (not ext.startswith(u'-'))]
d = {}
for (root, dirs, files) in os.walk(path, followlinks=True):
for f in files:
ext =... | Return a dict structure containing the info inside a folder.
This function uses the extensions specified by each project. | return a dict structure containing the info inside a folder . | Question:
What does this function do?
Code:
def open_project_with_extensions(path, extensions):
if (not os.path.exists(path)):
raise NinjaIOException(u'The folder does not exist')
valid_extensions = [ext.lower() for ext in extensions if (not ext.startswith(u'-'))]
d = {}
for (root, dirs, files) in os.walk(path... |
null | null | null | What does this function do? | def check_package_data(dist, attr, value):
if isinstance(value, dict):
for (k, v) in value.items():
if (not isinstance(k, str)):
break
try:
iter(v)
except TypeError:
break
else:
return
raise DistutilsSetupError((attr + ' must be a dictionary mapping package names to lists of wildcard patte... | null | null | null | Verify that value is a dictionary of package names to glob lists | pcsd | def check package data dist attr value if isinstance value dict for k v in value items if not isinstance k str break try iter v except Type Error break else return raise Distutils Setup Error attr + ' must be a dictionary mapping package names to lists of wildcard patterns' | 1634 | def check_package_data(dist, attr, value):
if isinstance(value, dict):
for (k, v) in value.items():
if (not isinstance(k, str)):
break
try:
iter(v)
except TypeError:
break
else:
return
raise DistutilsSetupError((attr + ' must be a dictionary mapping package names to lists of wildcard patte... | Verify that value is a dictionary of package names to glob lists | verify that value is a dictionary of package names to glob lists | Question:
What does this function do?
Code:
def check_package_data(dist, attr, value):
if isinstance(value, dict):
for (k, v) in value.items():
if (not isinstance(k, str)):
break
try:
iter(v)
except TypeError:
break
else:
return
raise DistutilsSetupError((attr + ' must be a dictionary m... |
null | null | null | What does this function do? | def getFileText(fileName, readMode='r', printWarning=True):
try:
file = open(fileName, readMode)
fileText = file.read()
file.close()
return fileText
except IOError:
if printWarning:
print (('The file ' + fileName) + ' does not exist.')
return ''
| null | null | null | Get the entire text of a file. | pcsd | def get File Text file Name read Mode='r' print Warning=True try file = open file Name read Mode file Text = file read file close return file Text except IO Error if print Warning print 'The file ' + file Name + ' does not exist ' return '' | 1635 | def getFileText(fileName, readMode='r', printWarning=True):
try:
file = open(fileName, readMode)
fileText = file.read()
file.close()
return fileText
except IOError:
if printWarning:
print (('The file ' + fileName) + ' does not exist.')
return ''
| Get the entire text of a file. | get the entire text of a file . | Question:
What does this function do?
Code:
def getFileText(fileName, readMode='r', printWarning=True):
try:
file = open(fileName, readMode)
fileText = file.read()
file.close()
return fileText
except IOError:
if printWarning:
print (('The file ' + fileName) + ' does not exist.')
return ''
|
null | null | null | What does this function do? | def flavor_get_extras(request, flavor_id, raw=False):
flavor = novaclient(request).flavors.get(flavor_id)
extras = flavor.get_keys()
if raw:
return extras
return [FlavorExtraSpec(flavor_id, key, value) for (key, value) in extras.items()]
| null | null | null | Get flavor extra specs. | pcsd | def flavor get extras request flavor id raw=False flavor = novaclient request flavors get flavor id extras = flavor get keys if raw return extras return [Flavor Extra Spec flavor id key value for key value in extras items ] | 1638 | def flavor_get_extras(request, flavor_id, raw=False):
flavor = novaclient(request).flavors.get(flavor_id)
extras = flavor.get_keys()
if raw:
return extras
return [FlavorExtraSpec(flavor_id, key, value) for (key, value) in extras.items()]
| Get flavor extra specs. | get flavor extra specs . | Question:
What does this function do?
Code:
def flavor_get_extras(request, flavor_id, raw=False):
flavor = novaclient(request).flavors.get(flavor_id)
extras = flavor.get_keys()
if raw:
return extras
return [FlavorExtraSpec(flavor_id, key, value) for (key, value) in extras.items()]
|
null | null | null | What does this function do? | def currency(val, symbol=True, grouping=False, international=False):
conv = localeconv()
digits = conv[((international and 'int_frac_digits') or 'frac_digits')]
if (digits == 127):
raise ValueError("Currency formatting is not possible using the 'C' locale.")
s = format(('%%.%if' % digits), abs(val), grouping, mon... | null | null | null | Formats val according to the currency settings
in the current locale. | pcsd | def currency val symbol=True grouping=False international=False conv = localeconv digits = conv[ international and 'int frac digits' or 'frac digits' ] if digits == 127 raise Value Error "Currency formatting is not possible using the 'C' locale " s = format '%% %if' % digits abs val grouping monetary=True s = '<' + s +... | 1643 | def currency(val, symbol=True, grouping=False, international=False):
conv = localeconv()
digits = conv[((international and 'int_frac_digits') or 'frac_digits')]
if (digits == 127):
raise ValueError("Currency formatting is not possible using the 'C' locale.")
s = format(('%%.%if' % digits), abs(val), grouping, mon... | Formats val according to the currency settings
in the current locale. | formats val according to the currency settings in the current locale . | Question:
What does this function do?
Code:
def currency(val, symbol=True, grouping=False, international=False):
conv = localeconv()
digits = conv[((international and 'int_frac_digits') or 'frac_digits')]
if (digits == 127):
raise ValueError("Currency formatting is not possible using the 'C' locale.")
s = form... |
null | null | null | What does this function do? | @with_setup(step_runner_environ)
def test_can_point_undefined_steps():
f = Feature.from_string(FEATURE2)
feature_result = f.run()
scenario_result = feature_result.scenario_results[0]
assert_equals(len(scenario_result.steps_undefined), 2)
assert_equals(len(scenario_result.steps_passed), 1)
assert_equals(scenario_r... | null | null | null | The scenario result has also the undefined steps. | pcsd | @with setup step runner environ def test can point undefined steps f = Feature from string FEATURE2 feature result = f run scenario result = feature result scenario results[0] assert equals len scenario result steps undefined 2 assert equals len scenario result steps passed 1 assert equals scenario result total steps 3... | 1644 | @with_setup(step_runner_environ)
def test_can_point_undefined_steps():
f = Feature.from_string(FEATURE2)
feature_result = f.run()
scenario_result = feature_result.scenario_results[0]
assert_equals(len(scenario_result.steps_undefined), 2)
assert_equals(len(scenario_result.steps_passed), 1)
assert_equals(scenario_r... | The scenario result has also the undefined steps. | the scenario result has also the undefined steps . | Question:
What does this function do?
Code:
@with_setup(step_runner_environ)
def test_can_point_undefined_steps():
f = Feature.from_string(FEATURE2)
feature_result = f.run()
scenario_result = feature_result.scenario_results[0]
assert_equals(len(scenario_result.steps_undefined), 2)
assert_equals(len(scenario_res... |
null | null | null | What does this function do? | @then(u'we see database created')
def step_see_db_created(context):
_expect_exact(context, u'CREATE DATABASE', timeout=2)
| null | null | null | Wait to see create database output. | pcsd | @then u'we see database created' def step see db created context expect exact context u'CREATE DATABASE' timeout=2 | 1652 | @then(u'we see database created')
def step_see_db_created(context):
_expect_exact(context, u'CREATE DATABASE', timeout=2)
| Wait to see create database output. | wait to see create database output . | Question:
What does this function do?
Code:
@then(u'we see database created')
def step_see_db_created(context):
_expect_exact(context, u'CREATE DATABASE', timeout=2)
|
null | null | null | What does this function do? | def version_string_as_tuple(s):
v = _unpack_version(*s.split(u'.'))
if isinstance(v.micro, string_t):
v = version_info_t(v.major, v.minor, *_splitmicro(*v[2:]))
if ((not v.serial) and v.releaselevel and (u'-' in v.releaselevel)):
v = version_info_t(*(list(v[0:3]) + v.releaselevel.split(u'-')))
return v
| null | null | null | Convert version string to version info tuple. | pcsd | def version string as tuple s v = unpack version *s split u' ' if isinstance v micro string t v = version info t v major v minor * splitmicro *v[2 ] if not v serial and v releaselevel and u'-' in v releaselevel v = version info t * list v[0 3] + v releaselevel split u'-' return v | 1655 | def version_string_as_tuple(s):
v = _unpack_version(*s.split(u'.'))
if isinstance(v.micro, string_t):
v = version_info_t(v.major, v.minor, *_splitmicro(*v[2:]))
if ((not v.serial) and v.releaselevel and (u'-' in v.releaselevel)):
v = version_info_t(*(list(v[0:3]) + v.releaselevel.split(u'-')))
return v
| Convert version string to version info tuple. | convert version string to version info tuple . | Question:
What does this function do?
Code:
def version_string_as_tuple(s):
v = _unpack_version(*s.split(u'.'))
if isinstance(v.micro, string_t):
v = version_info_t(v.major, v.minor, *_splitmicro(*v[2:]))
if ((not v.serial) and v.releaselevel and (u'-' in v.releaselevel)):
v = version_info_t(*(list(v[0:3]) + ... |
null | null | null | What does this function do? | def make_XAxis(xaxis_title, xaxis_range):
xaxis = graph_objs.XAxis(title=xaxis_title, range=xaxis_range, showgrid=False, zeroline=False, showline=False, mirror=False, ticks='', showticklabels=False)
return xaxis
| null | null | null | Makes the x-axis for a violin plot. | pcsd | def make X Axis xaxis title xaxis range xaxis = graph objs X Axis title=xaxis title range=xaxis range showgrid=False zeroline=False showline=False mirror=False ticks='' showticklabels=False return xaxis | 1656 | def make_XAxis(xaxis_title, xaxis_range):
xaxis = graph_objs.XAxis(title=xaxis_title, range=xaxis_range, showgrid=False, zeroline=False, showline=False, mirror=False, ticks='', showticklabels=False)
return xaxis
| Makes the x-axis for a violin plot. | makes the x - axis for a violin plot . | Question:
What does this function do?
Code:
def make_XAxis(xaxis_title, xaxis_range):
xaxis = graph_objs.XAxis(title=xaxis_title, range=xaxis_range, showgrid=False, zeroline=False, showline=False, mirror=False, ticks='', showticklabels=False)
return xaxis
|
null | null | null | What does this function do? | def toRoman(n):
if (not (0 < n < 5000)):
raise OutOfRangeError, 'number out of range (must be 1..4999)'
if (int(n) != n):
raise NotIntegerError, 'decimals can not be converted'
result = ''
for (numeral, integer) in romanNumeralMap:
while (n >= integer):
result += numeral
n -= integer
return result
| null | null | null | convert integer to Roman numeral | pcsd | def to Roman n if not 0 < n < 5000 raise Out Of Range Error 'number out of range must be 1 4999 ' if int n != n raise Not Integer Error 'decimals can not be converted' result = '' for numeral integer in roman Numeral Map while n >= integer result += numeral n -= integer return result | 1659 | def toRoman(n):
if (not (0 < n < 5000)):
raise OutOfRangeError, 'number out of range (must be 1..4999)'
if (int(n) != n):
raise NotIntegerError, 'decimals can not be converted'
result = ''
for (numeral, integer) in romanNumeralMap:
while (n >= integer):
result += numeral
n -= integer
return result
| convert integer to Roman numeral | convert integer to roman numeral | Question:
What does this function do?
Code:
def toRoman(n):
if (not (0 < n < 5000)):
raise OutOfRangeError, 'number out of range (must be 1..4999)'
if (int(n) != n):
raise NotIntegerError, 'decimals can not be converted'
result = ''
for (numeral, integer) in romanNumeralMap:
while (n >= integer):
result... |
null | null | null | What does this function do? | def is_installable_dir(path):
if (not os.path.isdir(path)):
return False
setup_py = os.path.join(path, 'setup.py')
if os.path.isfile(setup_py):
return True
return False
| null | null | null | Return True if `path` is a directory containing a setup.py file. | pcsd | def is installable dir path if not os path isdir path return False setup py = os path join path 'setup py' if os path isfile setup py return True return False | 1664 | def is_installable_dir(path):
if (not os.path.isdir(path)):
return False
setup_py = os.path.join(path, 'setup.py')
if os.path.isfile(setup_py):
return True
return False
| Return True if `path` is a directory containing a setup.py file. | return true if path is a directory containing a setup . py file . | Question:
What does this function do?
Code:
def is_installable_dir(path):
if (not os.path.isdir(path)):
return False
setup_py = os.path.join(path, 'setup.py')
if os.path.isfile(setup_py):
return True
return False
|
null | null | null | What does this function do? | def get_value(val_name, default=None, **kwargs):
return BACKEND.get_value(val_name, default, **kwargs)
| null | null | null | Returns a value associated with the request\'s microsite, if present | pcsd | def get value val name default=None **kwargs return BACKEND get value val name default **kwargs | 1674 | def get_value(val_name, default=None, **kwargs):
return BACKEND.get_value(val_name, default, **kwargs)
| Returns a value associated with the request\'s microsite, if present | returns a value associated with the requests microsite , if present | Question:
What does this function do?
Code:
def get_value(val_name, default=None, **kwargs):
return BACKEND.get_value(val_name, default, **kwargs)
|
null | null | null | What does this function do? | @login_required
@require_POST
def reply(request, document_slug, thread_id):
doc = get_document(document_slug, request)
form = ReplyForm(request.POST)
post_preview = None
if form.is_valid():
thread = get_object_or_404(Thread, pk=thread_id, document=doc)
if (not thread.is_locked):
reply_ = form.save(commit=Fal... | null | null | null | Reply to a thread. | pcsd | @login required @require POST def reply request document slug thread id doc = get document document slug request form = Reply Form request POST post preview = None if form is valid thread = get object or 404 Thread pk=thread id document=doc if not thread is locked reply = form save commit=False reply thread = thread re... | 1695 | @login_required
@require_POST
def reply(request, document_slug, thread_id):
doc = get_document(document_slug, request)
form = ReplyForm(request.POST)
post_preview = None
if form.is_valid():
thread = get_object_or_404(Thread, pk=thread_id, document=doc)
if (not thread.is_locked):
reply_ = form.save(commit=Fal... | Reply to a thread. | reply to a thread . | Question:
What does this function do?
Code:
@login_required
@require_POST
def reply(request, document_slug, thread_id):
doc = get_document(document_slug, request)
form = ReplyForm(request.POST)
post_preview = None
if form.is_valid():
thread = get_object_or_404(Thread, pk=thread_id, document=doc)
if (not thre... |
null | null | null | What does this function do? | def _cmd(binary, *args):
binary = salt.utils.which(binary)
if (not binary):
raise CommandNotFoundError('{0}: command not found'.format(binary))
cmd = ([binary] + list(args))
return __salt__['cmd.run_stdout'](([binary] + list(args)), python_shell=False)
| null | null | null | Wrapper to run at(1) or return None. | pcsd | def cmd binary *args binary = salt utils which binary if not binary raise Command Not Found Error '{0} command not found' format binary cmd = [binary] + list args return salt ['cmd run stdout'] [binary] + list args python shell=False | 1696 | def _cmd(binary, *args):
binary = salt.utils.which(binary)
if (not binary):
raise CommandNotFoundError('{0}: command not found'.format(binary))
cmd = ([binary] + list(args))
return __salt__['cmd.run_stdout'](([binary] + list(args)), python_shell=False)
| Wrapper to run at(1) or return None. | wrapper to run at ( 1 ) or return none . | Question:
What does this function do?
Code:
def _cmd(binary, *args):
binary = salt.utils.which(binary)
if (not binary):
raise CommandNotFoundError('{0}: command not found'.format(binary))
cmd = ([binary] + list(args))
return __salt__['cmd.run_stdout'](([binary] + list(args)), python_shell=False)
|
null | null | null | What does this function do? | def logistic_function(value):
return (1.0 / (1.0 + math.exp((- value))))
| null | null | null | Transform the value with the logistic function.
XXX This is in the wrong place -- I need to find a place to put it
that makes sense. | pcsd | def logistic function value return 1 0 / 1 0 + math exp - value | 1708 | def logistic_function(value):
return (1.0 / (1.0 + math.exp((- value))))
| Transform the value with the logistic function.
XXX This is in the wrong place -- I need to find a place to put it
that makes sense. | transform the value with the logistic function . | Question:
What does this function do?
Code:
def logistic_function(value):
return (1.0 / (1.0 + math.exp((- value))))
|
null | null | null | What does this function do? | def pytest_configure(config):
if config.getoption('--qute-profile-subprocs'):
try:
shutil.rmtree('prof')
except FileNotFoundError:
pass
| null | null | null | Remove old profile files. | pcsd | def pytest configure config if config getoption '--qute-profile-subprocs' try shutil rmtree 'prof' except File Not Found Error pass | 1711 | def pytest_configure(config):
if config.getoption('--qute-profile-subprocs'):
try:
shutil.rmtree('prof')
except FileNotFoundError:
pass
| Remove old profile files. | remove old profile files . | Question:
What does this function do?
Code:
def pytest_configure(config):
if config.getoption('--qute-profile-subprocs'):
try:
shutil.rmtree('prof')
except FileNotFoundError:
pass
|
null | null | null | What does this function do? | def sort_unicode(choices, key):
if (not HAS_PYUCA):
return sorted(choices, key=(lambda tup: remove_accents(key(tup)).lower()))
else:
collator = pyuca.Collator()
return sorted(choices, key=(lambda tup: collator.sort_key(force_text(key(tup)))))
| null | null | null | Unicode aware sorting if available | pcsd | def sort unicode choices key if not HAS PYUCA return sorted choices key= lambda tup remove accents key tup lower else collator = pyuca Collator return sorted choices key= lambda tup collator sort key force text key tup | 1712 | def sort_unicode(choices, key):
if (not HAS_PYUCA):
return sorted(choices, key=(lambda tup: remove_accents(key(tup)).lower()))
else:
collator = pyuca.Collator()
return sorted(choices, key=(lambda tup: collator.sort_key(force_text(key(tup)))))
| Unicode aware sorting if available | unicode aware sorting if available | Question:
What does this function do?
Code:
def sort_unicode(choices, key):
if (not HAS_PYUCA):
return sorted(choices, key=(lambda tup: remove_accents(key(tup)).lower()))
else:
collator = pyuca.Collator()
return sorted(choices, key=(lambda tup: collator.sort_key(force_text(key(tup)))))
|
null | null | null | What does this function do? | def equateCylindricalDotRadius(point, returnValue):
originalRadius = abs(point.dropAxis())
if (originalRadius > 0.0):
radiusMultipler = (returnValue / originalRadius)
point.x *= radiusMultipler
point.y *= radiusMultipler
| null | null | null | Get equation for cylindrical radius. | pcsd | def equate Cylindrical Dot Radius point return Value original Radius = abs point drop Axis if original Radius > 0 0 radius Multipler = return Value / original Radius point x *= radius Multipler point y *= radius Multipler | 1714 | def equateCylindricalDotRadius(point, returnValue):
originalRadius = abs(point.dropAxis())
if (originalRadius > 0.0):
radiusMultipler = (returnValue / originalRadius)
point.x *= radiusMultipler
point.y *= radiusMultipler
| Get equation for cylindrical radius. | get equation for cylindrical radius . | Question:
What does this function do?
Code:
def equateCylindricalDotRadius(point, returnValue):
originalRadius = abs(point.dropAxis())
if (originalRadius > 0.0):
radiusMultipler = (returnValue / originalRadius)
point.x *= radiusMultipler
point.y *= radiusMultipler
|
null | null | null | What does this function do? | def getdocumenttext(document):
paratextlist = []
paralist = []
for element in document.getiterator():
if (element.tag == (('{' + nsprefixes['w']) + '}p')):
paralist.append(element)
for para in paralist:
paratext = u''
for element in para.getiterator():
if (element.tag == (('{' + nsprefixes['w']) + '}t')... | null | null | null | Return the raw text of a document, as a list of paragraphs. | pcsd | def getdocumenttext document paratextlist = [] paralist = [] for element in document getiterator if element tag == '{' + nsprefixes['w'] + '}p' paralist append element for para in paralist paratext = u'' for element in para getiterator if element tag == '{' + nsprefixes['w'] + '}t' if element text paratext = paratext +... | 1723 | def getdocumenttext(document):
paratextlist = []
paralist = []
for element in document.getiterator():
if (element.tag == (('{' + nsprefixes['w']) + '}p')):
paralist.append(element)
for para in paralist:
paratext = u''
for element in para.getiterator():
if (element.tag == (('{' + nsprefixes['w']) + '}t')... | Return the raw text of a document, as a list of paragraphs. | return the raw text of a document , as a list of paragraphs . | Question:
What does this function do?
Code:
def getdocumenttext(document):
paratextlist = []
paralist = []
for element in document.getiterator():
if (element.tag == (('{' + nsprefixes['w']) + '}p')):
paralist.append(element)
for para in paralist:
paratext = u''
for element in para.getiterator():
if (... |
null | null | null | What does this function do? | def writestatus(text, mute=False):
if ((not mute) and config.SHOW_STATUS.get):
_writeline(text)
| null | null | null | Update status line. | pcsd | def writestatus text mute=False if not mute and config SHOW STATUS get writeline text | 1727 | def writestatus(text, mute=False):
if ((not mute) and config.SHOW_STATUS.get):
_writeline(text)
| Update status line. | update status line . | Question:
What does this function do?
Code:
def writestatus(text, mute=False):
if ((not mute) and config.SHOW_STATUS.get):
_writeline(text)
|
null | null | null | What does this function do? | def get_config_filename(packageormod=None):
cfg = get_config(packageormod)
while (cfg.parent is not cfg):
cfg = cfg.parent
return cfg.filename
| null | null | null | Get the filename of the config file associated with the given
package or module. | pcsd | def get config filename packageormod=None cfg = get config packageormod while cfg parent is not cfg cfg = cfg parent return cfg filename | 1747 | def get_config_filename(packageormod=None):
cfg = get_config(packageormod)
while (cfg.parent is not cfg):
cfg = cfg.parent
return cfg.filename
| Get the filename of the config file associated with the given
package or module. | get the filename of the config file associated with the given package or module . | Question:
What does this function do?
Code:
def get_config_filename(packageormod=None):
cfg = get_config(packageormod)
while (cfg.parent is not cfg):
cfg = cfg.parent
return cfg.filename
|
null | null | null | What does this function do? | def setup_platform(hass, config, add_devices, discovery_info=None):
name = config.get(CONF_NAME)
mac = config.get(CONF_MAC)
_LOGGER.debug('Setting up...')
mon = Monitor(hass, mac, name)
add_devices([SkybeaconTemp(name, mon)])
add_devices([SkybeaconHumid(name, mon)])
def monitor_stop(_service_or_event):
'Stop t... | null | null | null | Set up the sensor. | pcsd | def setup platform hass config add devices discovery info=None name = config get CONF NAME mac = config get CONF MAC LOGGER debug 'Setting up ' mon = Monitor hass mac name add devices [Skybeacon Temp name mon ] add devices [Skybeacon Humid name mon ] def monitor stop service or event 'Stop the monitor thread ' LOGGER i... | 1749 | def setup_platform(hass, config, add_devices, discovery_info=None):
name = config.get(CONF_NAME)
mac = config.get(CONF_MAC)
_LOGGER.debug('Setting up...')
mon = Monitor(hass, mac, name)
add_devices([SkybeaconTemp(name, mon)])
add_devices([SkybeaconHumid(name, mon)])
def monitor_stop(_service_or_event):
'Stop t... | Set up the sensor. | set up the sensor . | Question:
What does this function do?
Code:
def setup_platform(hass, config, add_devices, discovery_info=None):
name = config.get(CONF_NAME)
mac = config.get(CONF_MAC)
_LOGGER.debug('Setting up...')
mon = Monitor(hass, mac, name)
add_devices([SkybeaconTemp(name, mon)])
add_devices([SkybeaconHumid(name, mon)])
... |
null | null | null | What does this function do? | @csrf_protect
def aifile_edit(request, aifile_name=None, editmode='edit'):
if (not test_user_authenticated(request)):
return login(request, next=('/cobbler_web/aifile/edit/file:%s' % aifile_name), expired=True)
if (editmode == 'edit'):
editable = False
else:
editable = True
deleteable = False
aidata = ''
if... | null | null | null | This is the page where an automatic OS installation file is edited. | pcsd | @csrf protect def aifile edit request aifile name=None editmode='edit' if not test user authenticated request return login request next= '/cobbler web/aifile/edit/file %s' % aifile name expired=True if editmode == 'edit' editable = False else editable = True deleteable = False aidata = '' if aifile name is not None edi... | 1761 | @csrf_protect
def aifile_edit(request, aifile_name=None, editmode='edit'):
if (not test_user_authenticated(request)):
return login(request, next=('/cobbler_web/aifile/edit/file:%s' % aifile_name), expired=True)
if (editmode == 'edit'):
editable = False
else:
editable = True
deleteable = False
aidata = ''
if... | This is the page where an automatic OS installation file is edited. | this is the page where an automatic os installation file is edited . | Question:
What does this function do?
Code:
@csrf_protect
def aifile_edit(request, aifile_name=None, editmode='edit'):
if (not test_user_authenticated(request)):
return login(request, next=('/cobbler_web/aifile/edit/file:%s' % aifile_name), expired=True)
if (editmode == 'edit'):
editable = False
else:
edita... |
null | null | null | What does this function do? | def lookup_loc(location, country):
corrected = location_names.get(location)
if corrected:
return get_loc_from_db(corrected, country)
if (location[(-6):] == 'County'):
return get_loc_from_db(location[:(-6)].strip(), 'Liberia')
if location.startswith('Western Area'):
return get_loc_from_db(location[12:].strip()... | null | null | null | Location Names need to match what we have already | pcsd | def lookup loc location country corrected = location names get location if corrected return get loc from db corrected country if location[ -6 ] == 'County' return get loc from db location[ -6 ] strip 'Liberia' if location startswith 'Western Area' return get loc from db location[12 ] strip country if location in reject... | 1763 | def lookup_loc(location, country):
corrected = location_names.get(location)
if corrected:
return get_loc_from_db(corrected, country)
if (location[(-6):] == 'County'):
return get_loc_from_db(location[:(-6)].strip(), 'Liberia')
if location.startswith('Western Area'):
return get_loc_from_db(location[12:].strip()... | Location Names need to match what we have already | location names need to match what we have already | Question:
What does this function do?
Code:
def lookup_loc(location, country):
corrected = location_names.get(location)
if corrected:
return get_loc_from_db(corrected, country)
if (location[(-6):] == 'County'):
return get_loc_from_db(location[:(-6)].strip(), 'Liberia')
if location.startswith('Western Area'):... |
null | null | null | What does this function do? | def _plot_window(value, params):
max_times = (len(params['times']) - params['duration'])
if (value > max_times):
value = (len(params['times']) - params['duration'])
if (value < 0):
value = 0
if (params['t_start'] != value):
params['t_start'] = value
params['hsel_patch'].set_x(value)
params['plot_update_pr... | null | null | null | Deal with horizontal shift of the viewport. | pcsd | def plot window value params max times = len params['times'] - params['duration'] if value > max times value = len params['times'] - params['duration'] if value < 0 value = 0 if params['t start'] != value params['t start'] = value params['hsel patch'] set x value params['plot update proj callback'] params | 1766 | def _plot_window(value, params):
max_times = (len(params['times']) - params['duration'])
if (value > max_times):
value = (len(params['times']) - params['duration'])
if (value < 0):
value = 0
if (params['t_start'] != value):
params['t_start'] = value
params['hsel_patch'].set_x(value)
params['plot_update_pr... | Deal with horizontal shift of the viewport. | deal with horizontal shift of the viewport . | Question:
What does this function do?
Code:
def _plot_window(value, params):
max_times = (len(params['times']) - params['duration'])
if (value > max_times):
value = (len(params['times']) - params['duration'])
if (value < 0):
value = 0
if (params['t_start'] != value):
params['t_start'] = value
params['hse... |
null | null | null | What does this function do? | def _do_install_one(reg, app_loc, relative_path):
LOG.info(('=== Installing app at %s' % (app_loc,)))
try:
app_loc = os.path.realpath(app_loc)
(app_name, version, desc, author) = get_app_info(app_loc)
except (ValueError, OSError) as ex:
LOG.error(ex)
return False
app = registry.HueApp(app_name, version, app... | null | null | null | Install one app, without saving. Returns True/False. | pcsd | def do install one reg app loc relative path LOG info '=== Installing app at %s' % app loc try app loc = os path realpath app loc app name version desc author = get app info app loc except Value Error OS Error as ex LOG error ex return False app = registry Hue App app name version app loc desc author if relative path a... | 1769 | def _do_install_one(reg, app_loc, relative_path):
LOG.info(('=== Installing app at %s' % (app_loc,)))
try:
app_loc = os.path.realpath(app_loc)
(app_name, version, desc, author) = get_app_info(app_loc)
except (ValueError, OSError) as ex:
LOG.error(ex)
return False
app = registry.HueApp(app_name, version, app... | Install one app, without saving. Returns True/False. | install one app , without saving . | Question:
What does this function do?
Code:
def _do_install_one(reg, app_loc, relative_path):
LOG.info(('=== Installing app at %s' % (app_loc,)))
try:
app_loc = os.path.realpath(app_loc)
(app_name, version, desc, author) = get_app_info(app_loc)
except (ValueError, OSError) as ex:
LOG.error(ex)
return Fals... |
null | null | null | What does this function do? | def crc32(data):
return (_crc32(data) & 4294967295)
| null | null | null | Python version idempotent | pcsd | def crc32 data return crc32 data & 4294967295 | 1777 | def crc32(data):
return (_crc32(data) & 4294967295)
| Python version idempotent | python version idempotent | Question:
What does this function do?
Code:
def crc32(data):
return (_crc32(data) & 4294967295)
|
null | null | null | What does this function do? | def real_ip(request):
return request.META.get('HTTP_X_REAL_IP')
| null | null | null | Returns the IP Address contained in the HTTP_X_REAL_IP headers, if
present. Otherwise, `None`.
Should handle Nginx and some other WSGI servers. | pcsd | def real ip request return request META get 'HTTP X REAL IP' | 1779 | def real_ip(request):
return request.META.get('HTTP_X_REAL_IP')
| Returns the IP Address contained in the HTTP_X_REAL_IP headers, if
present. Otherwise, `None`.
Should handle Nginx and some other WSGI servers. | returns the ip address contained in the http _ x _ real _ ip headers , if present . | Question:
What does this function do?
Code:
def real_ip(request):
return request.META.get('HTTP_X_REAL_IP')
|
null | null | null | What does this function do? | def addVertexToAttributeDictionary(attributeDictionary, vertex):
if (vertex.x != 0.0):
attributeDictionary['x'] = str(vertex.x)
if (vertex.y != 0.0):
attributeDictionary['y'] = str(vertex.y)
if (vertex.z != 0.0):
attributeDictionary['z'] = str(vertex.z)
| null | null | null | Add to the attribute dictionary. | pcsd | def add Vertex To Attribute Dictionary attribute Dictionary vertex if vertex x != 0 0 attribute Dictionary['x'] = str vertex x if vertex y != 0 0 attribute Dictionary['y'] = str vertex y if vertex z != 0 0 attribute Dictionary['z'] = str vertex z | 1781 | def addVertexToAttributeDictionary(attributeDictionary, vertex):
if (vertex.x != 0.0):
attributeDictionary['x'] = str(vertex.x)
if (vertex.y != 0.0):
attributeDictionary['y'] = str(vertex.y)
if (vertex.z != 0.0):
attributeDictionary['z'] = str(vertex.z)
| Add to the attribute dictionary. | add to the attribute dictionary . | Question:
What does this function do?
Code:
def addVertexToAttributeDictionary(attributeDictionary, vertex):
if (vertex.x != 0.0):
attributeDictionary['x'] = str(vertex.x)
if (vertex.y != 0.0):
attributeDictionary['y'] = str(vertex.y)
if (vertex.z != 0.0):
attributeDictionary['z'] = str(vertex.z)
|
null | null | null | What does this function do? | def backends(user):
return user_backends_data(user, get_helper('AUTHENTICATION_BACKENDS'), module_member(get_helper('STORAGE')))
| null | null | null | Load Social Auth current user data to context under the key \'backends\'.
Will return the output of social.backends.utils.user_backends_data. | pcsd | def backends user return user backends data user get helper 'AUTHENTICATION BACKENDS' module member get helper 'STORAGE' | 1788 | def backends(user):
return user_backends_data(user, get_helper('AUTHENTICATION_BACKENDS'), module_member(get_helper('STORAGE')))
| Load Social Auth current user data to context under the key \'backends\'.
Will return the output of social.backends.utils.user_backends_data. | load social auth current user data to context under the key backends . | Question:
What does this function do?
Code:
def backends(user):
return user_backends_data(user, get_helper('AUTHENTICATION_BACKENDS'), module_member(get_helper('STORAGE')))
|
null | null | null | What does this function do? | def credential():
return s3db.hrm_credential_controller()
| null | null | null | RESTful CRUD controller - unfiltered version | pcsd | def credential return s3db hrm credential controller | 1792 | def credential():
return s3db.hrm_credential_controller()
| RESTful CRUD controller - unfiltered version | restful crud controller - unfiltered version | Question:
What does this function do?
Code:
def credential():
return s3db.hrm_credential_controller()
|
null | null | null | What does this function do? | def EnsureDirExists(path):
try:
os.makedirs(os.path.dirname(path))
except OSError:
pass
| null | null | null | Make sure the directory for |path| exists. | pcsd | def Ensure Dir Exists path try os makedirs os path dirname path except OS Error pass | 1804 | def EnsureDirExists(path):
try:
os.makedirs(os.path.dirname(path))
except OSError:
pass
| Make sure the directory for |path| exists. | make sure the directory for | path | exists . | Question:
What does this function do?
Code:
def EnsureDirExists(path):
try:
os.makedirs(os.path.dirname(path))
except OSError:
pass
|
null | null | null | What does this function do? | def filename_search_replace(sr_pairs, filename, backup=False):
in_txt = open(filename, 'rt').read((-1))
out_txt = in_txt[:]
for (in_exp, out_exp) in sr_pairs:
in_exp = re.compile(in_exp)
out_txt = in_exp.sub(out_exp, out_txt)
if (in_txt == out_txt):
return False
open(filename, 'wt').write(out_txt)
if backup... | null | null | null | Search and replace for expressions in files | pcsd | def filename search replace sr pairs filename backup=False in txt = open filename 'rt' read -1 out txt = in txt[ ] for in exp out exp in sr pairs in exp = re compile in exp out txt = in exp sub out exp out txt if in txt == out txt return False open filename 'wt' write out txt if backup open filename + ' bak' 'wt' write... | 1808 | def filename_search_replace(sr_pairs, filename, backup=False):
in_txt = open(filename, 'rt').read((-1))
out_txt = in_txt[:]
for (in_exp, out_exp) in sr_pairs:
in_exp = re.compile(in_exp)
out_txt = in_exp.sub(out_exp, out_txt)
if (in_txt == out_txt):
return False
open(filename, 'wt').write(out_txt)
if backup... | Search and replace for expressions in files | search and replace for expressions in files | Question:
What does this function do?
Code:
def filename_search_replace(sr_pairs, filename, backup=False):
in_txt = open(filename, 'rt').read((-1))
out_txt = in_txt[:]
for (in_exp, out_exp) in sr_pairs:
in_exp = re.compile(in_exp)
out_txt = in_exp.sub(out_exp, out_txt)
if (in_txt == out_txt):
return False
... |
null | null | null | What does this function do? | def vehicle():
tablename = 'asset_asset'
table = s3db[tablename]
s3db.configure('vehicle_vehicle', deletable=False)
set_method = s3db.set_method
set_method('asset', 'asset', method='assign', action=s3db.hrm_AssignMethod(component='human_resource'))
set_method('asset', 'asset', method='check-in', action=s3base.S3C... | null | null | null | RESTful CRUD controller
Filtered version of the asset_asset resource | pcsd | def vehicle tablename = 'asset asset' table = s3db[tablename] s3db configure 'vehicle vehicle' deletable=False set method = s3db set method set method 'asset' 'asset' method='assign' action=s3db hrm Assign Method component='human resource' set method 'asset' 'asset' method='check-in' action=s3base S3Check In Method set... | 1811 | def vehicle():
tablename = 'asset_asset'
table = s3db[tablename]
s3db.configure('vehicle_vehicle', deletable=False)
set_method = s3db.set_method
set_method('asset', 'asset', method='assign', action=s3db.hrm_AssignMethod(component='human_resource'))
set_method('asset', 'asset', method='check-in', action=s3base.S3C... | RESTful CRUD controller
Filtered version of the asset_asset resource | restful crud controller | Question:
What does this function do?
Code:
def vehicle():
tablename = 'asset_asset'
table = s3db[tablename]
s3db.configure('vehicle_vehicle', deletable=False)
set_method = s3db.set_method
set_method('asset', 'asset', method='assign', action=s3db.hrm_AssignMethod(component='human_resource'))
set_method('asset'... |
null | null | null | What does this function do? | def envs():
containers = __opts__.get('azurefs_containers', [])
return containers.keys()
| null | null | null | Treat each container as an environment | pcsd | def envs containers = opts get 'azurefs containers' [] return containers keys | 1817 | def envs():
containers = __opts__.get('azurefs_containers', [])
return containers.keys()
| Treat each container as an environment | treat each container as an environment | Question:
What does this function do?
Code:
def envs():
containers = __opts__.get('azurefs_containers', [])
return containers.keys()
|
null | null | null | What does this function do? | def p_parameter_type_list_2(t):
pass
| null | null | null | parameter_type_list : parameter_list COMMA ELLIPSIS | pcsd | def p parameter type list 2 t pass | 1818 | def p_parameter_type_list_2(t):
pass
| parameter_type_list : parameter_list COMMA ELLIPSIS | parameter _ type _ list : parameter _ list comma ellipsis | Question:
What does this function do?
Code:
def p_parameter_type_list_2(t):
pass
|
null | null | null | What does this function do? | def clone_env(prefix1, prefix2, verbose=True, quiet=False, index_args=None):
untracked_files = untracked(prefix1)
drecs = linked_data(prefix1)
filter = {}
found = True
while found:
found = False
for (dist, info) in iteritems(drecs):
name = info[u'name']
if (name in filter):
continue
if (name == u'... | null | null | null | clone existing prefix1 into new prefix2 | pcsd | def clone env prefix1 prefix2 verbose=True quiet=False index args=None untracked files = untracked prefix1 drecs = linked data prefix1 filter = {} found = True while found found = False for dist info in iteritems drecs name = info[u'name'] if name in filter continue if name == u'conda' filter[u'conda'] = dist found = T... | 1821 | def clone_env(prefix1, prefix2, verbose=True, quiet=False, index_args=None):
untracked_files = untracked(prefix1)
drecs = linked_data(prefix1)
filter = {}
found = True
while found:
found = False
for (dist, info) in iteritems(drecs):
name = info[u'name']
if (name in filter):
continue
if (name == u'... | clone existing prefix1 into new prefix2 | clone existing prefix1 into new prefix2 | Question:
What does this function do?
Code:
def clone_env(prefix1, prefix2, verbose=True, quiet=False, index_args=None):
untracked_files = untracked(prefix1)
drecs = linked_data(prefix1)
filter = {}
found = True
while found:
found = False
for (dist, info) in iteritems(drecs):
name = info[u'name']
if (... |
null | null | null | What does this function do? | def _build_image(data, cmap='gray'):
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
figsize = data.shape[::(-1)]
if (figsize[0] == 1):
figsize = tuple(figsize[1:])
data = data[:, :, 0]
fig = Figure(figsize=figsiz... | null | null | null | Build an image encoded in base64. | pcsd | def build image data cmap='gray' import matplotlib pyplot as plt from matplotlib figure import Figure from matplotlib backends backend agg import Figure Canvas Agg as Figure Canvas figsize = data shape[ -1 ] if figsize[0] == 1 figsize = tuple figsize[1 ] data = data[ 0] fig = Figure figsize=figsize dpi=1 0 frameon=Fals... | 1830 | def _build_image(data, cmap='gray'):
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
figsize = data.shape[::(-1)]
if (figsize[0] == 1):
figsize = tuple(figsize[1:])
data = data[:, :, 0]
fig = Figure(figsize=figsiz... | Build an image encoded in base64. | build an image encoded in base64 . | Question:
What does this function do?
Code:
def _build_image(data, cmap='gray'):
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
figsize = data.shape[::(-1)]
if (figsize[0] == 1):
figsize = tuple(figsize[1:])
da... |
null | null | null | What does this function do? | def run(cmd):
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
txt = p.stdout.read()
return (p.wait(), txt)
| null | null | null | Run system command, returns exit-code and stdout | pcsd | def run cmd p = subprocess Popen cmd stdout=subprocess PIPE stderr=subprocess PIPE shell=True txt = p stdout read return p wait txt | 1832 | def run(cmd):
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
txt = p.stdout.read()
return (p.wait(), txt)
| Run system command, returns exit-code and stdout | run system command , returns exit - code and stdout | Question:
What does this function do?
Code:
def run(cmd):
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
txt = p.stdout.read()
return (p.wait(), txt)
|
null | null | null | What does this function do? | def expanded_data(n=100):
(expanded_training_data, _, _) = network3.load_data_shared('../data/mnist_expanded.pkl.gz')
for j in range(3):
print ('Training with expanded data, %s neurons in the FC layer, run num %s' % (n, j))
net = Network([ConvPoolLayer(image_shape=(mini_batch_size, 1, 28, 28), filter_shape=(20, 1... | null | null | null | n is the number of neurons in the fully-connected layer. We\'ll try
n=100, 300, and 1000. | pcsd | def expanded data n=100 expanded training data = network3 load data shared ' /data/mnist expanded pkl gz' for j in range 3 print 'Training with expanded data %s neurons in the FC layer run num %s' % n j net = Network [Conv Pool Layer image shape= mini batch size 1 28 28 filter shape= 20 1 5 5 poolsize= 2 2 activation f... | 1841 | def expanded_data(n=100):
(expanded_training_data, _, _) = network3.load_data_shared('../data/mnist_expanded.pkl.gz')
for j in range(3):
print ('Training with expanded data, %s neurons in the FC layer, run num %s' % (n, j))
net = Network([ConvPoolLayer(image_shape=(mini_batch_size, 1, 28, 28), filter_shape=(20, 1... | n is the number of neurons in the fully-connected layer. We\'ll try
n=100, 300, and 1000. | n is the number of neurons in the fully - connected layer . | Question:
What does this function do?
Code:
def expanded_data(n=100):
(expanded_training_data, _, _) = network3.load_data_shared('../data/mnist_expanded.pkl.gz')
for j in range(3):
print ('Training with expanded data, %s neurons in the FC layer, run num %s' % (n, j))
net = Network([ConvPoolLayer(image_shape=(m... |
null | null | null | What does this function do? | @frappe.whitelist()
def update_event(args, field_map):
args = frappe._dict(json.loads(args))
field_map = frappe._dict(json.loads(field_map))
w = frappe.get_doc(args.doctype, args.name)
w.set(field_map.start, args[field_map.start])
w.set(field_map.end, args.get(field_map.end))
w.save()
| null | null | null | Updates Event (called via calendar) based on passed `field_map` | pcsd | @frappe whitelist def update event args field map args = frappe dict json loads args field map = frappe dict json loads field map w = frappe get doc args doctype args name w set field map start args[field map start] w set field map end args get field map end w save | 1842 | @frappe.whitelist()
def update_event(args, field_map):
args = frappe._dict(json.loads(args))
field_map = frappe._dict(json.loads(field_map))
w = frappe.get_doc(args.doctype, args.name)
w.set(field_map.start, args[field_map.start])
w.set(field_map.end, args.get(field_map.end))
w.save()
| Updates Event (called via calendar) based on passed `field_map` | updates event based on passed field _ map | Question:
What does this function do?
Code:
@frappe.whitelist()
def update_event(args, field_map):
args = frappe._dict(json.loads(args))
field_map = frappe._dict(json.loads(field_map))
w = frappe.get_doc(args.doctype, args.name)
w.set(field_map.start, args[field_map.start])
w.set(field_map.end, args.get(field_m... |
null | null | null | What does this function do? | @then(u'we see table created')
def step_see_table_created(context):
_expect_exact(context, u'CREATE TABLE', timeout=2)
| null | null | null | Wait to see create table output. | pcsd | @then u'we see table created' def step see table created context expect exact context u'CREATE TABLE' timeout=2 | 1853 | @then(u'we see table created')
def step_see_table_created(context):
_expect_exact(context, u'CREATE TABLE', timeout=2)
| Wait to see create table output. | wait to see create table output . | Question:
What does this function do?
Code:
@then(u'we see table created')
def step_see_table_created(context):
_expect_exact(context, u'CREATE TABLE', timeout=2)
|
null | null | null | What does this function do? | def user_agent():
from requests.utils import default_user_agent
return (('ka-lite/%s ' % VERSION) + default_user_agent())
| null | null | null | HTTP User-Agent header string derived from version, used by various HTTP
requests sent to learningequality.org for stats | pcsd | def user agent from requests utils import default user agent return 'ka-lite/%s ' % VERSION + default user agent | 1859 | def user_agent():
from requests.utils import default_user_agent
return (('ka-lite/%s ' % VERSION) + default_user_agent())
| HTTP User-Agent header string derived from version, used by various HTTP
requests sent to learningequality.org for stats | http user - agent header string derived from version , used by various http requests sent to learningequality . org for stats | Question:
What does this function do?
Code:
def user_agent():
from requests.utils import default_user_agent
return (('ka-lite/%s ' % VERSION) + default_user_agent())
|
null | null | null | What does this function do? | def filter_thing2(x):
return x._thing2
| null | null | null | A filter to apply to the results of a relationship query returns
the object of the relationship. | pcsd | def filter thing2 x return x thing2 | 1862 | def filter_thing2(x):
return x._thing2
| A filter to apply to the results of a relationship query returns
the object of the relationship. | a filter to apply to the results of a relationship query returns the object of the relationship . | Question:
What does this function do?
Code:
def filter_thing2(x):
return x._thing2
|
null | null | null | What does this function do? | def _vpc_peering_conn_id_for_name(name, conn):
log.debug('Retrieving VPC peering connection id')
ids = _get_peering_connection_ids(name, conn)
if (not ids):
ids = [None]
elif (len(ids) > 1):
raise SaltInvocationError('Found multiple VPC peering connections with the same name!! Please make sure you have only one... | null | null | null | Get the ID associated with this name | pcsd | def vpc peering conn id for name name conn log debug 'Retrieving VPC peering connection id' ids = get peering connection ids name conn if not ids ids = [None] elif len ids > 1 raise Salt Invocation Error 'Found multiple VPC peering connections with the same name!! Please make sure you have only one VPC peering connecti... | 1873 | def _vpc_peering_conn_id_for_name(name, conn):
log.debug('Retrieving VPC peering connection id')
ids = _get_peering_connection_ids(name, conn)
if (not ids):
ids = [None]
elif (len(ids) > 1):
raise SaltInvocationError('Found multiple VPC peering connections with the same name!! Please make sure you have only one... | Get the ID associated with this name | get the id associated with this name | Question:
What does this function do?
Code:
def _vpc_peering_conn_id_for_name(name, conn):
log.debug('Retrieving VPC peering connection id')
ids = _get_peering_connection_ids(name, conn)
if (not ids):
ids = [None]
elif (len(ids) > 1):
raise SaltInvocationError('Found multiple VPC peering connections with the... |
null | null | null | What does this function do? | def _smart_pad(x, n_pad):
if (n_pad == 0).all():
return x
elif (n_pad < 0).any():
raise RuntimeError('n_pad must be non-negative')
l_z_pad = np.zeros(max(((n_pad[0] - len(x)) + 1), 0), dtype=x.dtype)
r_z_pad = np.zeros(max(((n_pad[0] - len(x)) + 1), 0), dtype=x.dtype)
return np.concatenate([l_z_pad, ((2 * x[0]... | null | null | null | Pad vector x. | pcsd | def smart pad x n pad if n pad == 0 all return x elif n pad < 0 any raise Runtime Error 'n pad must be non-negative' l z pad = np zeros max n pad[0] - len x + 1 0 dtype=x dtype r z pad = np zeros max n pad[0] - len x + 1 0 dtype=x dtype return np concatenate [l z pad 2 * x[0] - x[n pad[0] 0 -1 ] x 2 * x[ -1 ] - x[ -2 -... | 1875 | def _smart_pad(x, n_pad):
if (n_pad == 0).all():
return x
elif (n_pad < 0).any():
raise RuntimeError('n_pad must be non-negative')
l_z_pad = np.zeros(max(((n_pad[0] - len(x)) + 1), 0), dtype=x.dtype)
r_z_pad = np.zeros(max(((n_pad[0] - len(x)) + 1), 0), dtype=x.dtype)
return np.concatenate([l_z_pad, ((2 * x[0]... | Pad vector x. | pad vector x . | Question:
What does this function do?
Code:
def _smart_pad(x, n_pad):
if (n_pad == 0).all():
return x
elif (n_pad < 0).any():
raise RuntimeError('n_pad must be non-negative')
l_z_pad = np.zeros(max(((n_pad[0] - len(x)) + 1), 0), dtype=x.dtype)
r_z_pad = np.zeros(max(((n_pad[0] - len(x)) + 1), 0), dtype=x.dty... |
null | null | null | What does this function do? | def isSidePointAdded(pixelTable, closestPath, closestPathIndex, closestPointIndex, layerExtrusionWidth, removedEndpointPoint, width):
if ((closestPointIndex <= 0) or (closestPointIndex >= len(closestPath))):
return False
pointBegin = closestPath[(closestPointIndex - 1)]
pointEnd = closestPath[closestPointIndex]
r... | null | null | null | Add side point along with the closest removed endpoint to the path, with minimal twisting. | pcsd | def is Side Point Added pixel Table closest Path closest Path Index closest Point Index layer Extrusion Width removed Endpoint Point width if closest Point Index <= 0 or closest Point Index >= len closest Path return False point Begin = closest Path[ closest Point Index - 1 ] point End = closest Path[closest Point Inde... | 1876 | def isSidePointAdded(pixelTable, closestPath, closestPathIndex, closestPointIndex, layerExtrusionWidth, removedEndpointPoint, width):
if ((closestPointIndex <= 0) or (closestPointIndex >= len(closestPath))):
return False
pointBegin = closestPath[(closestPointIndex - 1)]
pointEnd = closestPath[closestPointIndex]
r... | Add side point along with the closest removed endpoint to the path, with minimal twisting. | add side point along with the closest removed endpoint to the path , with minimal twisting . | Question:
What does this function do?
Code:
def isSidePointAdded(pixelTable, closestPath, closestPathIndex, closestPointIndex, layerExtrusionWidth, removedEndpointPoint, width):
if ((closestPointIndex <= 0) or (closestPointIndex >= len(closestPath))):
return False
pointBegin = closestPath[(closestPointIndex - 1)... |
null | null | null | What does this function do? | def set_dirty(using=None):
if (using is None):
using = DEFAULT_DB_ALIAS
connection = connections[using]
connection.set_dirty()
| null | null | null | Sets a dirty flag for the current thread and code streak. This can be used
to decide in a managed block of code to decide whether there are open
changes waiting for commit. | pcsd | def set dirty using=None if using is None using = DEFAULT DB ALIAS connection = connections[using] connection set dirty | 1886 | def set_dirty(using=None):
if (using is None):
using = DEFAULT_DB_ALIAS
connection = connections[using]
connection.set_dirty()
| Sets a dirty flag for the current thread and code streak. This can be used
to decide in a managed block of code to decide whether there are open
changes waiting for commit. | sets a dirty flag for the current thread and code streak . | Question:
What does this function do?
Code:
def set_dirty(using=None):
if (using is None):
using = DEFAULT_DB_ALIAS
connection = connections[using]
connection.set_dirty()
|
null | null | null | What does this function do? | def add_prefix(key, identity=u'image'):
return u'||'.join([settings.THUMBNAIL_KEY_PREFIX, identity, key])
| null | null | null | Adds prefixes to the key | pcsd | def add prefix key identity=u'image' return u'||' join [settings THUMBNAIL KEY PREFIX identity key] | 1891 | def add_prefix(key, identity=u'image'):
return u'||'.join([settings.THUMBNAIL_KEY_PREFIX, identity, key])
| Adds prefixes to the key | adds prefixes to the key | Question:
What does this function do?
Code:
def add_prefix(key, identity=u'image'):
return u'||'.join([settings.THUMBNAIL_KEY_PREFIX, identity, key])
|
null | null | null | What does this function do? | def JoinableQueue(maxsize=0):
from multiprocessing.queues import JoinableQueue
return JoinableQueue(maxsize)
| null | null | null | Returns a queue object | pcsd | def Joinable Queue maxsize=0 from multiprocessing queues import Joinable Queue return Joinable Queue maxsize | 1909 | def JoinableQueue(maxsize=0):
from multiprocessing.queues import JoinableQueue
return JoinableQueue(maxsize)
| Returns a queue object | returns a queue object | Question:
What does this function do?
Code:
def JoinableQueue(maxsize=0):
from multiprocessing.queues import JoinableQueue
return JoinableQueue(maxsize)
|
null | null | null | What does this function do? | def iterate_file(file):
while 1:
chunk = file.read(CHUNK_SIZE)
if (not chunk):
break
(yield chunk)
| null | null | null | Progressively return chunks from `file`. | pcsd | def iterate file file while 1 chunk = file read CHUNK SIZE if not chunk break yield chunk | 1918 | def iterate_file(file):
while 1:
chunk = file.read(CHUNK_SIZE)
if (not chunk):
break
(yield chunk)
| Progressively return chunks from `file`. | progressively return chunks from file . | Question:
What does this function do?
Code:
def iterate_file(file):
while 1:
chunk = file.read(CHUNK_SIZE)
if (not chunk):
break
(yield chunk)
|
null | null | null | What does this function do? | def map_download_check(request):
try:
layer = request.session['map_status']
if isinstance(layer, dict):
url = ('%srest/process/batchDownload/status/%s' % (ogc_server_settings.LOCATION, layer['id']))
(resp, content) = http_client.request(url, 'GET')
status = resp.status
if (resp.status == 400):
retu... | null | null | null | this is an endpoint for monitoring map downloads | pcsd | def map download check request try layer = request session['map status'] if isinstance layer dict url = '%srest/process/batch Download/status/%s' % ogc server settings LOCATION layer['id'] resp content = http client request url 'GET' status = resp status if resp status == 400 return Http Response content='Something wen... | 1919 | def map_download_check(request):
try:
layer = request.session['map_status']
if isinstance(layer, dict):
url = ('%srest/process/batchDownload/status/%s' % (ogc_server_settings.LOCATION, layer['id']))
(resp, content) = http_client.request(url, 'GET')
status = resp.status
if (resp.status == 400):
retu... | this is an endpoint for monitoring map downloads | this is an endpoint for monitoring map downloads | Question:
What does this function do?
Code:
def map_download_check(request):
try:
layer = request.session['map_status']
if isinstance(layer, dict):
url = ('%srest/process/batchDownload/status/%s' % (ogc_server_settings.LOCATION, layer['id']))
(resp, content) = http_client.request(url, 'GET')
status = r... |
null | null | null | What does this function do? | def to_rgba(c, alpha=None):
if _is_nth_color(c):
from matplotlib import rcParams
prop_cycler = rcParams[u'axes.prop_cycle']
colors = prop_cycler.by_key().get(u'color', [u'k'])
c = colors[(int(c[1]) % len(colors))]
try:
rgba = _colors_full_map.cache[(c, alpha)]
except (KeyError, TypeError):
rgba = _to_rgb... | null | null | null | Convert `c` to an RGBA color.
If `alpha` is not `None`, it forces the alpha value, except if `c` is
"none" (case-insensitive), which always maps to `(0, 0, 0, 0)`. | pcsd | def to rgba c alpha=None if is nth color c from matplotlib import rc Params prop cycler = rc Params[u'axes prop cycle'] colors = prop cycler by key get u'color' [u'k'] c = colors[ int c[1] % len colors ] try rgba = colors full map cache[ c alpha ] except Key Error Type Error rgba = to rgba no colorcycle c alpha try col... | 1921 | def to_rgba(c, alpha=None):
if _is_nth_color(c):
from matplotlib import rcParams
prop_cycler = rcParams[u'axes.prop_cycle']
colors = prop_cycler.by_key().get(u'color', [u'k'])
c = colors[(int(c[1]) % len(colors))]
try:
rgba = _colors_full_map.cache[(c, alpha)]
except (KeyError, TypeError):
rgba = _to_rgb... | Convert `c` to an RGBA color.
If `alpha` is not `None`, it forces the alpha value, except if `c` is
"none" (case-insensitive), which always maps to `(0, 0, 0, 0)`. | convert c to an rgba color . | Question:
What does this function do?
Code:
def to_rgba(c, alpha=None):
if _is_nth_color(c):
from matplotlib import rcParams
prop_cycler = rcParams[u'axes.prop_cycle']
colors = prop_cycler.by_key().get(u'color', [u'k'])
c = colors[(int(c[1]) % len(colors))]
try:
rgba = _colors_full_map.cache[(c, alpha)]
... |
null | null | null | What does this function do? | def photo(f):
filename = os.path.join(os.path.dirname(__file__), '..', f)
assert os.path.exists(filename)
return filename
| null | null | null | Helper function for photo file | pcsd | def photo f filename = os path join os path dirname file ' ' f assert os path exists filename return filename | 1924 | def photo(f):
filename = os.path.join(os.path.dirname(__file__), '..', f)
assert os.path.exists(filename)
return filename
| Helper function for photo file | helper function for photo file | Question:
What does this function do?
Code:
def photo(f):
filename = os.path.join(os.path.dirname(__file__), '..', f)
assert os.path.exists(filename)
return filename
|
null | null | null | What does this function do? | def get_dict_of_struct(struct, connection=None, fetch_nested=False, attributes=None):
def remove_underscore(val):
if val.startswith('_'):
val = val[1:]
remove_underscore(val)
return val
res = {}
if (struct is not None):
for (key, value) in struct.__dict__.items():
nested = False
key = remove_unders... | null | null | null | Convert SDK Struct type into dictionary. | pcsd | def get dict of struct struct connection=None fetch nested=False attributes=None def remove underscore val if val startswith ' ' val = val[1 ] remove underscore val return val res = {} if struct is not None for key value in struct dict items nested = False key = remove underscore key if value is None continue elif isin... | 1932 | def get_dict_of_struct(struct, connection=None, fetch_nested=False, attributes=None):
def remove_underscore(val):
if val.startswith('_'):
val = val[1:]
remove_underscore(val)
return val
res = {}
if (struct is not None):
for (key, value) in struct.__dict__.items():
nested = False
key = remove_unders... | Convert SDK Struct type into dictionary. | convert sdk struct type into dictionary . | Question:
What does this function do?
Code:
def get_dict_of_struct(struct, connection=None, fetch_nested=False, attributes=None):
def remove_underscore(val):
if val.startswith('_'):
val = val[1:]
remove_underscore(val)
return val
res = {}
if (struct is not None):
for (key, value) in struct.__dict__.it... |
null | null | null | What does this function do? | def add_new_field():
field_to_update = 'new_field2'
tablename = 'org_organisation'
s3migrate.migrate_to_unique_field(tablename, field_to_update, mapping_function(), ['org_organisation_type', 'org_sector'])
table = db[tablename]
for row in db((table.id > 0)).select(['id'], table[field_to_update]):
print 'id = ', ... | null | null | null | Test for S3Migrate().migrate_to_unique_field function | pcsd | def add new field field to update = 'new field2' tablename = 'org organisation' s3migrate migrate to unique field tablename field to update mapping function ['org organisation type' 'org sector'] table = db[tablename] for row in db table id > 0 select ['id'] table[field to update] print 'id = ' row['id'] field to updat... | 1936 | def add_new_field():
field_to_update = 'new_field2'
tablename = 'org_organisation'
s3migrate.migrate_to_unique_field(tablename, field_to_update, mapping_function(), ['org_organisation_type', 'org_sector'])
table = db[tablename]
for row in db((table.id > 0)).select(['id'], table[field_to_update]):
print 'id = ', ... | Test for S3Migrate().migrate_to_unique_field function | test for s3migrate ( ) . migrate _ to _ unique _ field function | Question:
What does this function do?
Code:
def add_new_field():
field_to_update = 'new_field2'
tablename = 'org_organisation'
s3migrate.migrate_to_unique_field(tablename, field_to_update, mapping_function(), ['org_organisation_type', 'org_sector'])
table = db[tablename]
for row in db((table.id > 0)).select(['i... |
null | null | null | What does this function do? | def MFI(barDs, count, timeperiod=(- (2 ** 31))):
return call_talib_with_hlcv(barDs, count, talib.MFI, timeperiod)
| null | null | null | Money Flow Index | pcsd | def MFI bar Ds count timeperiod= - 2 ** 31 return call talib with hlcv bar Ds count talib MFI timeperiod | 1962 | def MFI(barDs, count, timeperiod=(- (2 ** 31))):
return call_talib_with_hlcv(barDs, count, talib.MFI, timeperiod)
| Money Flow Index | money flow index | Question:
What does this function do?
Code:
def MFI(barDs, count, timeperiod=(- (2 ** 31))):
return call_talib_with_hlcv(barDs, count, talib.MFI, timeperiod)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.