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 the code destroy if it does not exist ?
| def backup_destroy(context, backup_id):
return IMPL.backup_destroy(context, backup_id)
| null | null | null | the backup or raise
| codeqa | def backup destroy context backup id return IMPL backup destroy context backup id
| null | null | null | null | Question:
What does the code destroy if it does not exist ?
Code:
def backup_destroy(context, backup_id):
return IMPL.backup_destroy(context, backup_id)
|
null | null | null | What does the code remove ?
| def removeGeneratedFiles():
gcodeFilePaths = archive.getFilesWithFileTypesWithoutWordsRecursively(['gcode'])
for gcodeFilePath in gcodeFilePaths:
if ('alterations' not in gcodeFilePath):
os.remove(gcodeFilePath)
print ('removeGeneratedFiles deleted ' + gcodeFilePath)
svgFilePaths = archive.getFilesWithFileTypesWithoutWordsRecursively(['svg'])
for svgFilePath in svgFilePaths:
if archive.getEndsWithList(svgFilePath, ['_bottom.svg', '_carve.svg', '_chop.svg', '_cleave.svg']):
os.remove(svgFilePath)
print ('removeGeneratedFiles deleted ' + svgFilePath)
xmlFilePaths = archive.getFilesWithFileTypesWithoutWordsRecursively(['xml'])
for xmlFilePath in xmlFilePaths:
if archive.getEndsWithList(xmlFilePath, ['_interpret.xml']):
os.remove(xmlFilePath)
print ('removeGeneratedFiles deleted ' + xmlFilePath)
archive.removeBackupFilesByTypes(['gcode', 'svg', 'xml'])
| null | null | null | files
| codeqa | def remove Generated Files gcode File Paths archive get Files With File Types Without Words Recursively ['gcode'] for gcode File Path in gcode File Paths if 'alterations' not in gcode File Path os remove gcode File Path print 'remove Generated Filesdeleted' + gcode File Path svg File Paths archive get Files With File Types Without Words Recursively ['svg'] for svg File Path in svg File Paths if archive get Ends With List svg File Path [' bottom svg' ' carve svg' ' chop svg' ' cleave svg'] os remove svg File Path print 'remove Generated Filesdeleted' + svg File Path xml File Paths archive get Files With File Types Without Words Recursively ['xml'] for xml File Path in xml File Paths if archive get Ends With List xml File Path [' interpret xml'] os remove xml File Path print 'remove Generated Filesdeleted' + xml File Path archive remove Backup Files By Types ['gcode' 'svg' 'xml']
| null | null | null | null | Question:
What does the code remove ?
Code:
def removeGeneratedFiles():
gcodeFilePaths = archive.getFilesWithFileTypesWithoutWordsRecursively(['gcode'])
for gcodeFilePath in gcodeFilePaths:
if ('alterations' not in gcodeFilePath):
os.remove(gcodeFilePath)
print ('removeGeneratedFiles deleted ' + gcodeFilePath)
svgFilePaths = archive.getFilesWithFileTypesWithoutWordsRecursively(['svg'])
for svgFilePath in svgFilePaths:
if archive.getEndsWithList(svgFilePath, ['_bottom.svg', '_carve.svg', '_chop.svg', '_cleave.svg']):
os.remove(svgFilePath)
print ('removeGeneratedFiles deleted ' + svgFilePath)
xmlFilePaths = archive.getFilesWithFileTypesWithoutWordsRecursively(['xml'])
for xmlFilePath in xmlFilePaths:
if archive.getEndsWithList(xmlFilePath, ['_interpret.xml']):
os.remove(xmlFilePath)
print ('removeGeneratedFiles deleted ' + xmlFilePath)
archive.removeBackupFilesByTypes(['gcode', 'svg', 'xml'])
|
null | null | null | What does the code add to text between the tags by the given indentation level ?
| @register.tag
def indentby(parser, token):
args = token.split_contents()
largs = len(args)
if (largs not in (2, 4)):
raise template.TemplateSyntaxError('%r tag requires 1 or 3 arguments')
indent_level = args[1]
if_statement = None
if (largs == 4):
if_statement = args[3]
nodelist = parser.parse(('endindentby',))
parser.delete_first_token()
return IndentByNode(nodelist, indent_level, if_statement)
| null | null | null | indentation
| codeqa | @register tagdef indentby parser token args token split contents largs len args if largs not in 2 4 raise template Template Syntax Error '%rtagrequires 1 or 3 arguments' indent level args[ 1 ]if statement Noneif largs 4 if statement args[ 3 ]nodelist parser parse 'endindentby' parser delete first token return Indent By Node nodelist indent level if statement
| null | null | null | null | Question:
What does the code add to text between the tags by the given indentation level ?
Code:
@register.tag
def indentby(parser, token):
args = token.split_contents()
largs = len(args)
if (largs not in (2, 4)):
raise template.TemplateSyntaxError('%r tag requires 1 or 3 arguments')
indent_level = args[1]
if_statement = None
if (largs == 4):
if_statement = args[3]
nodelist = parser.parse(('endindentby',))
parser.delete_first_token()
return IndentByNode(nodelist, indent_level, if_statement)
|
null | null | null | How does the code add indentation to text between the tags ?
| @register.tag
def indentby(parser, token):
args = token.split_contents()
largs = len(args)
if (largs not in (2, 4)):
raise template.TemplateSyntaxError('%r tag requires 1 or 3 arguments')
indent_level = args[1]
if_statement = None
if (largs == 4):
if_statement = args[3]
nodelist = parser.parse(('endindentby',))
parser.delete_first_token()
return IndentByNode(nodelist, indent_level, if_statement)
| null | null | null | by the given indentation level
| codeqa | @register tagdef indentby parser token args token split contents largs len args if largs not in 2 4 raise template Template Syntax Error '%rtagrequires 1 or 3 arguments' indent level args[ 1 ]if statement Noneif largs 4 if statement args[ 3 ]nodelist parser parse 'endindentby' parser delete first token return Indent By Node nodelist indent level if statement
| null | null | null | null | Question:
How does the code add indentation to text between the tags ?
Code:
@register.tag
def indentby(parser, token):
args = token.split_contents()
largs = len(args)
if (largs not in (2, 4)):
raise template.TemplateSyntaxError('%r tag requires 1 or 3 arguments')
indent_level = args[1]
if_statement = None
if (largs == 4):
if_statement = args[3]
nodelist = parser.parse(('endindentby',))
parser.delete_first_token()
return IndentByNode(nodelist, indent_level, if_statement)
|
null | null | null | What does the code get ?
| def get_grade_book_page(request, course, course_key):
current_offset = request.GET.get('offset', 0)
enrolled_students = User.objects.filter(courseenrollment__course_id=course_key, courseenrollment__is_active=1).order_by('username').select_related('profile')
total_students = enrolled_students.count()
page = calculate_page_info(current_offset, total_students)
offset = page['offset']
total_pages = page['total_pages']
if (total_pages > 1):
enrolled_students = enrolled_students[offset:(offset + MAX_STUDENTS_PER_PAGE_GRADE_BOOK)]
with modulestore().bulk_operations(course.location.course_key):
student_info = [{'username': student.username, 'id': student.id, 'email': student.email, 'grade_summary': CourseGradeFactory().create(student, course).summary} for student in enrolled_students]
return (student_info, page)
| null | null | null | student records per page
| codeqa | def get grade book page request course course key current offset request GET get 'offset' 0 enrolled students User objects filter courseenrollment course id course key courseenrollment is active 1 order by 'username' select related 'profile' total students enrolled students count page calculate page info current offset total students offset page['offset']total pages page['total pages']if total pages > 1 enrolled students enrolled students[offset offset + MAX STUDENTS PER PAGE GRADE BOOK ]with modulestore bulk operations course location course key student info [{'username' student username 'id' student id 'email' student email 'grade summary' Course Grade Factory create student course summary} for student in enrolled students]return student info page
| null | null | null | null | Question:
What does the code get ?
Code:
def get_grade_book_page(request, course, course_key):
current_offset = request.GET.get('offset', 0)
enrolled_students = User.objects.filter(courseenrollment__course_id=course_key, courseenrollment__is_active=1).order_by('username').select_related('profile')
total_students = enrolled_students.count()
page = calculate_page_info(current_offset, total_students)
offset = page['offset']
total_pages = page['total_pages']
if (total_pages > 1):
enrolled_students = enrolled_students[offset:(offset + MAX_STUDENTS_PER_PAGE_GRADE_BOOK)]
with modulestore().bulk_operations(course.location.course_key):
student_info = [{'username': student.username, 'id': student.id, 'email': student.email, 'grade_summary': CourseGradeFactory().create(student, course).summary} for student in enrolled_students]
return (student_info, page)
|
null | null | null | Where do the exceptions happen ?
| def atomic_method(method):
def wrapper(*args, **kwargs):
try:
method(*args, **kwargs)
except Exception:
args[0].exceptionq.put(('A worker thread crashed:\n' + traceback.format_exc()))
return wrapper
| null | null | null | in detached thread atomic tasks
| codeqa | def atomic method method def wrapper *args **kwargs try method *args **kwargs except Exception args[ 0 ] exceptionq put ' Aworkerthreadcrashed \n' + traceback format exc return wrapper
| null | null | null | null | Question:
Where do the exceptions happen ?
Code:
def atomic_method(method):
def wrapper(*args, **kwargs):
try:
method(*args, **kwargs)
except Exception:
args[0].exceptionq.put(('A worker thread crashed:\n' + traceback.format_exc()))
return wrapper
|
null | null | null | Where do them display ?
| def atomic_method(method):
def wrapper(*args, **kwargs):
try:
method(*args, **kwargs)
except Exception:
args[0].exceptionq.put(('A worker thread crashed:\n' + traceback.format_exc()))
return wrapper
| null | null | null | in the logs
| codeqa | def atomic method method def wrapper *args **kwargs try method *args **kwargs except Exception args[ 0 ] exceptionq put ' Aworkerthreadcrashed \n' + traceback format exc return wrapper
| null | null | null | null | Question:
Where do them display ?
Code:
def atomic_method(method):
def wrapper(*args, **kwargs):
try:
method(*args, **kwargs)
except Exception:
args[0].exceptionq.put(('A worker thread crashed:\n' + traceback.format_exc()))
return wrapper
|
null | null | null | What does the code find from the service ?
| def __determine_resource_obj(service, resource):
path = resource.split('.')
node = service
for elem in path:
try:
node = getattr(node, elem)()
except AttributeError:
raise AttributeError('"{0}" has no attribute "{1}"'.format('.'.join(path[0:path.index(elem)]), elem))
return node
| null | null | null | the desired resource object method container
| codeqa | def determine resource obj service resource path resource split ' ' node servicefor elem in path try node getattr node elem except Attribute Error raise Attribute Error '"{ 0 }"hasnoattribute"{ 1 }"' format ' ' join path[ 0 path index elem ] elem return node
| null | null | null | null | Question:
What does the code find from the service ?
Code:
def __determine_resource_obj(service, resource):
path = resource.split('.')
node = service
for elem in path:
try:
node = getattr(node, elem)()
except AttributeError:
raise AttributeError('"{0}" has no attribute "{1}"'.format('.'.join(path[0:path.index(elem)]), elem))
return node
|
null | null | null | When does a tagged value attach to an interface ?
| def taggedValue(key, value):
f_locals = sys._getframe(1).f_locals
tagged_values = f_locals.setdefault(TAGGED_DATA, {})
tagged_values[key] = value
return _decorator_non_return
| null | null | null | at definition time
| codeqa | def tagged Value key value f locals sys getframe 1 f localstagged values f locals setdefault TAGGED DATA {} tagged values[key] valuereturn decorator non return
| null | null | null | null | Question:
When does a tagged value attach to an interface ?
Code:
def taggedValue(key, value):
f_locals = sys._getframe(1).f_locals
tagged_values = f_locals.setdefault(TAGGED_DATA, {})
tagged_values[key] = value
return _decorator_non_return
|
null | null | null | What does the code take from the config ?
| def parse_percent(percent_input):
percent_input = percent_input.rstrip(u'%')
try:
return float(percent_input)
except ValueError:
raise ValueError(u"should be in format '0-x%'")
| null | null | null | a size string
| codeqa | def parse percent percent input percent input percent input rstrip u'%' try return float percent input except Value Error raise Value Error u"shouldbeinformat' 0 -x%'"
| null | null | null | null | Question:
What does the code take from the config ?
Code:
def parse_percent(percent_input):
percent_input = percent_input.rstrip(u'%')
try:
return float(percent_input)
except ValueError:
raise ValueError(u"should be in format '0-x%'")
|
null | null | null | What does the code take ?
| def paginate_search_results(object_class, search_results, page_size, page):
paginator = Paginator(search_results['results'], page_size)
try:
page_number = paginator.validate_number(page)
except InvalidPage:
if (page == 'last'):
page_number = paginator.num_pages
else:
raise Http404("Page is not 'last', nor can it be converted to an int.")
try:
paged_results = paginator.page(page_number)
except InvalidPage as exception:
raise Http404('Invalid page {page_number}: {message}'.format(page_number=page_number, message=str(exception)))
search_queryset_pks = [item['data']['pk'] for item in paged_results.object_list]
queryset = object_class.objects.filter(pk__in=search_queryset_pks)
def ordered_objects(primary_key):
' Returns database object matching the search result object'
for obj in queryset:
if (obj.pk == primary_key):
return obj
object_results = map(ordered_objects, search_queryset_pks)
paged_results.object_list = object_results
return paged_results
| null | null | null | edx - search results
| codeqa | def paginate search results object class search results page size page paginator Paginator search results['results'] page size try page number paginator validate number page except Invalid Page if page 'last' page number paginator num pageselse raise Http 404 " Pageisnot'last' norcanitbeconvertedtoanint " try paged results paginator page page number except Invalid Page as exception raise Http 404 ' Invalidpage{page number} {message}' format page number page number message str exception search queryset pks [item['data']['pk'] for item in paged results object list]queryset object class objects filter pk in search queryset pks def ordered objects primary key ' Returnsdatabaseobjectmatchingthesearchresultobject'for obj in queryset if obj pk primary key return objobject results map ordered objects search queryset pks paged results object list object resultsreturn paged results
| null | null | null | null | Question:
What does the code take ?
Code:
def paginate_search_results(object_class, search_results, page_size, page):
paginator = Paginator(search_results['results'], page_size)
try:
page_number = paginator.validate_number(page)
except InvalidPage:
if (page == 'last'):
page_number = paginator.num_pages
else:
raise Http404("Page is not 'last', nor can it be converted to an int.")
try:
paged_results = paginator.page(page_number)
except InvalidPage as exception:
raise Http404('Invalid page {page_number}: {message}'.format(page_number=page_number, message=str(exception)))
search_queryset_pks = [item['data']['pk'] for item in paged_results.object_list]
queryset = object_class.objects.filter(pk__in=search_queryset_pks)
def ordered_objects(primary_key):
' Returns database object matching the search result object'
for obj in queryset:
if (obj.pk == primary_key):
return obj
object_results = map(ordered_objects, search_queryset_pks)
paged_results.object_list = object_results
return paged_results
|
null | null | null | What does the code return ?
| def paginate_search_results(object_class, search_results, page_size, page):
paginator = Paginator(search_results['results'], page_size)
try:
page_number = paginator.validate_number(page)
except InvalidPage:
if (page == 'last'):
page_number = paginator.num_pages
else:
raise Http404("Page is not 'last', nor can it be converted to an int.")
try:
paged_results = paginator.page(page_number)
except InvalidPage as exception:
raise Http404('Invalid page {page_number}: {message}'.format(page_number=page_number, message=str(exception)))
search_queryset_pks = [item['data']['pk'] for item in paged_results.object_list]
queryset = object_class.objects.filter(pk__in=search_queryset_pks)
def ordered_objects(primary_key):
' Returns database object matching the search result object'
for obj in queryset:
if (obj.pk == primary_key):
return obj
object_results = map(ordered_objects, search_queryset_pks)
paged_results.object_list = object_results
return paged_results
| null | null | null | a page object populated with db objects for that page
| codeqa | def paginate search results object class search results page size page paginator Paginator search results['results'] page size try page number paginator validate number page except Invalid Page if page 'last' page number paginator num pageselse raise Http 404 " Pageisnot'last' norcanitbeconvertedtoanint " try paged results paginator page page number except Invalid Page as exception raise Http 404 ' Invalidpage{page number} {message}' format page number page number message str exception search queryset pks [item['data']['pk'] for item in paged results object list]queryset object class objects filter pk in search queryset pks def ordered objects primary key ' Returnsdatabaseobjectmatchingthesearchresultobject'for obj in queryset if obj pk primary key return objobject results map ordered objects search queryset pks paged results object list object resultsreturn paged results
| null | null | null | null | Question:
What does the code return ?
Code:
def paginate_search_results(object_class, search_results, page_size, page):
paginator = Paginator(search_results['results'], page_size)
try:
page_number = paginator.validate_number(page)
except InvalidPage:
if (page == 'last'):
page_number = paginator.num_pages
else:
raise Http404("Page is not 'last', nor can it be converted to an int.")
try:
paged_results = paginator.page(page_number)
except InvalidPage as exception:
raise Http404('Invalid page {page_number}: {message}'.format(page_number=page_number, message=str(exception)))
search_queryset_pks = [item['data']['pk'] for item in paged_results.object_list]
queryset = object_class.objects.filter(pk__in=search_queryset_pks)
def ordered_objects(primary_key):
' Returns database object matching the search result object'
for obj in queryset:
if (obj.pk == primary_key):
return obj
object_results = map(ordered_objects, search_queryset_pks)
paged_results.object_list = object_results
return paged_results
|
null | null | null | What does the code make ?
| def make_link_node(rawtext, text, url, options):
node = nodes.reference(rawtext, text, refuri=url, *options)
return node
| null | null | null | a rest link node
| codeqa | def make link node rawtext text url options node nodes reference rawtext text refuri url *options return node
| null | null | null | null | Question:
What does the code make ?
Code:
def make_link_node(rawtext, text, url, options):
node = nodes.reference(rawtext, text, refuri=url, *options)
return node
|
null | null | null | What does the code add to _ recent_tiles ?
| def _addRecentTile(layer, coord, format, body, age=300):
key = (layer, coord, format)
due = (time() + age)
_recent_tiles['hash'][key] = (body, due)
_recent_tiles['list'].append((key, due))
logging.debug('TileStache.Core._addRecentTile() added tile to recent tiles: %s', key)
cutoff = 0
for (i, (key, due_by)) in enumerate(_recent_tiles['list']):
if (time() < due_by):
cutoff = i
break
logging.debug('TileStache.Core._addRecentTile() removed tile from recent tiles: %s', key)
try:
del _recent_tiles['hash'][key]
except KeyError:
pass
del _recent_tiles['list'][:cutoff]
| null | null | null | the body of a tile
| codeqa | def add Recent Tile layer coord format body age 300 key layer coord format due time + age recent tiles['hash'][key] body due recent tiles['list'] append key due logging debug ' Tile Stache Core add Recent Tile addedtiletorecenttiles %s' key cutoff 0for i key due by in enumerate recent tiles['list'] if time < due by cutoff ibreaklogging debug ' Tile Stache Core add Recent Tile removedtilefromrecenttiles %s' key try del recent tiles['hash'][key]except Key Error passdel recent tiles['list'][ cutoff]
| null | null | null | null | Question:
What does the code add to _ recent_tiles ?
Code:
def _addRecentTile(layer, coord, format, body, age=300):
key = (layer, coord, format)
due = (time() + age)
_recent_tiles['hash'][key] = (body, due)
_recent_tiles['list'].append((key, due))
logging.debug('TileStache.Core._addRecentTile() added tile to recent tiles: %s', key)
cutoff = 0
for (i, (key, due_by)) in enumerate(_recent_tiles['list']):
if (time() < due_by):
cutoff = i
break
logging.debug('TileStache.Core._addRecentTile() removed tile from recent tiles: %s', key)
try:
del _recent_tiles['hash'][key]
except KeyError:
pass
del _recent_tiles['list'][:cutoff]
|
null | null | null | What does the code add the body of a tile ?
| def _addRecentTile(layer, coord, format, body, age=300):
key = (layer, coord, format)
due = (time() + age)
_recent_tiles['hash'][key] = (body, due)
_recent_tiles['list'].append((key, due))
logging.debug('TileStache.Core._addRecentTile() added tile to recent tiles: %s', key)
cutoff = 0
for (i, (key, due_by)) in enumerate(_recent_tiles['list']):
if (time() < due_by):
cutoff = i
break
logging.debug('TileStache.Core._addRecentTile() removed tile from recent tiles: %s', key)
try:
del _recent_tiles['hash'][key]
except KeyError:
pass
del _recent_tiles['list'][:cutoff]
| null | null | null | to _ recent_tiles
| codeqa | def add Recent Tile layer coord format body age 300 key layer coord format due time + age recent tiles['hash'][key] body due recent tiles['list'] append key due logging debug ' Tile Stache Core add Recent Tile addedtiletorecenttiles %s' key cutoff 0for i key due by in enumerate recent tiles['list'] if time < due by cutoff ibreaklogging debug ' Tile Stache Core add Recent Tile removedtilefromrecenttiles %s' key try del recent tiles['hash'][key]except Key Error passdel recent tiles['list'][ cutoff]
| null | null | null | null | Question:
What does the code add the body of a tile ?
Code:
def _addRecentTile(layer, coord, format, body, age=300):
key = (layer, coord, format)
due = (time() + age)
_recent_tiles['hash'][key] = (body, due)
_recent_tiles['list'].append((key, due))
logging.debug('TileStache.Core._addRecentTile() added tile to recent tiles: %s', key)
cutoff = 0
for (i, (key, due_by)) in enumerate(_recent_tiles['list']):
if (time() < due_by):
cutoff = i
break
logging.debug('TileStache.Core._addRecentTile() removed tile from recent tiles: %s', key)
try:
del _recent_tiles['hash'][key]
except KeyError:
pass
del _recent_tiles['list'][:cutoff]
|
null | null | null | What does the code get ?
| def serial_for_url(url, *args, **kwargs):
do_open = (not kwargs.pop('do_not_open', False))
klass = Serial
try:
url_lowercase = url.lower()
except AttributeError:
pass
else:
if ('://' in url_lowercase):
protocol = url_lowercase.split('://', 1)[0]
module_name = '.protocol_{}'.format(protocol)
for package_name in protocol_handler_packages:
try:
importlib.import_module(package_name)
handler_module = importlib.import_module(module_name, package_name)
except ImportError:
continue
else:
if hasattr(handler_module, 'serial_class_for_url'):
(url, klass) = handler_module.serial_class_for_url(url)
else:
klass = handler_module.Serial
break
else:
raise ValueError('invalid URL, protocol {!r} not known'.format(protocol))
instance = klass(None, *args, **kwargs)
instance.port = url
if do_open:
instance.open()
return instance
| null | null | null | an instance of the serial class
| codeqa | def serial for url url *args **kwargs do open not kwargs pop 'do not open' False klass Serialtry url lowercase url lower except Attribute Error passelse if ' //' in url lowercase protocol url lowercase split ' //' 1 [0 ]module name ' protocol {}' format protocol for package name in protocol handler packages try importlib import module package name handler module importlib import module module name package name except Import Error continueelse if hasattr handler module 'serial class for url' url klass handler module serial class for url url else klass handler module Serialbreakelse raise Value Error 'invalid URL protocol{ r}notknown' format protocol instance klass None *args **kwargs instance port urlif do open instance open return instance
| null | null | null | null | Question:
What does the code get ?
Code:
def serial_for_url(url, *args, **kwargs):
do_open = (not kwargs.pop('do_not_open', False))
klass = Serial
try:
url_lowercase = url.lower()
except AttributeError:
pass
else:
if ('://' in url_lowercase):
protocol = url_lowercase.split('://', 1)[0]
module_name = '.protocol_{}'.format(protocol)
for package_name in protocol_handler_packages:
try:
importlib.import_module(package_name)
handler_module = importlib.import_module(module_name, package_name)
except ImportError:
continue
else:
if hasattr(handler_module, 'serial_class_for_url'):
(url, klass) = handler_module.serial_class_for_url(url)
else:
klass = handler_module.Serial
break
else:
raise ValueError('invalid URL, protocol {!r} not known'.format(protocol))
instance = klass(None, *args, **kwargs)
instance.port = url
if do_open:
instance.open()
return instance
|
null | null | null | What did the code give ?
| def unread_handler(things, user, unread):
sr_messages = collections.defaultdict(list)
comments = []
messages = []
for thing in things:
if isinstance(thing, Message):
if getattr(thing, 'sr_id', False):
sr_messages[thing.sr_id].append(thing)
else:
messages.append(thing)
else:
comments.append(thing)
if sr_messages:
mod_srs = Subreddit.reverse_moderator_ids(user)
srs = Subreddit._byID(sr_messages.keys())
else:
mod_srs = []
with CachedQueryMutator() as m:
for (sr_id, things) in sr_messages.items():
set_unread(things, user, unread, mutator=m)
if (sr_id in mod_srs):
sr = srs[sr_id]
set_sr_unread(things, sr, unread, mutator=m)
if comments:
set_unread(comments, user, unread, mutator=m)
if messages:
set_unread(messages, user, unread, mutator=m)
| null | null | null | a user
| codeqa | def unread handler things user unread sr messages collections defaultdict list comments []messages []for thing in things if isinstance thing Message if getattr thing 'sr id' False sr messages[thing sr id] append thing else messages append thing else comments append thing if sr messages mod srs Subreddit reverse moderator ids user srs Subreddit by ID sr messages keys else mod srs []with Cached Query Mutator as m for sr id things in sr messages items set unread things user unread mutator m if sr id in mod srs sr srs[sr id]set sr unread things sr unread mutator m if comments set unread comments user unread mutator m if messages set unread messages user unread mutator m
| null | null | null | null | Question:
What did the code give ?
Code:
def unread_handler(things, user, unread):
sr_messages = collections.defaultdict(list)
comments = []
messages = []
for thing in things:
if isinstance(thing, Message):
if getattr(thing, 'sr_id', False):
sr_messages[thing.sr_id].append(thing)
else:
messages.append(thing)
else:
comments.append(thing)
if sr_messages:
mod_srs = Subreddit.reverse_moderator_ids(user)
srs = Subreddit._byID(sr_messages.keys())
else:
mod_srs = []
with CachedQueryMutator() as m:
for (sr_id, things) in sr_messages.items():
set_unread(things, user, unread, mutator=m)
if (sr_id in mod_srs):
sr = srs[sr_id]
set_sr_unread(things, sr, unread, mutator=m)
if comments:
set_unread(comments, user, unread, mutator=m)
if messages:
set_unread(messages, user, unread, mutator=m)
|
null | null | null | What do utility function validate ?
| def _validate_encode_value(value, do_pickle):
flags = 0
stored_value = value
if isinstance(value, str):
pass
elif isinstance(value, unicode):
stored_value = value.encode('utf-8')
flags |= TYPE_UNICODE
elif isinstance(value, bool):
stored_value = str(int(value))
flags |= TYPE_BOOL
elif isinstance(value, int):
stored_value = str(value)
flags |= TYPE_INT
elif isinstance(value, long):
stored_value = str(value)
flags |= TYPE_LONG
else:
stored_value = do_pickle(value)
flags |= TYPE_PICKLED
if (len(stored_value) > MAX_VALUE_SIZE):
raise ValueError(('Values may not be more than %d bytes in length; received %d bytes' % (MAX_VALUE_SIZE, len(stored_value))))
return (stored_value, flags)
| null | null | null | server keys and values
| codeqa | def validate encode value value do pickle flags 0stored value valueif isinstance value str passelif isinstance value unicode stored value value encode 'utf- 8 ' flags TYPE UNICOD Eelif isinstance value bool stored value str int value flags TYPE BOO Lelif isinstance value int stored value str value flags TYPE IN Telif isinstance value long stored value str value flags TYPE LON Gelse stored value do pickle value flags TYPE PICKLE Dif len stored value > MAX VALUE SIZE raise Value Error ' Valuesmaynotbemorethan%dbytesinlength received%dbytes' % MAX VALUE SIZE len stored value return stored value flags
| null | null | null | null | Question:
What do utility function validate ?
Code:
def _validate_encode_value(value, do_pickle):
flags = 0
stored_value = value
if isinstance(value, str):
pass
elif isinstance(value, unicode):
stored_value = value.encode('utf-8')
flags |= TYPE_UNICODE
elif isinstance(value, bool):
stored_value = str(int(value))
flags |= TYPE_BOOL
elif isinstance(value, int):
stored_value = str(value)
flags |= TYPE_INT
elif isinstance(value, long):
stored_value = str(value)
flags |= TYPE_LONG
else:
stored_value = do_pickle(value)
flags |= TYPE_PICKLED
if (len(stored_value) > MAX_VALUE_SIZE):
raise ValueError(('Values may not be more than %d bytes in length; received %d bytes' % (MAX_VALUE_SIZE, len(stored_value))))
return (stored_value, flags)
|
null | null | null | What validates server keys and values ?
| def _validate_encode_value(value, do_pickle):
flags = 0
stored_value = value
if isinstance(value, str):
pass
elif isinstance(value, unicode):
stored_value = value.encode('utf-8')
flags |= TYPE_UNICODE
elif isinstance(value, bool):
stored_value = str(int(value))
flags |= TYPE_BOOL
elif isinstance(value, int):
stored_value = str(value)
flags |= TYPE_INT
elif isinstance(value, long):
stored_value = str(value)
flags |= TYPE_LONG
else:
stored_value = do_pickle(value)
flags |= TYPE_PICKLED
if (len(stored_value) > MAX_VALUE_SIZE):
raise ValueError(('Values may not be more than %d bytes in length; received %d bytes' % (MAX_VALUE_SIZE, len(stored_value))))
return (stored_value, flags)
| null | null | null | utility function
| codeqa | def validate encode value value do pickle flags 0stored value valueif isinstance value str passelif isinstance value unicode stored value value encode 'utf- 8 ' flags TYPE UNICOD Eelif isinstance value bool stored value str int value flags TYPE BOO Lelif isinstance value int stored value str value flags TYPE IN Telif isinstance value long stored value str value flags TYPE LON Gelse stored value do pickle value flags TYPE PICKLE Dif len stored value > MAX VALUE SIZE raise Value Error ' Valuesmaynotbemorethan%dbytesinlength received%dbytes' % MAX VALUE SIZE len stored value return stored value flags
| null | null | null | null | Question:
What validates server keys and values ?
Code:
def _validate_encode_value(value, do_pickle):
flags = 0
stored_value = value
if isinstance(value, str):
pass
elif isinstance(value, unicode):
stored_value = value.encode('utf-8')
flags |= TYPE_UNICODE
elif isinstance(value, bool):
stored_value = str(int(value))
flags |= TYPE_BOOL
elif isinstance(value, int):
stored_value = str(value)
flags |= TYPE_INT
elif isinstance(value, long):
stored_value = str(value)
flags |= TYPE_LONG
else:
stored_value = do_pickle(value)
flags |= TYPE_PICKLED
if (len(stored_value) > MAX_VALUE_SIZE):
raise ValueError(('Values may not be more than %d bytes in length; received %d bytes' % (MAX_VALUE_SIZE, len(stored_value))))
return (stored_value, flags)
|
null | null | null | What does the code get ?
| def security_group_rule_get_by_instance(context, instance_uuid):
return IMPL.security_group_rule_get_by_instance(context, instance_uuid)
| null | null | null | all rules for a given instance
| codeqa | def security group rule get by instance context instance uuid return IMPL security group rule get by instance context instance uuid
| null | null | null | null | Question:
What does the code get ?
Code:
def security_group_rule_get_by_instance(context, instance_uuid):
return IMPL.security_group_rule_get_by_instance(context, instance_uuid)
|
null | null | null | What did the code build ?
| def build_desired_iface_config(module):
module.custom_desired_config = {'addr_family': None, 'auto': True, 'config': {}, 'name': module.params.get('name')}
build_addr_method(module)
build_address(module)
build_vids(module)
build_pvid(module)
build_speed(module)
build_alias_name(module)
build_vrr(module)
for _attr in ['mtu', 'mstpctl_portnetwork', 'mstpctl_portadminedge', 'mstpctl_bpduguard', 'clagd_enable', 'clagd_priority', 'clagd_peer_ip', 'clagd_sys_mac', 'clagd_args']:
build_generic_attr(module, _attr)
| null | null | null | ifupdown2 compatible hash
| codeqa | def build desired iface config module module custom desired config {'addr family' None 'auto' True 'config' {} 'name' module params get 'name' }build addr method module build address module build vids module build pvid module build speed module build alias name module build vrr module for attr in ['mtu' 'mstpctl portnetwork' 'mstpctl portadminedge' 'mstpctl bpduguard' 'clagd enable' 'clagd priority' 'clagd peer ip' 'clagd sys mac' 'clagd args'] build generic attr module attr
| null | null | null | null | Question:
What did the code build ?
Code:
def build_desired_iface_config(module):
module.custom_desired_config = {'addr_family': None, 'auto': True, 'config': {}, 'name': module.params.get('name')}
build_addr_method(module)
build_address(module)
build_vids(module)
build_pvid(module)
build_speed(module)
build_alias_name(module)
build_vrr(module)
for _attr in ['mtu', 'mstpctl_portnetwork', 'mstpctl_portadminedge', 'mstpctl_bpduguard', 'clagd_enable', 'clagd_priority', 'clagd_peer_ip', 'clagd_sys_mac', 'clagd_args']:
build_generic_attr(module, _attr)
|
null | null | null | What does the code take ?
| def build_desired_iface_config(module):
module.custom_desired_config = {'addr_family': None, 'auto': True, 'config': {}, 'name': module.params.get('name')}
build_addr_method(module)
build_address(module)
build_vids(module)
build_pvid(module)
build_speed(module)
build_alias_name(module)
build_vrr(module)
for _attr in ['mtu', 'mstpctl_portnetwork', 'mstpctl_portadminedge', 'mstpctl_bpduguard', 'clagd_enable', 'clagd_priority', 'clagd_peer_ip', 'clagd_sys_mac', 'clagd_args']:
build_generic_attr(module, _attr)
| null | null | null | parameters defined
| codeqa | def build desired iface config module module custom desired config {'addr family' None 'auto' True 'config' {} 'name' module params get 'name' }build addr method module build address module build vids module build pvid module build speed module build alias name module build vrr module for attr in ['mtu' 'mstpctl portnetwork' 'mstpctl portadminedge' 'mstpctl bpduguard' 'clagd enable' 'clagd priority' 'clagd peer ip' 'clagd sys mac' 'clagd args'] build generic attr module attr
| null | null | null | null | Question:
What does the code take ?
Code:
def build_desired_iface_config(module):
module.custom_desired_config = {'addr_family': None, 'auto': True, 'config': {}, 'name': module.params.get('name')}
build_addr_method(module)
build_address(module)
build_vids(module)
build_pvid(module)
build_speed(module)
build_alias_name(module)
build_vrr(module)
for _attr in ['mtu', 'mstpctl_portnetwork', 'mstpctl_portadminedge', 'mstpctl_bpduguard', 'clagd_enable', 'clagd_priority', 'clagd_peer_ip', 'clagd_sys_mac', 'clagd_args']:
build_generic_attr(module, _attr)
|
null | null | null | What does the code create ?
| def test_show_weights():
skip_if_no_matplotlib()
with open('model.pkl', 'wb') as f:
model = MLP(layers=[Linear(dim=1, layer_name='h0', irange=0.1)], nvis=784)
model.dataset_yaml_src = "\n!obj:pylearn2.datasets.mnist.MNIST {\n which_set: 'train'\n}\n"
cPickle.dump(model, f, protocol=cPickle.HIGHEST_PROTOCOL)
show_weights('model.pkl', rescale='individual', border=True, out='garbage.png')
os.remove('model.pkl')
os.remove('garbage.png')
| null | null | null | a pickled model
| codeqa | def test show weights skip if no matplotlib with open 'model pkl' 'wb' as f model MLP layers [ Linear dim 1 layer name 'h 0 ' irange 0 1 ] nvis 784 model dataset yaml src "\n obj pylearn 2 datasets mnist MNIST{\nwhich set 'train'\n}\n"c Pickle dump model f protocol c Pickle HIGHEST PROTOCOL show weights 'model pkl' rescale 'individual' border True out 'garbage png' os remove 'model pkl' os remove 'garbage png'
| null | null | null | null | Question:
What does the code create ?
Code:
def test_show_weights():
skip_if_no_matplotlib()
with open('model.pkl', 'wb') as f:
model = MLP(layers=[Linear(dim=1, layer_name='h0', irange=0.1)], nvis=784)
model.dataset_yaml_src = "\n!obj:pylearn2.datasets.mnist.MNIST {\n which_set: 'train'\n}\n"
cPickle.dump(model, f, protocol=cPickle.HIGHEST_PROTOCOL)
show_weights('model.pkl', rescale='individual', border=True, out='garbage.png')
os.remove('model.pkl')
os.remove('garbage.png')
|
null | null | null | What does the code show ?
| def test_show_weights():
skip_if_no_matplotlib()
with open('model.pkl', 'wb') as f:
model = MLP(layers=[Linear(dim=1, layer_name='h0', irange=0.1)], nvis=784)
model.dataset_yaml_src = "\n!obj:pylearn2.datasets.mnist.MNIST {\n which_set: 'train'\n}\n"
cPickle.dump(model, f, protocol=cPickle.HIGHEST_PROTOCOL)
show_weights('model.pkl', rescale='individual', border=True, out='garbage.png')
os.remove('model.pkl')
os.remove('garbage.png')
| null | null | null | the weights
| codeqa | def test show weights skip if no matplotlib with open 'model pkl' 'wb' as f model MLP layers [ Linear dim 1 layer name 'h 0 ' irange 0 1 ] nvis 784 model dataset yaml src "\n obj pylearn 2 datasets mnist MNIST{\nwhich set 'train'\n}\n"c Pickle dump model f protocol c Pickle HIGHEST PROTOCOL show weights 'model pkl' rescale 'individual' border True out 'garbage png' os remove 'model pkl' os remove 'garbage png'
| null | null | null | null | Question:
What does the code show ?
Code:
def test_show_weights():
skip_if_no_matplotlib()
with open('model.pkl', 'wb') as f:
model = MLP(layers=[Linear(dim=1, layer_name='h0', irange=0.1)], nvis=784)
model.dataset_yaml_src = "\n!obj:pylearn2.datasets.mnist.MNIST {\n which_set: 'train'\n}\n"
cPickle.dump(model, f, protocol=cPickle.HIGHEST_PROTOCOL)
show_weights('model.pkl', rescale='individual', border=True, out='garbage.png')
os.remove('model.pkl')
os.remove('garbage.png')
|
null | null | null | What do class see ?
| @sync_performer
def perform_delete_s3_keys(dispatcher, intent):
s3 = boto.connect_s3()
bucket = s3.get_bucket(intent.bucket)
bucket.delete_keys([(intent.prefix + key) for key in intent.keys])
| null | null | null | class
| codeqa | @sync performerdef perform delete s3 keys dispatcher intent s3 boto connect s3 bucket s3 get bucket intent bucket bucket delete keys [ intent prefix + key for key in intent keys]
| null | null | null | null | Question:
What do class see ?
Code:
@sync_performer
def perform_delete_s3_keys(dispatcher, intent):
s3 = boto.connect_s3()
bucket = s3.get_bucket(intent.bucket)
bucket.delete_keys([(intent.prefix + key) for key in intent.keys])
|
null | null | null | What sees class ?
| @sync_performer
def perform_delete_s3_keys(dispatcher, intent):
s3 = boto.connect_s3()
bucket = s3.get_bucket(intent.bucket)
bucket.delete_keys([(intent.prefix + key) for key in intent.keys])
| null | null | null | class
| codeqa | @sync performerdef perform delete s3 keys dispatcher intent s3 boto connect s3 bucket s3 get bucket intent bucket bucket delete keys [ intent prefix + key for key in intent keys]
| null | null | null | null | Question:
What sees class ?
Code:
@sync_performer
def perform_delete_s3_keys(dispatcher, intent):
s3 = boto.connect_s3()
bucket = s3.get_bucket(intent.bucket)
bucket.delete_keys([(intent.prefix + key) for key in intent.keys])
|
null | null | null | What does the code send to a pushover channel ?
| def post_message(name, user=None, device=None, message=None, title=None, priority=None, expire=None, retry=None, sound=None, api_version=1, token=None):
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
ret['comment'] = 'The following message is to be sent to PushOver: {0}'.format(message)
ret['result'] = None
return ret
if (not user):
ret['comment'] = 'PushOver user is missing: {0}'.format(user)
return ret
if (not message):
ret['comment'] = 'PushOver message is missing: {0}'.format(message)
return ret
result = __salt__['pushover.post_message'](user=user, message=message, title=title, device=device, priority=priority, expire=expire, retry=retry, token=token)
if result:
ret['result'] = True
ret['comment'] = 'Sent message: {0}'.format(name)
else:
ret['comment'] = 'Failed to send message: {0}'.format(name)
return ret
| null | null | null | a message
| codeqa | def post message name user None device None message None title None priority None expire None retry None sound None api version 1 token None ret {'name' name 'changes' {} 'result' False 'comment' ''}if opts ['test'] ret['comment'] ' Thefollowingmessageistobesentto Push Over {0 }' format message ret['result'] Nonereturn retif not user ret['comment'] ' Push Overuserismissing {0 }' format user return retif not message ret['comment'] ' Push Overmessageismissing {0 }' format message return retresult salt ['pushover post message'] user user message message title title device device priority priority expire expire retry retry token token if result ret['result'] Trueret['comment'] ' Sentmessage {0 }' format name else ret['comment'] ' Failedtosendmessage {0 }' format name return ret
| null | null | null | null | Question:
What does the code send to a pushover channel ?
Code:
def post_message(name, user=None, device=None, message=None, title=None, priority=None, expire=None, retry=None, sound=None, api_version=1, token=None):
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
ret['comment'] = 'The following message is to be sent to PushOver: {0}'.format(message)
ret['result'] = None
return ret
if (not user):
ret['comment'] = 'PushOver user is missing: {0}'.format(user)
return ret
if (not message):
ret['comment'] = 'PushOver message is missing: {0}'.format(message)
return ret
result = __salt__['pushover.post_message'](user=user, message=message, title=title, device=device, priority=priority, expire=expire, retry=retry, token=token)
if result:
ret['result'] = True
ret['comment'] = 'Sent message: {0}'.format(name)
else:
ret['comment'] = 'Failed to send message: {0}'.format(name)
return ret
|
null | null | null | What does the code convert to a binary string ?
| def byte2bin(number, classic_mode=True):
text = ''
for i in range(0, 8):
if classic_mode:
mask = (1 << (7 - i))
else:
mask = (1 << i)
if ((number & mask) == mask):
text += '1'
else:
text += '0'
return text
| null | null | null | a byte
| codeqa | def byte 2 bin number classic mode True text ''for i in range 0 8 if classic mode mask 1 << 7 - i else mask 1 << i if number & mask mask text + '1 'else text + '0 'return text
| null | null | null | null | Question:
What does the code convert to a binary string ?
Code:
def byte2bin(number, classic_mode=True):
text = ''
for i in range(0, 8):
if classic_mode:
mask = (1 << (7 - i))
else:
mask = (1 << i)
if ((number & mask) == mask):
text += '1'
else:
text += '0'
return text
|
null | null | null | Where does the code extract the block of code ?
| def getblock(lines):
blockfinder = BlockFinder()
try:
tokenize.tokenize(iter(lines).next, blockfinder.tokeneater)
except (EndOfBlock, IndentationError):
pass
return lines[:blockfinder.last]
| null | null | null | at the top of the given list of lines
| codeqa | def getblock lines blockfinder Block Finder try tokenize tokenize iter lines next blockfinder tokeneater except End Of Block Indentation Error passreturn lines[ blockfinder last]
| null | null | null | null | Question:
Where does the code extract the block of code ?
Code:
def getblock(lines):
blockfinder = BlockFinder()
try:
tokenize.tokenize(iter(lines).next, blockfinder.tokeneater)
except (EndOfBlock, IndentationError):
pass
return lines[:blockfinder.last]
|
null | null | null | What does the code extract at the top of the given list of lines ?
| def getblock(lines):
blockfinder = BlockFinder()
try:
tokenize.tokenize(iter(lines).next, blockfinder.tokeneater)
except (EndOfBlock, IndentationError):
pass
return lines[:blockfinder.last]
| null | null | null | the block of code
| codeqa | def getblock lines blockfinder Block Finder try tokenize tokenize iter lines next blockfinder tokeneater except End Of Block Indentation Error passreturn lines[ blockfinder last]
| null | null | null | null | Question:
What does the code extract at the top of the given list of lines ?
Code:
def getblock(lines):
blockfinder = BlockFinder()
try:
tokenize.tokenize(iter(lines).next, blockfinder.tokeneater)
except (EndOfBlock, IndentationError):
pass
return lines[:blockfinder.last]
|
null | null | null | What does the code convert into a list ?
| def tolist(val):
if (val is None):
return None
try:
val.extend([])
return val
except AttributeError:
pass
try:
return re.split('\\s*,\\s*', val)
except TypeError:
return list(val)
| null | null | null | a value that may be a list or a string
| codeqa | def tolist val if val is None return Nonetry val extend [] return valexcept Attribute Error passtry return re split '\\s* \\s*' val except Type Error return list val
| null | null | null | null | Question:
What does the code convert into a list ?
Code:
def tolist(val):
if (val is None):
return None
try:
val.extend([])
return val
except AttributeError:
pass
try:
return re.split('\\s*,\\s*', val)
except TypeError:
return list(val)
|
null | null | null | What does the code remove from the given string ?
| def deaccent(text):
if (not isinstance(text, unicode)):
text = text.decode('utf8')
norm = unicodedata.normalize('NFD', text)
result = u('').join((ch for ch in norm if (unicodedata.category(ch) != 'Mn')))
return unicodedata.normalize('NFC', result)
| null | null | null | accentuation
| codeqa | def deaccent text if not isinstance text unicode text text decode 'utf 8 ' norm unicodedata normalize 'NFD' text result u '' join ch for ch in norm if unicodedata category ch ' Mn' return unicodedata normalize 'NFC' result
| null | null | null | null | Question:
What does the code remove from the given string ?
Code:
def deaccent(text):
if (not isinstance(text, unicode)):
text = text.decode('utf8')
norm = unicodedata.normalize('NFD', text)
result = u('').join((ch for ch in norm if (unicodedata.category(ch) != 'Mn')))
return unicodedata.normalize('NFC', result)
|
null | null | null | What sets to be the task user ?
| def set_task_user(f):
@functools.wraps(f)
def wrapper(*args, **kw):
old_user = get_user()
set_user(get_task_user())
try:
result = f(*args, **kw)
finally:
set_user(old_user)
return result
return wrapper
| null | null | null | the user
| codeqa | def set task user f @functools wraps f def wrapper *args **kw old user get user set user get task user try result f *args **kw finally set user old user return resultreturn wrapper
| null | null | null | null | Question:
What sets to be the task user ?
Code:
def set_task_user(f):
@functools.wraps(f)
def wrapper(*args, **kw):
old_user = get_user()
set_user(get_task_user())
try:
result = f(*args, **kw)
finally:
set_user(old_user)
return result
return wrapper
|
null | null | null | What does the user set ?
| def set_task_user(f):
@functools.wraps(f)
def wrapper(*args, **kw):
old_user = get_user()
set_user(get_task_user())
try:
result = f(*args, **kw)
finally:
set_user(old_user)
return result
return wrapper
| null | null | null | to be the task user
| codeqa | def set task user f @functools wraps f def wrapper *args **kw old user get user set user get task user try result f *args **kw finally set user old user return resultreturn wrapper
| null | null | null | null | Question:
What does the user set ?
Code:
def set_task_user(f):
@functools.wraps(f)
def wrapper(*args, **kw):
old_user = get_user()
set_user(get_task_user())
try:
result = f(*args, **kw)
finally:
set_user(old_user)
return result
return wrapper
|
null | null | null | What does the code take ?
| def dynamize_value(val):
dynamodb_type = get_dynamodb_type(val)
if (dynamodb_type == 'N'):
val = {dynamodb_type: serialize_num(val)}
elif (dynamodb_type == 'S'):
val = {dynamodb_type: val}
elif (dynamodb_type == 'NS'):
val = {dynamodb_type: list(map(serialize_num, val))}
elif (dynamodb_type == 'SS'):
val = {dynamodb_type: [n for n in val]}
elif (dynamodb_type == 'B'):
if isinstance(val, bytes):
val = Binary(val)
val = {dynamodb_type: val.encode()}
elif (dynamodb_type == 'BS'):
val = {dynamodb_type: [n.encode() for n in val]}
return val
| null | null | null | a scalar python value
| codeqa | def dynamize value val dynamodb type get dynamodb type val if dynamodb type 'N' val {dynamodb type serialize num val }elif dynamodb type 'S' val {dynamodb type val}elif dynamodb type 'NS' val {dynamodb type list map serialize num val }elif dynamodb type 'SS' val {dynamodb type [n for n in val]}elif dynamodb type 'B' if isinstance val bytes val Binary val val {dynamodb type val encode }elif dynamodb type 'BS' val {dynamodb type [n encode for n in val]}return val
| null | null | null | null | Question:
What does the code take ?
Code:
def dynamize_value(val):
dynamodb_type = get_dynamodb_type(val)
if (dynamodb_type == 'N'):
val = {dynamodb_type: serialize_num(val)}
elif (dynamodb_type == 'S'):
val = {dynamodb_type: val}
elif (dynamodb_type == 'NS'):
val = {dynamodb_type: list(map(serialize_num, val))}
elif (dynamodb_type == 'SS'):
val = {dynamodb_type: [n for n in val]}
elif (dynamodb_type == 'B'):
if isinstance(val, bytes):
val = Binary(val)
val = {dynamodb_type: val.encode()}
elif (dynamodb_type == 'BS'):
val = {dynamodb_type: [n.encode() for n in val]}
return val
|
null | null | null | What redirects /foo/ to /foo ?
| def get_redirect_route(regex_route, handler, defaults=None):
if (defaults is None):
defaults = {}
name = regex_route.replace('/', '_')
return RedirectRoute(regex_route, handler, name, strict_slash=True, defaults=defaults)
| null | null | null | a route
| codeqa | def get redirect route regex route handler defaults None if defaults is None defaults {}name regex route replace '/' ' ' return Redirect Route regex route handler name strict slash True defaults defaults
| null | null | null | null | Question:
What redirects /foo/ to /foo ?
Code:
def get_redirect_route(regex_route, handler, defaults=None):
if (defaults is None):
defaults = {}
name = regex_route.replace('/', '_')
return RedirectRoute(regex_route, handler, name, strict_slash=True, defaults=defaults)
|
null | null | null | What does a route redirect to /foo ?
| def get_redirect_route(regex_route, handler, defaults=None):
if (defaults is None):
defaults = {}
name = regex_route.replace('/', '_')
return RedirectRoute(regex_route, handler, name, strict_slash=True, defaults=defaults)
| null | null | null | /foo/
| codeqa | def get redirect route regex route handler defaults None if defaults is None defaults {}name regex route replace '/' ' ' return Redirect Route regex route handler name strict slash True defaults defaults
| null | null | null | null | Question:
What does a route redirect to /foo ?
Code:
def get_redirect_route(regex_route, handler, defaults=None):
if (defaults is None):
defaults = {}
name = regex_route.replace('/', '_')
return RedirectRoute(regex_route, handler, name, strict_slash=True, defaults=defaults)
|
null | null | null | What does the code test ?
| @with_setup(prepare_stdout)
def test_output_with_success_colorless_with_table():
runner = Runner(feature_name('success_table'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines('\nFeature: Table Success # tests/functional/output_features/success_table/success_table.feature:1\n\n Scenario: Add two numbers \xe2\x99\xa5 # tests/functional/output_features/success_table/success_table.feature:2\n Given I have 0 bucks # tests/functional/output_features/success_table/success_table_steps.py:28\n And that I have these items: # tests/functional/output_features/success_table/success_table_steps.py:32\n | name | price |\n | Porsche | 200000 |\n | Ferrari | 400000 |\n When I sell the "Ferrari" # tests/functional/output_features/success_table/success_table_steps.py:42\n Then I have 400000 bucks # tests/functional/output_features/success_table/success_table_steps.py:28\n And my garage contains: # tests/functional/output_features/success_table/success_table_steps.py:47\n | name | price |\n | Porsche | 200000 |\n\n1 feature (1 passed)\n1 scenario (1 passed)\n5 steps (5 passed)\n')
| null | null | null | the colorless output of success with table
| codeqa | @with setup prepare stdout def test output with success colorless with table runner Runner feature name 'success table' verbosity 3 no color True runner run assert stdout lines '\n Feature Table Success#tests/functional/output features/success table/success table feature 1\n\n Scenario Addtwonumbers\xe 2 \x 99 \xa 5 #tests/functional/output features/success table/success table feature 2\n Given Ihave 0 bucks#tests/functional/output features/success table/success table steps py 28 \n Andthat Ihavetheseitems #tests/functional/output features/success table/success table steps py 32 \n name price \n Porsche 200000 \n Ferrari 400000 \n When Isellthe" Ferrari"#tests/functional/output features/success table/success table steps py 42 \n Then Ihave 400000 bucks#tests/functional/output features/success table/success table steps py 28 \n Andmygaragecontains #tests/functional/output features/success table/success table steps py 47 \n name price \n Porsche 200000 \n\n 1 feature 1passed \n 1 scenario 1passed \n 5 steps 5passed \n'
| null | null | null | null | Question:
What does the code test ?
Code:
@with_setup(prepare_stdout)
def test_output_with_success_colorless_with_table():
runner = Runner(feature_name('success_table'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines('\nFeature: Table Success # tests/functional/output_features/success_table/success_table.feature:1\n\n Scenario: Add two numbers \xe2\x99\xa5 # tests/functional/output_features/success_table/success_table.feature:2\n Given I have 0 bucks # tests/functional/output_features/success_table/success_table_steps.py:28\n And that I have these items: # tests/functional/output_features/success_table/success_table_steps.py:32\n | name | price |\n | Porsche | 200000 |\n | Ferrari | 400000 |\n When I sell the "Ferrari" # tests/functional/output_features/success_table/success_table_steps.py:42\n Then I have 400000 bucks # tests/functional/output_features/success_table/success_table_steps.py:28\n And my garage contains: # tests/functional/output_features/success_table/success_table_steps.py:47\n | name | price |\n | Porsche | 200000 |\n\n1 feature (1 passed)\n1 scenario (1 passed)\n5 steps (5 passed)\n')
|
null | null | null | What does the code pull from the thing / data tables ?
| def fetch_query(table, id_col, thing_id):
single = False
if (not isinstance(thing_id, iters)):
single = True
thing_id = (thing_id,)
s = sa.select([table], id_col.in_(thing_id))
try:
r = add_request_info(s).execute().fetchall()
except Exception as e:
dbm.mark_dead(table.bind)
raise
return (r, single)
| null | null | null | the columns
| codeqa | def fetch query table id col thing id single Falseif not isinstance thing id iters single Truething id thing id s sa select [table] id col in thing id try r add request info s execute fetchall except Exception as e dbm mark dead table bind raisereturn r single
| null | null | null | null | Question:
What does the code pull from the thing / data tables ?
Code:
def fetch_query(table, id_col, thing_id):
single = False
if (not isinstance(thing_id, iters)):
single = True
thing_id = (thing_id,)
s = sa.select([table], id_col.in_(thing_id))
try:
r = add_request_info(s).execute().fetchall()
except Exception as e:
dbm.mark_dead(table.bind)
raise
return (r, single)
|
null | null | null | What do returns put ?
| @app.route('/put', methods=('PUT',))
def view_put():
return jsonify(get_dict('url', 'args', 'form', 'data', 'origin', 'headers', 'files', 'json'))
| null | null | null | data
| codeqa | @app route '/put' methods 'PUT' def view put return jsonify get dict 'url' 'args' 'form' 'data' 'origin' 'headers' 'files' 'json'
| null | null | null | null | Question:
What do returns put ?
Code:
@app.route('/put', methods=('PUT',))
def view_put():
return jsonify(get_dict('url', 'args', 'form', 'data', 'origin', 'headers', 'files', 'json'))
|
null | null | null | What put data ?
| @app.route('/put', methods=('PUT',))
def view_put():
return jsonify(get_dict('url', 'args', 'form', 'data', 'origin', 'headers', 'files', 'json'))
| null | null | null | returns
| codeqa | @app route '/put' methods 'PUT' def view put return jsonify get dict 'url' 'args' 'form' 'data' 'origin' 'headers' 'files' 'json'
| null | null | null | null | Question:
What put data ?
Code:
@app.route('/put', methods=('PUT',))
def view_put():
return jsonify(get_dict('url', 'args', 'form', 'data', 'origin', 'headers', 'files', 'json'))
|
null | null | null | What is containing the hold expression ?
| def _get_hold(line, pattern=__HOLD_PATTERN, full=True):
if full:
if (_yum() == 'dnf'):
lock_re = '({0}-\\S+)'.format(pattern)
else:
lock_re = '(\\d+:{0}-\\S+)'.format(pattern)
elif (_yum() == 'dnf'):
lock_re = '({0}-\\S+)'.format(pattern)
else:
lock_re = '\\d+:({0}-\\S+)'.format(pattern)
match = re.search(lock_re, line)
if match:
if (not full):
woarch = match.group(1).rsplit('.', 1)[0]
worel = woarch.rsplit('-', 1)[0]
return worel.rsplit('-', 1)[0]
else:
return match.group(1)
return None
| null | null | null | a line
| codeqa | def get hold line pattern HOLD PATTERN full True if full if yum 'dnf' lock re ' {0 }-\\S+ ' format pattern else lock re ' \\d+ {0 }-\\S+ ' format pattern elif yum 'dnf' lock re ' {0 }-\\S+ ' format pattern else lock re '\\d+ {0 }-\\S+ ' format pattern match re search lock re line if match if not full woarch match group 1 rsplit ' ' 1 [0 ]worel woarch rsplit '-' 1 [0 ]return worel rsplit '-' 1 [0 ]else return match group 1 return None
| null | null | null | null | Question:
What is containing the hold expression ?
Code:
def _get_hold(line, pattern=__HOLD_PATTERN, full=True):
if full:
if (_yum() == 'dnf'):
lock_re = '({0}-\\S+)'.format(pattern)
else:
lock_re = '(\\d+:{0}-\\S+)'.format(pattern)
elif (_yum() == 'dnf'):
lock_re = '({0}-\\S+)'.format(pattern)
else:
lock_re = '\\d+:({0}-\\S+)'.format(pattern)
match = re.search(lock_re, line)
if match:
if (not full):
woarch = match.group(1).rsplit('.', 1)[0]
worel = woarch.rsplit('-', 1)[0]
return worel.rsplit('-', 1)[0]
else:
return match.group(1)
return None
|
null | null | null | What does the code resolve from a line containing the hold expression ?
| def _get_hold(line, pattern=__HOLD_PATTERN, full=True):
if full:
if (_yum() == 'dnf'):
lock_re = '({0}-\\S+)'.format(pattern)
else:
lock_re = '(\\d+:{0}-\\S+)'.format(pattern)
elif (_yum() == 'dnf'):
lock_re = '({0}-\\S+)'.format(pattern)
else:
lock_re = '\\d+:({0}-\\S+)'.format(pattern)
match = re.search(lock_re, line)
if match:
if (not full):
woarch = match.group(1).rsplit('.', 1)[0]
worel = woarch.rsplit('-', 1)[0]
return worel.rsplit('-', 1)[0]
else:
return match.group(1)
return None
| null | null | null | a package name
| codeqa | def get hold line pattern HOLD PATTERN full True if full if yum 'dnf' lock re ' {0 }-\\S+ ' format pattern else lock re ' \\d+ {0 }-\\S+ ' format pattern elif yum 'dnf' lock re ' {0 }-\\S+ ' format pattern else lock re '\\d+ {0 }-\\S+ ' format pattern match re search lock re line if match if not full woarch match group 1 rsplit ' ' 1 [0 ]worel woarch rsplit '-' 1 [0 ]return worel rsplit '-' 1 [0 ]else return match group 1 return None
| null | null | null | null | Question:
What does the code resolve from a line containing the hold expression ?
Code:
def _get_hold(line, pattern=__HOLD_PATTERN, full=True):
if full:
if (_yum() == 'dnf'):
lock_re = '({0}-\\S+)'.format(pattern)
else:
lock_re = '(\\d+:{0}-\\S+)'.format(pattern)
elif (_yum() == 'dnf'):
lock_re = '({0}-\\S+)'.format(pattern)
else:
lock_re = '\\d+:({0}-\\S+)'.format(pattern)
match = re.search(lock_re, line)
if match:
if (not full):
woarch = match.group(1).rsplit('.', 1)[0]
worel = woarch.rsplit('-', 1)[0]
return worel.rsplit('-', 1)[0]
else:
return match.group(1)
return None
|
null | null | null | What does the code create from a parser ?
| def extractMetadata(parser, quality=QUALITY_NORMAL):
try:
extractor = extractors[parser.__class__]
except KeyError:
return None
metadata = extractor(quality)
try:
metadata.extract(parser)
except HACHOIR_ERRORS as err:
error(('Error during metadata extraction: %s' % unicode(err)))
return None
except Exception as err:
error(('Error during metadata extraction: %s' % unicode(err)))
return None
if metadata:
metadata.mime_type = parser.mime_type
metadata.endian = endian_name[parser.endian]
return metadata
| null | null | null | a metadata class
| codeqa | def extract Metadata parser quality QUALITY NORMAL try extractor extractors[parser class ]except Key Error return Nonemetadata extractor quality try metadata extract parser except HACHOIR ERRORS as err error ' Errorduringmetadataextraction %s' % unicode err return Noneexcept Exception as err error ' Errorduringmetadataextraction %s' % unicode err return Noneif metadata metadata mime type parser mime typemetadata endian endian name[parser endian]return metadata
| null | null | null | null | Question:
What does the code create from a parser ?
Code:
def extractMetadata(parser, quality=QUALITY_NORMAL):
try:
extractor = extractors[parser.__class__]
except KeyError:
return None
metadata = extractor(quality)
try:
metadata.extract(parser)
except HACHOIR_ERRORS as err:
error(('Error during metadata extraction: %s' % unicode(err)))
return None
except Exception as err:
error(('Error during metadata extraction: %s' % unicode(err)))
return None
if metadata:
metadata.mime_type = parser.mime_type
metadata.endian = endian_name[parser.endian]
return metadata
|
null | null | null | What does the code locate ?
| def _find_lteq(a, x):
i = bisect_left(a, x)
if ((i != len(a)) and (a[i] == x)):
return i
raise ValueError
| null | null | null | the leftmost value exactly equal to x
| codeqa | def find lteq a x i bisect left a x if i len a and a[i] x return iraise Value Error
| null | null | null | null | Question:
What does the code locate ?
Code:
def _find_lteq(a, x):
i = bisect_left(a, x)
if ((i != len(a)) and (a[i] == x)):
return i
raise ValueError
|
null | null | null | What does the code make ?
| def make_parser(*features, **kwargs):
if features:
bases = tuple((PARSER_MODULES.get(f, f) for f in features))
parser_class = type('CustomCSSParser', (bases + (CSS21Parser,)), {})
else:
parser_class = CSS21Parser
return parser_class(**kwargs)
| null | null | null | a parser object with the chosen features
| codeqa | def make parser *features **kwargs if features bases tuple PARSER MODULES get f f for f in features parser class type ' Custom CSS Parser' bases + CSS 21 Parser {} else parser class CSS 21 Parserreturn parser class **kwargs
| null | null | null | null | Question:
What does the code make ?
Code:
def make_parser(*features, **kwargs):
if features:
bases = tuple((PARSER_MODULES.get(f, f) for f in features))
parser_class = type('CustomCSSParser', (bases + (CSS21Parser,)), {})
else:
parser_class = CSS21Parser
return parser_class(**kwargs)
|
null | null | null | How do the directory path given remove ?
| def remove_directory(dirpath):
if os.path.exists(dirpath):
shutil.rmtree(dirpath, ignore_errors=True)
| null | null | null | recursively
| codeqa | def remove directory dirpath if os path exists dirpath shutil rmtree dirpath ignore errors True
| null | null | null | null | Question:
How do the directory path given remove ?
Code:
def remove_directory(dirpath):
if os.path.exists(dirpath):
shutil.rmtree(dirpath, ignore_errors=True)
|
null | null | null | What does self documenting step indicate ?
| @then('it should pass because "{reason}"')
def then_it_should_pass_because(context, reason):
pass
| null | null | null | some reason
| codeqa | @then 'itshouldpassbecause"{reason}"' def then it should pass because context reason pass
| null | null | null | null | Question:
What does self documenting step indicate ?
Code:
@then('it should pass because "{reason}"')
def then_it_should_pass_because(context, reason):
pass
|
null | null | null | What indicates some reason ?
| @then('it should pass because "{reason}"')
def then_it_should_pass_because(context, reason):
pass
| null | null | null | self documenting step
| codeqa | @then 'itshouldpassbecause"{reason}"' def then it should pass because context reason pass
| null | null | null | null | Question:
What indicates some reason ?
Code:
@then('it should pass because "{reason}"')
def then_it_should_pass_because(context, reason):
pass
|
null | null | null | What constructs new matrices from 2d nested lists of numbers ?
| def Matrix(data, typecode=None, copy=1, savespace=0):
if isinstance(data, type('')):
raise TypeError('numerix Matrix does not support Numeric matrix string notation. Use nested lists.')
a = fromlist(data, type=typecode)
if (a.rank == 0):
a.shape = (1, 1)
elif (a.rank == 1):
a.shape = ((1,) + a.shape)
a.__class__ = _Matrix
return a
| null | null | null | matrix
| codeqa | def Matrix data typecode None copy 1 savespace 0 if isinstance data type '' raise Type Error 'numerix Matrixdoesnotsupport Numericmatrixstringnotation Usenestedlists ' a fromlist data type typecode if a rank 0 a shape 1 1 elif a rank 1 a shape 1 + a shape a class Matrixreturn a
| null | null | null | null | Question:
What constructs new matrices from 2d nested lists of numbers ?
Code:
def Matrix(data, typecode=None, copy=1, savespace=0):
if isinstance(data, type('')):
raise TypeError('numerix Matrix does not support Numeric matrix string notation. Use nested lists.')
a = fromlist(data, type=typecode)
if (a.rank == 0):
a.shape = (1, 1)
elif (a.rank == 1):
a.shape = ((1,) + a.shape)
a.__class__ = _Matrix
return a
|
null | null | null | What does matrix construct ?
| def Matrix(data, typecode=None, copy=1, savespace=0):
if isinstance(data, type('')):
raise TypeError('numerix Matrix does not support Numeric matrix string notation. Use nested lists.')
a = fromlist(data, type=typecode)
if (a.rank == 0):
a.shape = (1, 1)
elif (a.rank == 1):
a.shape = ((1,) + a.shape)
a.__class__ = _Matrix
return a
| null | null | null | new matrices from 2d nested lists of numbers
| codeqa | def Matrix data typecode None copy 1 savespace 0 if isinstance data type '' raise Type Error 'numerix Matrixdoesnotsupport Numericmatrixstringnotation Usenestedlists ' a fromlist data type typecode if a rank 0 a shape 1 1 elif a rank 1 a shape 1 + a shape a class Matrixreturn a
| null | null | null | null | Question:
What does matrix construct ?
Code:
def Matrix(data, typecode=None, copy=1, savespace=0):
if isinstance(data, type('')):
raise TypeError('numerix Matrix does not support Numeric matrix string notation. Use nested lists.')
a = fromlist(data, type=typecode)
if (a.rank == 0):
a.shape = (1, 1)
elif (a.rank == 1):
a.shape = ((1,) + a.shape)
a.__class__ = _Matrix
return a
|
null | null | null | What is the private key here ?
| def decipher_kid_rsa(msg, key):
(n, d) = key
return ((msg * d) % n)
| null | null | null | msg
| codeqa | def decipher kid rsa msg key n d keyreturn msg * d % n
| null | null | null | null | Question:
What is the private key here ?
Code:
def decipher_kid_rsa(msg, key):
(n, d) = key
return ((msg * d) % n)
|
null | null | null | For what purpose do a string split ?
| def split_title(title, width, title_fs):
titles = []
if (not title):
return titles
size = reverse_text_len(width, (title_fs * 1.1))
title_lines = title.split('\n')
for title_line in title_lines:
while (len(title_line) > size):
title_part = title_line[:size]
i = title_part.rfind(' ')
if (i == (-1)):
i = len(title_part)
titles.append(title_part[:i])
title_line = title_line[i:].strip()
titles.append(title_line)
return titles
| null | null | null | for a specified width and font size
| codeqa | def split title title width title fs titles []if not title return titlessize reverse text len width title fs * 1 1 title lines title split '\n' for title line in title lines while len title line > size title part title line[ size]i title part rfind '' if i -1 i len title part titles append title part[ i] title line title line[i ] strip titles append title line return titles
| null | null | null | null | Question:
For what purpose do a string split ?
Code:
def split_title(title, width, title_fs):
titles = []
if (not title):
return titles
size = reverse_text_len(width, (title_fs * 1.1))
title_lines = title.split('\n')
for title_line in title_lines:
while (len(title_line) > size):
title_part = title_line[:size]
i = title_part.rfind(' ')
if (i == (-1)):
i = len(title_part)
titles.append(title_part[:i])
title_line = title_line[i:].strip()
titles.append(title_line)
return titles
|
null | null | null | What do bear directories have ?
| def collect_bears(bear_dirs, bear_globs, kinds, log_printer, warn_if_unused_glob=True):
bears_found = tuple(([] for i in range(len(kinds))))
bear_globs_with_bears = set()
for (bear, glob) in icollect_bears(bear_dirs, bear_globs, kinds, log_printer):
index = kinds.index(_get_kind(bear))
bears_found[index].append(bear)
bear_globs_with_bears.add(glob)
if warn_if_unused_glob:
_warn_if_unused_glob(log_printer, bear_globs, bear_globs_with_bears, "No bears matching '{}' were found. Make sure you have coala-bears installed or you have typed the name correctly.")
return bears_found
| null | null | null | a matching kind matching the given globs
| codeqa | def collect bears bear dirs bear globs kinds log printer warn if unused glob True bears found tuple [] for i in range len kinds bear globs with bears set for bear glob in icollect bears bear dirs bear globs kinds log printer index kinds index get kind bear bears found[index] append bear bear globs with bears add glob if warn if unused glob warn if unused glob log printer bear globs bear globs with bears " Nobearsmatching'{}'werefound Makesureyouhavecoala-bearsinstalledoryouhavetypedthenamecorrectly " return bears found
| null | null | null | null | Question:
What do bear directories have ?
Code:
def collect_bears(bear_dirs, bear_globs, kinds, log_printer, warn_if_unused_glob=True):
bears_found = tuple(([] for i in range(len(kinds))))
bear_globs_with_bears = set()
for (bear, glob) in icollect_bears(bear_dirs, bear_globs, kinds, log_printer):
index = kinds.index(_get_kind(bear))
bears_found[index].append(bear)
bear_globs_with_bears.add(glob)
if warn_if_unused_glob:
_warn_if_unused_glob(log_printer, bear_globs, bear_globs_with_bears, "No bears matching '{}' were found. Make sure you have coala-bears installed or you have typed the name correctly.")
return bears_found
|
null | null | null | What have a matching kind matching the given globs ?
| def collect_bears(bear_dirs, bear_globs, kinds, log_printer, warn_if_unused_glob=True):
bears_found = tuple(([] for i in range(len(kinds))))
bear_globs_with_bears = set()
for (bear, glob) in icollect_bears(bear_dirs, bear_globs, kinds, log_printer):
index = kinds.index(_get_kind(bear))
bears_found[index].append(bear)
bear_globs_with_bears.add(glob)
if warn_if_unused_glob:
_warn_if_unused_glob(log_printer, bear_globs, bear_globs_with_bears, "No bears matching '{}' were found. Make sure you have coala-bears installed or you have typed the name correctly.")
return bears_found
| null | null | null | bear directories
| codeqa | def collect bears bear dirs bear globs kinds log printer warn if unused glob True bears found tuple [] for i in range len kinds bear globs with bears set for bear glob in icollect bears bear dirs bear globs kinds log printer index kinds index get kind bear bears found[index] append bear bear globs with bears add glob if warn if unused glob warn if unused glob log printer bear globs bear globs with bears " Nobearsmatching'{}'werefound Makesureyouhavecoala-bearsinstalledoryouhavetypedthenamecorrectly " return bears found
| null | null | null | null | Question:
What have a matching kind matching the given globs ?
Code:
def collect_bears(bear_dirs, bear_globs, kinds, log_printer, warn_if_unused_glob=True):
bears_found = tuple(([] for i in range(len(kinds))))
bear_globs_with_bears = set()
for (bear, glob) in icollect_bears(bear_dirs, bear_globs, kinds, log_printer):
index = kinds.index(_get_kind(bear))
bears_found[index].append(bear)
bear_globs_with_bears.add(glob)
if warn_if_unused_glob:
_warn_if_unused_glob(log_printer, bear_globs, bear_globs_with_bears, "No bears matching '{}' were found. Make sure you have coala-bears installed or you have typed the name correctly.")
return bears_found
|
null | null | null | What does the code collect from bear directories that have a matching kind matching the given globs ?
| def collect_bears(bear_dirs, bear_globs, kinds, log_printer, warn_if_unused_glob=True):
bears_found = tuple(([] for i in range(len(kinds))))
bear_globs_with_bears = set()
for (bear, glob) in icollect_bears(bear_dirs, bear_globs, kinds, log_printer):
index = kinds.index(_get_kind(bear))
bears_found[index].append(bear)
bear_globs_with_bears.add(glob)
if warn_if_unused_glob:
_warn_if_unused_glob(log_printer, bear_globs, bear_globs_with_bears, "No bears matching '{}' were found. Make sure you have coala-bears installed or you have typed the name correctly.")
return bears_found
| null | null | null | all bears
| codeqa | def collect bears bear dirs bear globs kinds log printer warn if unused glob True bears found tuple [] for i in range len kinds bear globs with bears set for bear glob in icollect bears bear dirs bear globs kinds log printer index kinds index get kind bear bears found[index] append bear bear globs with bears add glob if warn if unused glob warn if unused glob log printer bear globs bear globs with bears " Nobearsmatching'{}'werefound Makesureyouhavecoala-bearsinstalledoryouhavetypedthenamecorrectly " return bears found
| null | null | null | null | Question:
What does the code collect from bear directories that have a matching kind matching the given globs ?
Code:
def collect_bears(bear_dirs, bear_globs, kinds, log_printer, warn_if_unused_glob=True):
bears_found = tuple(([] for i in range(len(kinds))))
bear_globs_with_bears = set()
for (bear, glob) in icollect_bears(bear_dirs, bear_globs, kinds, log_printer):
index = kinds.index(_get_kind(bear))
bears_found[index].append(bear)
bear_globs_with_bears.add(glob)
if warn_if_unused_glob:
_warn_if_unused_glob(log_printer, bear_globs, bear_globs_with_bears, "No bears matching '{}' were found. Make sure you have coala-bears installed or you have typed the name correctly.")
return bears_found
|
null | null | null | What does the code add ?
| def addCollarShaft(collarThickness, derivation, negatives, positives, xmlElement):
if (collarThickness <= 0.0):
addShaft(derivation, negatives, positives)
return
connectionEnd = Vector3(0.0, 0.0, (derivation.pinionThickness + collarThickness))
collarDerivation = extrude.ExtrudeDerivation()
collarDerivation.offsetPathDefault = [Vector3(0.0, 0.0, derivation.pinionThickness), connectionEnd]
addCollarShaftSetDerivation(collarDerivation, collarThickness, derivation, negatives, positives, xmlElement)
| null | null | null | collar
| codeqa | def add Collar Shaft collar Thickness derivation negatives positives xml Element if collar Thickness < 0 0 add Shaft derivation negatives positives returnconnection End Vector 3 0 0 0 0 derivation pinion Thickness + collar Thickness collar Derivation extrude Extrude Derivation collar Derivation offset Path Default [ Vector 3 0 0 0 0 derivation pinion Thickness connection End]add Collar Shaft Set Derivation collar Derivation collar Thickness derivation negatives positives xml Element
| null | null | null | null | Question:
What does the code add ?
Code:
def addCollarShaft(collarThickness, derivation, negatives, positives, xmlElement):
if (collarThickness <= 0.0):
addShaft(derivation, negatives, positives)
return
connectionEnd = Vector3(0.0, 0.0, (derivation.pinionThickness + collarThickness))
collarDerivation = extrude.ExtrudeDerivation()
collarDerivation.offsetPathDefault = [Vector3(0.0, 0.0, derivation.pinionThickness), connectionEnd]
addCollarShaftSetDerivation(collarDerivation, collarThickness, derivation, negatives, positives, xmlElement)
|
null | null | null | What does the code send ?
| def send_message(to, text, sender=None):
if sender:
msg = OutboxMessage.objects.create(sender=sender, message=text)
msg.to.add(*to)
for user in to:
im = InboxMessage.objects.create(sender=sender, to=user, message=text)
if Setting.get_for_user(user, 'email_private_messages'):
email_private_message(inbox_message_id=im.id)
message_sent.send(sender=InboxMessage, to=to, text=text, msg_sender=sender)
| null | null | null | a private message
| codeqa | def send message to text sender None if sender msg Outbox Message objects create sender sender message text msg to add *to for user in to im Inbox Message objects create sender sender to user message text if Setting get for user user 'email private messages' email private message inbox message id im id message sent send sender Inbox Message to to text text msg sender sender
| null | null | null | null | Question:
What does the code send ?
Code:
def send_message(to, text, sender=None):
if sender:
msg = OutboxMessage.objects.create(sender=sender, message=text)
msg.to.add(*to)
for user in to:
im = InboxMessage.objects.create(sender=sender, to=user, message=text)
if Setting.get_for_user(user, 'email_private_messages'):
email_private_message(inbox_message_id=im.id)
message_sent.send(sender=InboxMessage, to=to, text=text, msg_sender=sender)
|
null | null | null | What does the code fall ?
| def CDLRISEFALL3METHODS(barDs, count):
return call_talib_with_ohlc(barDs, count, talib.CDLRISEFALL3METHODS)
| null | null | null | three methods
| codeqa | def CDLRISEFALL 3 METHODS bar Ds count return call talib with ohlc bar Ds count talib CDLRISEFALL 3 METHODS
| null | null | null | null | Question:
What does the code fall ?
Code:
def CDLRISEFALL3METHODS(barDs, count):
return call_talib_with_ohlc(barDs, count, talib.CDLRISEFALL3METHODS)
|
null | null | null | When does a receiver attach to the provided signal within the scope of the context manager ?
| @contextmanager
def mock_signal_receiver(signal, wraps=None, **kwargs):
if (wraps is None):
def wraps(*args, **kwargs):
return None
receiver = Mock(wraps=wraps)
signal.connect(receiver, **kwargs)
(yield receiver)
signal.disconnect(receiver)
| null | null | null | temporarily
| codeqa | @contextmanagerdef mock signal receiver signal wraps None **kwargs if wraps is None def wraps *args **kwargs return Nonereceiver Mock wraps wraps signal connect receiver **kwargs yield receiver signal disconnect receiver
| null | null | null | null | Question:
When does a receiver attach to the provided signal within the scope of the context manager ?
Code:
@contextmanager
def mock_signal_receiver(signal, wraps=None, **kwargs):
if (wraps is None):
def wraps(*args, **kwargs):
return None
receiver = Mock(wraps=wraps)
signal.connect(receiver, **kwargs)
(yield receiver)
signal.disconnect(receiver)
|
null | null | null | What attaches to the provided signal within the scope of the context manager ?
| @contextmanager
def mock_signal_receiver(signal, wraps=None, **kwargs):
if (wraps is None):
def wraps(*args, **kwargs):
return None
receiver = Mock(wraps=wraps)
signal.connect(receiver, **kwargs)
(yield receiver)
signal.disconnect(receiver)
| null | null | null | a receiver
| codeqa | @contextmanagerdef mock signal receiver signal wraps None **kwargs if wraps is None def wraps *args **kwargs return Nonereceiver Mock wraps wraps signal connect receiver **kwargs yield receiver signal disconnect receiver
| null | null | null | null | Question:
What attaches to the provided signal within the scope of the context manager ?
Code:
@contextmanager
def mock_signal_receiver(signal, wraps=None, **kwargs):
if (wraps is None):
def wraps(*args, **kwargs):
return None
receiver = Mock(wraps=wraps)
signal.connect(receiver, **kwargs)
(yield receiver)
signal.disconnect(receiver)
|
null | null | null | Where does a receiver attach to the provided signal temporarily ?
| @contextmanager
def mock_signal_receiver(signal, wraps=None, **kwargs):
if (wraps is None):
def wraps(*args, **kwargs):
return None
receiver = Mock(wraps=wraps)
signal.connect(receiver, **kwargs)
(yield receiver)
signal.disconnect(receiver)
| null | null | null | within the scope of the context manager
| codeqa | @contextmanagerdef mock signal receiver signal wraps None **kwargs if wraps is None def wraps *args **kwargs return Nonereceiver Mock wraps wraps signal connect receiver **kwargs yield receiver signal disconnect receiver
| null | null | null | null | Question:
Where does a receiver attach to the provided signal temporarily ?
Code:
@contextmanager
def mock_signal_receiver(signal, wraps=None, **kwargs):
if (wraps is None):
def wraps(*args, **kwargs):
return None
receiver = Mock(wraps=wraps)
signal.connect(receiver, **kwargs)
(yield receiver)
signal.disconnect(receiver)
|
null | null | null | What converts into an actual solution ?
| def _handle_Integral(expr, func, order, hint):
if hint.endswith('_Integral'):
return expr
elif (hint == '1st_linear_constant_coeff'):
return simplify(expr.doit())
else:
return expr
| null | null | null | a solution with integrals in it
| codeqa | def handle Integral expr func order hint if hint endswith ' Integral' return exprelif hint '1 st linear constant coeff' return simplify expr doit else return expr
| null | null | null | null | Question:
What converts into an actual solution ?
Code:
def _handle_Integral(expr, func, order, hint):
if hint.endswith('_Integral'):
return expr
elif (hint == '1st_linear_constant_coeff'):
return simplify(expr.doit())
else:
return expr
|
null | null | null | What does a solution with integrals in it convert ?
| def _handle_Integral(expr, func, order, hint):
if hint.endswith('_Integral'):
return expr
elif (hint == '1st_linear_constant_coeff'):
return simplify(expr.doit())
else:
return expr
| null | null | null | into an actual solution
| codeqa | def handle Integral expr func order hint if hint endswith ' Integral' return exprelif hint '1 st linear constant coeff' return simplify expr doit else return expr
| null | null | null | null | Question:
What does a solution with integrals in it convert ?
Code:
def _handle_Integral(expr, func, order, hint):
if hint.endswith('_Integral'):
return expr
elif (hint == '1st_linear_constant_coeff'):
return simplify(expr.doit())
else:
return expr
|
null | null | null | What exceeds the threshold ?
| def total_norm_constraint(tensor_vars, max_norm, epsilon=1e-07, return_norm=False):
norm = T.sqrt(sum((T.sum((tensor ** 2)) for tensor in tensor_vars)))
dtype = np.dtype(theano.config.floatX).type
target_norm = T.clip(norm, 0, dtype(max_norm))
multiplier = (target_norm / (dtype(epsilon) + norm))
tensor_vars_scaled = [(step * multiplier) for step in tensor_vars]
if return_norm:
return (tensor_vars_scaled, norm)
else:
return tensor_vars_scaled
| null | null | null | the combined norm of the input tensors
| codeqa | def total norm constraint tensor vars max norm epsilon 1e- 07 return norm False norm T sqrt sum T sum tensor ** 2 for tensor in tensor vars dtype np dtype theano config float X typetarget norm T clip norm 0 dtype max norm multiplier target norm / dtype epsilon + norm tensor vars scaled [ step * multiplier for step in tensor vars]if return norm return tensor vars scaled norm else return tensor vars scaled
| null | null | null | null | Question:
What exceeds the threshold ?
Code:
def total_norm_constraint(tensor_vars, max_norm, epsilon=1e-07, return_norm=False):
norm = T.sqrt(sum((T.sum((tensor ** 2)) for tensor in tensor_vars)))
dtype = np.dtype(theano.config.floatX).type
target_norm = T.clip(norm, 0, dtype(max_norm))
multiplier = (target_norm / (dtype(epsilon) + norm))
tensor_vars_scaled = [(step * multiplier) for step in tensor_vars]
if return_norm:
return (tensor_vars_scaled, norm)
else:
return tensor_vars_scaled
|
null | null | null | What did the combined norm of the input tensors exceed ?
| def total_norm_constraint(tensor_vars, max_norm, epsilon=1e-07, return_norm=False):
norm = T.sqrt(sum((T.sum((tensor ** 2)) for tensor in tensor_vars)))
dtype = np.dtype(theano.config.floatX).type
target_norm = T.clip(norm, 0, dtype(max_norm))
multiplier = (target_norm / (dtype(epsilon) + norm))
tensor_vars_scaled = [(step * multiplier) for step in tensor_vars]
if return_norm:
return (tensor_vars_scaled, norm)
else:
return tensor_vars_scaled
| null | null | null | the threshold
| codeqa | def total norm constraint tensor vars max norm epsilon 1e- 07 return norm False norm T sqrt sum T sum tensor ** 2 for tensor in tensor vars dtype np dtype theano config float X typetarget norm T clip norm 0 dtype max norm multiplier target norm / dtype epsilon + norm tensor vars scaled [ step * multiplier for step in tensor vars]if return norm return tensor vars scaled norm else return tensor vars scaled
| null | null | null | null | Question:
What did the combined norm of the input tensors exceed ?
Code:
def total_norm_constraint(tensor_vars, max_norm, epsilon=1e-07, return_norm=False):
norm = T.sqrt(sum((T.sum((tensor ** 2)) for tensor in tensor_vars)))
dtype = np.dtype(theano.config.floatX).type
target_norm = T.clip(norm, 0, dtype(max_norm))
multiplier = (target_norm / (dtype(epsilon) + norm))
tensor_vars_scaled = [(step * multiplier) for step in tensor_vars]
if return_norm:
return (tensor_vars_scaled, norm)
else:
return tensor_vars_scaled
|
null | null | null | What allows copy ?
| def deepcopy_bound(name):
def _deepcopy_method(x, memo):
return type(x)(x.im_func, copy.deepcopy(x.im_self, memo), x.im_class)
try:
pre_dispatch = copy._deepcopy_dispatch
copy._deepcopy_dispatch[types.MethodType] = _deepcopy_method
ret = copy.deepcopy(name)
finally:
copy._deepcopy_dispatch = pre_dispatch
return ret
| null | null | null | compatibility helper function
| codeqa | def deepcopy bound name def deepcopy method x memo return type x x im func copy deepcopy x im self memo x im class try pre dispatch copy deepcopy dispatchcopy deepcopy dispatch[types Method Type] deepcopy methodret copy deepcopy name finally copy deepcopy dispatch pre dispatchreturn ret
| null | null | null | null | Question:
What allows copy ?
Code:
def deepcopy_bound(name):
def _deepcopy_method(x, memo):
return type(x)(x.im_func, copy.deepcopy(x.im_self, memo), x.im_class)
try:
pre_dispatch = copy._deepcopy_dispatch
copy._deepcopy_dispatch[types.MethodType] = _deepcopy_method
ret = copy.deepcopy(name)
finally:
copy._deepcopy_dispatch = pre_dispatch
return ret
|
null | null | null | What do compatibility helper function allow ?
| def deepcopy_bound(name):
def _deepcopy_method(x, memo):
return type(x)(x.im_func, copy.deepcopy(x.im_self, memo), x.im_class)
try:
pre_dispatch = copy._deepcopy_dispatch
copy._deepcopy_dispatch[types.MethodType] = _deepcopy_method
ret = copy.deepcopy(name)
finally:
copy._deepcopy_dispatch = pre_dispatch
return ret
| null | null | null | copy
| codeqa | def deepcopy bound name def deepcopy method x memo return type x x im func copy deepcopy x im self memo x im class try pre dispatch copy deepcopy dispatchcopy deepcopy dispatch[types Method Type] deepcopy methodret copy deepcopy name finally copy deepcopy dispatch pre dispatchreturn ret
| null | null | null | null | Question:
What do compatibility helper function allow ?
Code:
def deepcopy_bound(name):
def _deepcopy_method(x, memo):
return type(x)(x.im_func, copy.deepcopy(x.im_self, memo), x.im_class)
try:
pre_dispatch = copy._deepcopy_dispatch
copy._deepcopy_dispatch[types.MethodType] = _deepcopy_method
ret = copy.deepcopy(name)
finally:
copy._deepcopy_dispatch = pre_dispatch
return ret
|
null | null | null | How did memory align ?
| def test_aligned_mem_float():
a = arange(402, dtype=np.uint8)
z = np.frombuffer(a.data, offset=2, count=100, dtype=float32)
z.shape = (10, 10)
eig(z, overwrite_a=True)
eig(z.T, overwrite_a=True)
| null | null | null | non
| codeqa | def test aligned mem float a arange 402 dtype np uint 8 z np frombuffer a data offset 2 count 100 dtype float 32 z shape 10 10 eig z overwrite a True eig z T overwrite a True
| null | null | null | null | Question:
How did memory align ?
Code:
def test_aligned_mem_float():
a = arange(402, dtype=np.uint8)
z = np.frombuffer(a.data, offset=2, count=100, dtype=float32)
z.shape = (10, 10)
eig(z, overwrite_a=True)
eig(z.T, overwrite_a=True)
|
null | null | null | What does the code get ?
| def _getAccessibleAttribute(attributeName, listObject):
if (attributeName in globalNativeFunctionSet):
return getattr(listObject, attributeName, None)
if (attributeName in globalGetAccessibleAttributeSet):
stringAttribute = ListAttribute(listObject)
return getattr(stringAttribute, attributeName, None)
return None
| null | null | null | the accessible attribute
| codeqa | def get Accessible Attribute attribute Name list Object if attribute Name in global Native Function Set return getattr list Object attribute Name None if attribute Name in global Get Accessible Attribute Set string Attribute List Attribute list Object return getattr string Attribute attribute Name None return None
| null | null | null | null | Question:
What does the code get ?
Code:
def _getAccessibleAttribute(attributeName, listObject):
if (attributeName in globalNativeFunctionSet):
return getattr(listObject, attributeName, None)
if (attributeName in globalGetAccessibleAttributeSet):
stringAttribute = ListAttribute(listObject)
return getattr(stringAttribute, attributeName, None)
return None
|
null | null | null | Where does the code apply a function ?
| def minibatch_map(fn, batch_size, input_data, output_data=None, output_width=None):
if (output_width is None):
if (output_data is None):
raise ValueError('output_data or output_width should be provided')
output_width = output_data.shape[1]
output_length = input_data.shape[0]
if (output_data is None):
output_data = numpy.empty((output_length, output_width))
else:
assert (output_data.shape[0] == input_data.shape[0]), ('output_data should have the same length as input_data', output_data.shape[0], input_data.shape[0])
for i in xrange(0, output_length, batch_size):
output_data[i:(i + batch_size)] = fn(input_data[i:(i + batch_size)])
return output_data
| null | null | null | on input_data
| codeqa | def minibatch map fn batch size input data output data None output width None if output width is None if output data is None raise Value Error 'output dataoroutput widthshouldbeprovided' output width output data shape[ 1 ]output length input data shape[ 0 ]if output data is None output data numpy empty output length output width else assert output data shape[ 0 ] input data shape[ 0 ] 'output datashouldhavethesamelengthasinput data' output data shape[ 0 ] input data shape[ 0 ] for i in xrange 0 output length batch size output data[i i + batch size ] fn input data[i i + batch size ] return output data
| null | null | null | null | Question:
Where does the code apply a function ?
Code:
def minibatch_map(fn, batch_size, input_data, output_data=None, output_width=None):
if (output_width is None):
if (output_data is None):
raise ValueError('output_data or output_width should be provided')
output_width = output_data.shape[1]
output_length = input_data.shape[0]
if (output_data is None):
output_data = numpy.empty((output_length, output_width))
else:
assert (output_data.shape[0] == input_data.shape[0]), ('output_data should have the same length as input_data', output_data.shape[0], input_data.shape[0])
for i in xrange(0, output_length, batch_size):
output_data[i:(i + batch_size)] = fn(input_data[i:(i + batch_size)])
return output_data
|
null | null | null | What does the code remove from the list table ?
| def removeElementFromListTable(element, key, listDictionary):
if (key not in listDictionary):
return
elementList = listDictionary[key]
if (len(elementList) < 2):
del listDictionary[key]
return
if (element in elementList):
elementList.remove(element)
| null | null | null | an element
| codeqa | def remove Element From List Table element key list Dictionary if key not in list Dictionary returnelement List list Dictionary[key]if len element List < 2 del list Dictionary[key]returnif element in element List element List remove element
| null | null | null | null | Question:
What does the code remove from the list table ?
Code:
def removeElementFromListTable(element, key, listDictionary):
if (key not in listDictionary):
return
elementList = listDictionary[key]
if (len(elementList) < 2):
del listDictionary[key]
return
if (element in elementList):
elementList.remove(element)
|
null | null | null | What does the code build ?
| def buildTableFromCompletedList(data_source):
headers = data_source[0]
items = data_source[2:]
table = TABLE(_id='completed_list', _class='dataTable display')
hr = TR()
for title in headers:
hr.append(TH(title))
header = THEAD(hr)
body = TBODY()
for row in items:
tr = TR()
for answer in row:
tr.append(TD(answer))
body.append(tr)
table.append(header)
table.append(body)
current.response.s3.no_sspag = True
attr = S3DataTable.getConfigData()
form = S3DataTable.htmlConfig(table, 'completed_list', [[0, 'asc']], '', None, **attr)
return form
| null | null | null | a table to display completed list
| codeqa | def build Table From Completed List data source headers data source[ 0 ]items data source[ 2 ]table TABLE id 'completed list' class 'data Tabledisplay' hr TR for title in headers hr append TH title header THEAD hr body TBODY for row in items tr TR for answer in row tr append TD answer body append tr table append header table append body current response s3 no sspag Trueattr S3 Data Table get Config Data form S3 Data Table html Config table 'completed list' [[ 0 'asc']] '' None **attr return form
| null | null | null | null | Question:
What does the code build ?
Code:
def buildTableFromCompletedList(data_source):
headers = data_source[0]
items = data_source[2:]
table = TABLE(_id='completed_list', _class='dataTable display')
hr = TR()
for title in headers:
hr.append(TH(title))
header = THEAD(hr)
body = TBODY()
for row in items:
tr = TR()
for answer in row:
tr.append(TD(answer))
body.append(tr)
table.append(header)
table.append(body)
current.response.s3.no_sspag = True
attr = S3DataTable.getConfigData()
form = S3DataTable.htmlConfig(table, 'completed_list', [[0, 'asc']], '', None, **attr)
return form
|
null | null | null | What satisfy the predicate ?
| def sfilter(pred, brule):
def filtered_brl(expr):
for x in filter(pred, brule(expr)):
(yield x)
return filtered_brl
| null | null | null | only those results
| codeqa | def sfilter pred brule def filtered brl expr for x in filter pred brule expr yield x return filtered brl
| null | null | null | null | Question:
What satisfy the predicate ?
Code:
def sfilter(pred, brule):
def filtered_brl(expr):
for x in filter(pred, brule(expr)):
(yield x)
return filtered_brl
|
null | null | null | What do only those results satisfy ?
| def sfilter(pred, brule):
def filtered_brl(expr):
for x in filter(pred, brule(expr)):
(yield x)
return filtered_brl
| null | null | null | the predicate
| codeqa | def sfilter pred brule def filtered brl expr for x in filter pred brule expr yield x return filtered brl
| null | null | null | null | Question:
What do only those results satisfy ?
Code:
def sfilter(pred, brule):
def filtered_brl(expr):
for x in filter(pred, brule(expr)):
(yield x)
return filtered_brl
|
null | null | null | What is showing the training and use of a projective dependency parser ?
| def projective_prob_parse_demo():
from nltk.parse.dependencygraph import conll_data2
graphs = [DependencyGraph(entry) for entry in conll_data2.split(u'\n\n') if entry]
ppdp = ProbabilisticProjectiveDependencyParser()
print(u'Training Probabilistic Projective Dependency Parser...')
ppdp.train(graphs)
sent = [u'Cathy', u'zag', u'hen', u'wild', u'zwaaien', u'.']
print(u"Parsing '", u' '.join(sent), u"'...")
print(u'Parse:')
for tree in ppdp.parse(sent):
print(tree)
| null | null | null | a demo
| codeqa | def projective prob parse demo from nltk parse dependencygraph import conll data 2 graphs [ Dependency Graph entry for entry in conll data 2 split u'\n\n' if entry]ppdp Probabilistic Projective Dependency Parser print u' Training Probabilistic Projective Dependency Parser ' ppdp train graphs sent [u' Cathy' u'zag' u'hen' u'wild' u'zwaaien' u' ']print u" Parsing'" u'' join sent u"' " print u' Parse ' for tree in ppdp parse sent print tree
| null | null | null | null | Question:
What is showing the training and use of a projective dependency parser ?
Code:
def projective_prob_parse_demo():
from nltk.parse.dependencygraph import conll_data2
graphs = [DependencyGraph(entry) for entry in conll_data2.split(u'\n\n') if entry]
ppdp = ProbabilisticProjectiveDependencyParser()
print(u'Training Probabilistic Projective Dependency Parser...')
ppdp.train(graphs)
sent = [u'Cathy', u'zag', u'hen', u'wild', u'zwaaien', u'.']
print(u"Parsing '", u' '.join(sent), u"'...")
print(u'Parse:')
for tree in ppdp.parse(sent):
print(tree)
|
null | null | null | What do helper function return ?
| def get_or_compute_grads(loss_or_grads, params):
if any(((not isinstance(p, theano.compile.SharedVariable)) for p in params)):
raise ValueError('params must contain shared variables only. If it contains arbitrary parameter expressions, then lasagne.utils.collect_shared_vars() may help you.')
if isinstance(loss_or_grads, list):
if (not (len(loss_or_grads) == len(params))):
raise ValueError(('Got %d gradient expressions for %d parameters' % (len(loss_or_grads), len(params))))
return loss_or_grads
else:
return theano.grad(loss_or_grads, params)
| null | null | null | a list of gradients parameters
| codeqa | def get or compute grads loss or grads params if any not isinstance p theano compile Shared Variable for p in params raise Value Error 'paramsmustcontainsharedvariablesonly Ifitcontainsarbitraryparameterexpressions thenlasagne utils collect shared vars mayhelpyou ' if isinstance loss or grads list if not len loss or grads len params raise Value Error ' Got%dgradientexpressionsfor%dparameters' % len loss or grads len params return loss or gradselse return theano grad loss or grads params
| null | null | null | null | Question:
What do helper function return ?
Code:
def get_or_compute_grads(loss_or_grads, params):
if any(((not isinstance(p, theano.compile.SharedVariable)) for p in params)):
raise ValueError('params must contain shared variables only. If it contains arbitrary parameter expressions, then lasagne.utils.collect_shared_vars() may help you.')
if isinstance(loss_or_grads, list):
if (not (len(loss_or_grads) == len(params))):
raise ValueError(('Got %d gradient expressions for %d parameters' % (len(loss_or_grads), len(params))))
return loss_or_grads
else:
return theano.grad(loss_or_grads, params)
|
null | null | null | What is returning a list of gradients parameters ?
| def get_or_compute_grads(loss_or_grads, params):
if any(((not isinstance(p, theano.compile.SharedVariable)) for p in params)):
raise ValueError('params must contain shared variables only. If it contains arbitrary parameter expressions, then lasagne.utils.collect_shared_vars() may help you.')
if isinstance(loss_or_grads, list):
if (not (len(loss_or_grads) == len(params))):
raise ValueError(('Got %d gradient expressions for %d parameters' % (len(loss_or_grads), len(params))))
return loss_or_grads
else:
return theano.grad(loss_or_grads, params)
| null | null | null | helper function
| codeqa | def get or compute grads loss or grads params if any not isinstance p theano compile Shared Variable for p in params raise Value Error 'paramsmustcontainsharedvariablesonly Ifitcontainsarbitraryparameterexpressions thenlasagne utils collect shared vars mayhelpyou ' if isinstance loss or grads list if not len loss or grads len params raise Value Error ' Got%dgradientexpressionsfor%dparameters' % len loss or grads len params return loss or gradselse return theano grad loss or grads params
| null | null | null | null | Question:
What is returning a list of gradients parameters ?
Code:
def get_or_compute_grads(loss_or_grads, params):
if any(((not isinstance(p, theano.compile.SharedVariable)) for p in params)):
raise ValueError('params must contain shared variables only. If it contains arbitrary parameter expressions, then lasagne.utils.collect_shared_vars() may help you.')
if isinstance(loss_or_grads, list):
if (not (len(loss_or_grads) == len(params))):
raise ValueError(('Got %d gradient expressions for %d parameters' % (len(loss_or_grads), len(params))))
return loss_or_grads
else:
return theano.grad(loss_or_grads, params)
|
null | null | null | What does the code stop ?
| def stop(service):
action('stop', service)
| null | null | null | a service
| codeqa | def stop service action 'stop' service
| null | null | null | null | Question:
What does the code stop ?
Code:
def stop(service):
action('stop', service)
|
null | null | null | How do summation elementwise ?
| def bias(x, y, axis=1):
x_shape = x.shape
y_shape = y.shape
if chainer.is_debug():
assert (x_shape[axis:(axis + len(y_shape))] == y_shape)
y1_shape = tuple(((([1] * axis) + list(y_shape)) + ([1] * ((len(x_shape) - axis) - len(y_shape)))))
y1 = reshape.reshape(y, y1_shape)
y2 = broadcast.broadcast_to(y1, x_shape)
return (x + y2)
| null | null | null | with broadcasting
| codeqa | def bias x y axis 1 x shape x shapey shape y shapeif chainer is debug assert x shape[axis axis + len y shape ] y shape y1 shape tuple [1 ] * axis + list y shape + [1 ] * len x shape - axis - len y shape y1 reshape reshape y y1 shape y2 broadcast broadcast to y1 x shape return x + y2
| null | null | null | null | Question:
How do summation elementwise ?
Code:
def bias(x, y, axis=1):
x_shape = x.shape
y_shape = y.shape
if chainer.is_debug():
assert (x_shape[axis:(axis + len(y_shape))] == y_shape)
y1_shape = tuple(((([1] * axis) + list(y_shape)) + ([1] * ((len(x_shape) - axis) - len(y_shape)))))
y1 = reshape.reshape(y, y1_shape)
y2 = broadcast.broadcast_to(y1, x_shape)
return (x + y2)
|
null | null | null | What is hosting the given watch ?
| def restart(watch):
if (not misc.is_string_secure(watch)):
logging.error('Watch string [{0}] is a possible security violation'.format(watch))
return False
logging.info('Restarting watch {0}'.format(watch))
return run_with_retry([MONIT, 'restart', '-g', watch])
| null | null | null | all processes
| codeqa | def restart watch if not misc is string secure watch logging error ' Watchstring[{ 0 }]isapossiblesecurityviolation' format watch return Falselogging info ' Restartingwatch{ 0 }' format watch return run with retry [MONIT 'restart' '-g' watch]
| null | null | null | null | Question:
What is hosting the given watch ?
Code:
def restart(watch):
if (not misc.is_string_secure(watch)):
logging.error('Watch string [{0}] is a possible security violation'.format(watch))
return False
logging.info('Restarting watch {0}'.format(watch))
return run_with_retry([MONIT, 'restart', '-g', watch])
|
null | null | null | What do all processes host ?
| def restart(watch):
if (not misc.is_string_secure(watch)):
logging.error('Watch string [{0}] is a possible security violation'.format(watch))
return False
logging.info('Restarting watch {0}'.format(watch))
return run_with_retry([MONIT, 'restart', '-g', watch])
| null | null | null | the given watch
| codeqa | def restart watch if not misc is string secure watch logging error ' Watchstring[{ 0 }]isapossiblesecurityviolation' format watch return Falselogging info ' Restartingwatch{ 0 }' format watch return run with retry [MONIT 'restart' '-g' watch]
| null | null | null | null | Question:
What do all processes host ?
Code:
def restart(watch):
if (not misc.is_string_secure(watch)):
logging.error('Watch string [{0}] is a possible security violation'.format(watch))
return False
logging.info('Restarting watch {0}'.format(watch))
return run_with_retry([MONIT, 'restart', '-g', watch])
|
null | null | null | In which direction do graph read in p2 g format ?
| @open_file(0, mode='r')
def read_p2g(path, encoding='utf-8'):
lines = (line.decode(encoding) for line in path)
G = parse_p2g(lines)
return G
| null | null | null | from path
| codeqa | @open file 0 mode 'r' def read p2 g path encoding 'utf- 8 ' lines line decode encoding for line in path G parse p2 g lines return G
| null | null | null | null | Question:
In which direction do graph read in p2 g format ?
Code:
@open_file(0, mode='r')
def read_p2g(path, encoding='utf-8'):
lines = (line.decode(encoding) for line in path)
G = parse_p2g(lines)
return G
|
null | null | null | How do graph read from path ?
| @open_file(0, mode='r')
def read_p2g(path, encoding='utf-8'):
lines = (line.decode(encoding) for line in path)
G = parse_p2g(lines)
return G
| null | null | null | in p2 g format
| codeqa | @open file 0 mode 'r' def read p2 g path encoding 'utf- 8 ' lines line decode encoding for line in path G parse p2 g lines return G
| null | null | null | null | Question:
How do graph read from path ?
Code:
@open_file(0, mode='r')
def read_p2g(path, encoding='utf-8'):
lines = (line.decode(encoding) for line in path)
G = parse_p2g(lines)
return G
|
null | null | null | What do minions support ?
| def __virtual__():
return ('sysctl.show' in __salt__)
| null | null | null | sysctl
| codeqa | def virtual return 'sysctl show' in salt
| null | null | null | null | Question:
What do minions support ?
Code:
def __virtual__():
return ('sysctl.show' in __salt__)
|
null | null | null | What does the code create ?
| def technical_404_response(request, exception):
try:
tried = exception.args[0]['tried']
except (IndexError, TypeError, KeyError):
tried = []
else:
if (not tried):
return empty_urlconf(request)
urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
if isinstance(urlconf, types.ModuleType):
urlconf = urlconf.__name__
t = Template(TECHNICAL_404_TEMPLATE, name='Technical 404 template')
c = Context({'urlconf': urlconf, 'root_urlconf': settings.ROOT_URLCONF, 'request_path': request.path_info[1:], 'urlpatterns': tried, 'reason': smart_str(exception, errors='replace'), 'request': request, 'settings': get_safe_settings()})
return HttpResponseNotFound(t.render(c), mimetype='text/html')
| null | null | null | a technical 404 error response
| codeqa | def technical 404 response request exception try tried exception args[ 0 ]['tried']except Index Error Type Error Key Error tried []else if not tried return empty urlconf request urlconf getattr request 'urlconf' settings ROOT URLCONF if isinstance urlconf types Module Type urlconf urlconf name t Template TECHNICAL 404 TEMPLATE name ' Technical 404 template' c Context {'urlconf' urlconf 'root urlconf' settings ROOT URLCONF 'request path' request path info[ 1 ] 'urlpatterns' tried 'reason' smart str exception errors 'replace' 'request' request 'settings' get safe settings } return Http Response Not Found t render c mimetype 'text/html'
| null | null | null | null | Question:
What does the code create ?
Code:
def technical_404_response(request, exception):
try:
tried = exception.args[0]['tried']
except (IndexError, TypeError, KeyError):
tried = []
else:
if (not tried):
return empty_urlconf(request)
urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
if isinstance(urlconf, types.ModuleType):
urlconf = urlconf.__name__
t = Template(TECHNICAL_404_TEMPLATE, name='Technical 404 template')
c = Context({'urlconf': urlconf, 'root_urlconf': settings.ROOT_URLCONF, 'request_path': request.path_info[1:], 'urlpatterns': tried, 'reason': smart_str(exception, errors='replace'), 'request': request, 'settings': get_safe_settings()})
return HttpResponseNotFound(t.render(c), mimetype='text/html')
|
null | null | null | What did the code design ?
| def wait_for_build(obj, att=None, desired=None, callback=None, interval=None, attempts=None, verbose=None, verbose_atts=None):
att = (att or 'status')
desired = (desired or ['ACTIVE', 'ERROR', 'available', 'COMPLETED'])
interval = (interval or 20)
attempts = (attempts or 0)
verbose_atts = (verbose_atts or 'progress')
return wait_until(obj, att, desired, callback=callback, interval=interval, attempts=attempts, verbose=verbose, verbose_atts=verbose_atts)
| null | null | null | to handle the most common use case for wait_until : an object whose status attribute will end up in either active or error state
| codeqa | def wait for build obj att None desired None callback None interval None attempts None verbose None verbose atts None att att or 'status' desired desired or ['ACTIVE' 'ERROR' 'available' 'COMPLETED'] interval interval or 20 attempts attempts or 0 verbose atts verbose atts or 'progress' return wait until obj att desired callback callback interval interval attempts attempts verbose verbose verbose atts verbose atts
| null | null | null | null | Question:
What did the code design ?
Code:
def wait_for_build(obj, att=None, desired=None, callback=None, interval=None, attempts=None, verbose=None, verbose_atts=None):
att = (att or 'status')
desired = (desired or ['ACTIVE', 'ERROR', 'available', 'COMPLETED'])
interval = (interval or 20)
attempts = (attempts or 0)
verbose_atts = (verbose_atts or 'progress')
return wait_until(obj, att, desired, callback=callback, interval=interval, attempts=attempts, verbose=verbose, verbose_atts=verbose_atts)
|
null | null | null | What does the code add ?
| def _AddMessageMethods(message_descriptor, cls):
_AddListFieldsMethod(message_descriptor, cls)
_AddHasFieldMethod(message_descriptor, cls)
_AddClearFieldMethod(message_descriptor, cls)
if message_descriptor.is_extendable:
_AddClearExtensionMethod(cls)
_AddHasExtensionMethod(cls)
_AddClearMethod(message_descriptor, cls)
_AddEqualsMethod(message_descriptor, cls)
_AddStrMethod(message_descriptor, cls)
_AddUnicodeMethod(message_descriptor, cls)
_AddSetListenerMethod(cls)
_AddByteSizeMethod(message_descriptor, cls)
_AddSerializeToStringMethod(message_descriptor, cls)
_AddSerializePartialToStringMethod(message_descriptor, cls)
_AddMergeFromStringMethod(message_descriptor, cls)
_AddIsInitializedMethod(message_descriptor, cls)
_AddMergeFromMethod(cls)
| null | null | null | implementations of all message methods
| codeqa | def Add Message Methods message descriptor cls Add List Fields Method message descriptor cls Add Has Field Method message descriptor cls Add Clear Field Method message descriptor cls if message descriptor is extendable Add Clear Extension Method cls Add Has Extension Method cls Add Clear Method message descriptor cls Add Equals Method message descriptor cls Add Str Method message descriptor cls Add Unicode Method message descriptor cls Add Set Listener Method cls Add Byte Size Method message descriptor cls Add Serialize To String Method message descriptor cls Add Serialize Partial To String Method message descriptor cls Add Merge From String Method message descriptor cls Add Is Initialized Method message descriptor cls Add Merge From Method cls
| null | null | null | null | Question:
What does the code add ?
Code:
def _AddMessageMethods(message_descriptor, cls):
_AddListFieldsMethod(message_descriptor, cls)
_AddHasFieldMethod(message_descriptor, cls)
_AddClearFieldMethod(message_descriptor, cls)
if message_descriptor.is_extendable:
_AddClearExtensionMethod(cls)
_AddHasExtensionMethod(cls)
_AddClearMethod(message_descriptor, cls)
_AddEqualsMethod(message_descriptor, cls)
_AddStrMethod(message_descriptor, cls)
_AddUnicodeMethod(message_descriptor, cls)
_AddSetListenerMethod(cls)
_AddByteSizeMethod(message_descriptor, cls)
_AddSerializeToStringMethod(message_descriptor, cls)
_AddSerializePartialToStringMethod(message_descriptor, cls)
_AddMergeFromStringMethod(message_descriptor, cls)
_AddIsInitializedMethod(message_descriptor, cls)
_AddMergeFromMethod(cls)
|
null | null | null | For what purpose do message write immediately ?
| def status(msg):
sys.stdout.write(msg)
sys.stdout.write('\n')
sys.stdout.flush()
| null | null | null | to stdout
| codeqa | def status msg sys stdout write msg sys stdout write '\n' sys stdout flush
| null | null | null | null | Question:
For what purpose do message write immediately ?
Code:
def status(msg):
sys.stdout.write(msg)
sys.stdout.write('\n')
sys.stdout.flush()
|
null | null | null | When do message write to stdout ?
| def status(msg):
sys.stdout.write(msg)
sys.stdout.write('\n')
sys.stdout.flush()
| null | null | null | immediately
| codeqa | def status msg sys stdout write msg sys stdout write '\n' sys stdout flush
| null | null | null | null | Question:
When do message write to stdout ?
Code:
def status(msg):
sys.stdout.write(msg)
sys.stdout.write('\n')
sys.stdout.flush()
|
null | null | null | What does nothing ?
| @contextmanager
def _noop_context_manager(obj):
(yield obj)
| null | null | null | context manager
| codeqa | @contextmanagerdef noop context manager obj yield obj
| null | null | null | null | Question:
What does nothing ?
Code:
@contextmanager
def _noop_context_manager(obj):
(yield obj)
|
null | null | null | What does context manager do ?
| @contextmanager
def _noop_context_manager(obj):
(yield obj)
| null | null | null | nothing
| codeqa | @contextmanagerdef noop context manager obj yield obj
| null | null | null | null | Question:
What does context manager do ?
Code:
@contextmanager
def _noop_context_manager(obj):
(yield obj)
|
null | null | null | What does the code get ?
| def refget(objs, level=1):
for _ in xrange(level):
refs = gc.get_referrers(*objs)
try:
refs.remove(objs)
except ValueError:
pass
objs = refs
return refs
| null | null | null | the referrers to the sequence of objects passed in
| codeqa | def refget objs level 1 for in xrange level refs gc get referrers *objs try refs remove objs except Value Error passobjs refsreturn refs
| null | null | null | null | Question:
What does the code get ?
Code:
def refget(objs, level=1):
for _ in xrange(level):
refs = gc.get_referrers(*objs)
try:
refs.remove(objs)
except ValueError:
pass
objs = refs
return refs
|
null | null | null | What does the code get ?
| def get_default_flavor():
name = CONF.default_flavor
return get_flavor_by_name(name)
| null | null | null | the default flavor
| codeqa | def get default flavor name CONF default flavorreturn get flavor by name name
| null | null | null | null | Question:
What does the code get ?
Code:
def get_default_flavor():
name = CONF.default_flavor
return get_flavor_by_name(name)
|
null | null | null | In which direction do spines offset ?
| def offset_spines(offset=10, fig=None, ax=None):
warn_msg = '`offset_spines` is deprecated and will be removed in v0.5'
warnings.warn(warn_msg, UserWarning)
if ((fig is None) and (ax is None)):
axes = plt.gcf().axes
elif (fig is not None):
axes = fig.axes
elif (ax is not None):
axes = [ax]
for ax_i in axes:
for spine in ax_i.spines.values():
_set_spine_position(spine, ('outward', offset))
| null | null | null | away from axes
| codeqa | def offset spines offset 10 fig None ax None warn msg '`offset spines`isdeprecatedandwillberemovedinv 0 5'warnings warn warn msg User Warning if fig is None and ax is None axes plt gcf axeselif fig is not None axes fig axeselif ax is not None axes [ax]for ax i in axes for spine in ax i spines values set spine position spine 'outward' offset
| null | null | null | null | Question:
In which direction do spines offset ?
Code:
def offset_spines(offset=10, fig=None, ax=None):
warn_msg = '`offset_spines` is deprecated and will be removed in v0.5'
warnings.warn(warn_msg, UserWarning)
if ((fig is None) and (ax is None)):
axes = plt.gcf().axes
elif (fig is not None):
axes = fig.axes
elif (ax is not None):
axes = [ax]
for ax_i in axes:
for spine in ax_i.spines.values():
_set_spine_position(spine, ('outward', offset))
|
null | null | null | What does the code add ?
| def addSparseEndpoints(doubleExtrusionWidth, endpoints, fillLine, horizontalSegmentLists, infillSolidity, removedEndpoints, solidSurfaceThickness, surroundingXIntersections):
horizontalEndpoints = horizontalSegmentLists[fillLine]
for segment in horizontalEndpoints:
addSparseEndpointsFromSegment(doubleExtrusionWidth, endpoints, fillLine, horizontalSegmentLists, infillSolidity, removedEndpoints, segment, solidSurfaceThickness, surroundingXIntersections)
| null | null | null | sparse endpoints
| codeqa | def add Sparse Endpoints double Extrusion Width endpoints fill Line horizontal Segment Lists infill Solidity removed Endpoints solid Surface Thickness surrounding X Intersections horizontal Endpoints horizontal Segment Lists[fill Line]for segment in horizontal Endpoints add Sparse Endpoints From Segment double Extrusion Width endpoints fill Line horizontal Segment Lists infill Solidity removed Endpoints segment solid Surface Thickness surrounding X Intersections
| null | null | null | null | Question:
What does the code add ?
Code:
def addSparseEndpoints(doubleExtrusionWidth, endpoints, fillLine, horizontalSegmentLists, infillSolidity, removedEndpoints, solidSurfaceThickness, surroundingXIntersections):
horizontalEndpoints = horizontalSegmentLists[fillLine]
for segment in horizontalEndpoints:
addSparseEndpointsFromSegment(doubleExtrusionWidth, endpoints, fillLine, horizontalSegmentLists, infillSolidity, removedEndpoints, segment, solidSurfaceThickness, surroundingXIntersections)
|
null | null | null | What does the code write to writer ?
| def runNetwork(network, writer):
sensorRegion = network.regions['sensor']
spatialPoolerRegion = network.regions['spatialPoolerRegion']
temporalPoolerRegion = network.regions['temporalPoolerRegion']
anomalyLikelihoodRegion = network.regions['anomalyLikelihoodRegion']
prevPredictedColumns = []
for i in xrange(_NUM_RECORDS):
network.run(1)
consumption = sensorRegion.getOutputData('sourceOut')[0]
anomalyScore = temporalPoolerRegion.getOutputData('anomalyScore')[0]
anomalyLikelihood = anomalyLikelihoodRegion.getOutputData('anomalyLikelihood')[0]
writer.writerow((i, consumption, anomalyScore, anomalyLikelihood))
| null | null | null | output
| codeqa | def run Network network writer sensor Region network regions['sensor']spatial Pooler Region network regions['spatial Pooler Region']temporal Pooler Region network regions['temporal Pooler Region']anomaly Likelihood Region network regions['anomaly Likelihood Region']prev Predicted Columns []for i in xrange NUM RECORDS network run 1 consumption sensor Region get Output Data 'source Out' [0 ]anomaly Score temporal Pooler Region get Output Data 'anomaly Score' [0 ]anomaly Likelihood anomaly Likelihood Region get Output Data 'anomaly Likelihood' [0 ]writer writerow i consumption anomaly Score anomaly Likelihood
| null | null | null | null | Question:
What does the code write to writer ?
Code:
def runNetwork(network, writer):
sensorRegion = network.regions['sensor']
spatialPoolerRegion = network.regions['spatialPoolerRegion']
temporalPoolerRegion = network.regions['temporalPoolerRegion']
anomalyLikelihoodRegion = network.regions['anomalyLikelihoodRegion']
prevPredictedColumns = []
for i in xrange(_NUM_RECORDS):
network.run(1)
consumption = sensorRegion.getOutputData('sourceOut')[0]
anomalyScore = temporalPoolerRegion.getOutputData('anomalyScore')[0]
anomalyLikelihood = anomalyLikelihoodRegion.getOutputData('anomalyLikelihood')[0]
writer.writerow((i, consumption, anomalyScore, anomalyLikelihood))
|
null | null | null | What does the code run ?
| def runNetwork(network, writer):
sensorRegion = network.regions['sensor']
spatialPoolerRegion = network.regions['spatialPoolerRegion']
temporalPoolerRegion = network.regions['temporalPoolerRegion']
anomalyLikelihoodRegion = network.regions['anomalyLikelihoodRegion']
prevPredictedColumns = []
for i in xrange(_NUM_RECORDS):
network.run(1)
consumption = sensorRegion.getOutputData('sourceOut')[0]
anomalyScore = temporalPoolerRegion.getOutputData('anomalyScore')[0]
anomalyLikelihood = anomalyLikelihoodRegion.getOutputData('anomalyLikelihood')[0]
writer.writerow((i, consumption, anomalyScore, anomalyLikelihood))
| null | null | null | the network
| codeqa | def run Network network writer sensor Region network regions['sensor']spatial Pooler Region network regions['spatial Pooler Region']temporal Pooler Region network regions['temporal Pooler Region']anomaly Likelihood Region network regions['anomaly Likelihood Region']prev Predicted Columns []for i in xrange NUM RECORDS network run 1 consumption sensor Region get Output Data 'source Out' [0 ]anomaly Score temporal Pooler Region get Output Data 'anomaly Score' [0 ]anomaly Likelihood anomaly Likelihood Region get Output Data 'anomaly Likelihood' [0 ]writer writerow i consumption anomaly Score anomaly Likelihood
| null | null | null | null | Question:
What does the code run ?
Code:
def runNetwork(network, writer):
sensorRegion = network.regions['sensor']
spatialPoolerRegion = network.regions['spatialPoolerRegion']
temporalPoolerRegion = network.regions['temporalPoolerRegion']
anomalyLikelihoodRegion = network.regions['anomalyLikelihoodRegion']
prevPredictedColumns = []
for i in xrange(_NUM_RECORDS):
network.run(1)
consumption = sensorRegion.getOutputData('sourceOut')[0]
anomalyScore = temporalPoolerRegion.getOutputData('anomalyScore')[0]
anomalyLikelihood = anomalyLikelihoodRegion.getOutputData('anomalyLikelihood')[0]
writer.writerow((i, consumption, anomalyScore, anomalyLikelihood))
|
null | null | null | How does the code write output ?
| def runNetwork(network, writer):
sensorRegion = network.regions['sensor']
spatialPoolerRegion = network.regions['spatialPoolerRegion']
temporalPoolerRegion = network.regions['temporalPoolerRegion']
anomalyLikelihoodRegion = network.regions['anomalyLikelihoodRegion']
prevPredictedColumns = []
for i in xrange(_NUM_RECORDS):
network.run(1)
consumption = sensorRegion.getOutputData('sourceOut')[0]
anomalyScore = temporalPoolerRegion.getOutputData('anomalyScore')[0]
anomalyLikelihood = anomalyLikelihoodRegion.getOutputData('anomalyLikelihood')[0]
writer.writerow((i, consumption, anomalyScore, anomalyLikelihood))
| null | null | null | to writer
| codeqa | def run Network network writer sensor Region network regions['sensor']spatial Pooler Region network regions['spatial Pooler Region']temporal Pooler Region network regions['temporal Pooler Region']anomaly Likelihood Region network regions['anomaly Likelihood Region']prev Predicted Columns []for i in xrange NUM RECORDS network run 1 consumption sensor Region get Output Data 'source Out' [0 ]anomaly Score temporal Pooler Region get Output Data 'anomaly Score' [0 ]anomaly Likelihood anomaly Likelihood Region get Output Data 'anomaly Likelihood' [0 ]writer writerow i consumption anomaly Score anomaly Likelihood
| null | null | null | null | Question:
How does the code write output ?
Code:
def runNetwork(network, writer):
sensorRegion = network.regions['sensor']
spatialPoolerRegion = network.regions['spatialPoolerRegion']
temporalPoolerRegion = network.regions['temporalPoolerRegion']
anomalyLikelihoodRegion = network.regions['anomalyLikelihoodRegion']
prevPredictedColumns = []
for i in xrange(_NUM_RECORDS):
network.run(1)
consumption = sensorRegion.getOutputData('sourceOut')[0]
anomalyScore = temporalPoolerRegion.getOutputData('anomalyScore')[0]
anomalyLikelihood = anomalyLikelihoodRegion.getOutputData('anomalyLikelihood')[0]
writer.writerow((i, consumption, anomalyScore, anomalyLikelihood))
|
null | null | null | When does viewport parameter ?
| def draw_texture(tex):
from .program import Program
program = Program(vert_draw, frag_draw)
program['u_texture'] = tex
program['a_position'] = [[(-1.0), (-1.0)], [(-1.0), 1.0], [1.0, (-1.0)], [1.0, 1.0]]
program['a_texcoord'] = [[0.0, 1.0], [0.0, 0.0], [1.0, 1.0], [1.0, 0.0]]
program.draw('triangle_strip')
| null | null | null | current
| codeqa | def draw texture tex from program import Programprogram Program vert draw frag draw program['u texture'] texprogram['a position'] [[ -1 0 -1 0 ] [ -1 0 1 0] [1 0 -1 0 ] [1 0 1 0]]program['a texcoord'] [[ 0 0 1 0] [0 0 0 0] [1 0 1 0] [1 0 0 0]]program draw 'triangle strip'
| null | null | null | null | Question:
When does viewport parameter ?
Code:
def draw_texture(tex):
from .program import Program
program = Program(vert_draw, frag_draw)
program['u_texture'] = tex
program['a_position'] = [[(-1.0), (-1.0)], [(-1.0), 1.0], [1.0, (-1.0)], [1.0, 1.0]]
program['a_texcoord'] = [[0.0, 1.0], [0.0, 0.0], [1.0, 1.0], [1.0, 0.0]]
program.draw('triangle_strip')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.