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 allows a course author to select the grader type for a given section of a course ?
| def _filter_entrance_exam_grader(graders):
if is_entrance_exams_enabled():
graders = [grader for grader in graders if (grader.get('type') != u'Entrance Exam')]
return graders
| null | null | null | dropdown
| codeqa | def filter entrance exam grader graders if is entrance exams enabled graders [grader for grader in graders if grader get 'type' u' Entrance Exam' ]return graders
| null | null | null | null | Question:
What allows a course author to select the grader type for a given section of a course ?
Code:
def _filter_entrance_exam_grader(graders):
if is_entrance_exams_enabled():
graders = [grader for grader in graders if (grader.get('type') != u'Entrance Exam')]
return graders
|
null | null | null | What selects the grader type for a given section of a course ?
| def _filter_entrance_exam_grader(graders):
if is_entrance_exams_enabled():
graders = [grader for grader in graders if (grader.get('type') != u'Entrance Exam')]
return graders
| null | null | null | a course author
| codeqa | def filter entrance exam grader graders if is entrance exams enabled graders [grader for grader in graders if grader get 'type' u' Entrance Exam' ]return graders
| null | null | null | null | Question:
What selects the grader type for a given section of a course ?
Code:
def _filter_entrance_exam_grader(graders):
if is_entrance_exams_enabled():
graders = [grader for grader in graders if (grader.get('type') != u'Entrance Exam')]
return graders
|
null | null | null | What does the code add ?
| def isPointAddedAroundClosest(pixelTable, layerExtrusionWidth, paths, removedEndpointPoint, width):
closestDistanceSquared = 1e+18
closestPathIndex = None
for pathIndex in xrange(len(paths)):
path = paths[pathIndex]
for pointIndex in xrange(len(path)):
point = path[pointIndex]
distanceSquared = abs((point - removedEndpointPoint))
if (distanceSquared < closestDistanceSquared):
closestDistanceSquared = distanceSquared
closestPathIndex = pathIndex
if (closestPathIndex == None):
return
if (closestDistanceSquared < ((0.8 * layerExtrusionWidth) * layerExtrusionWidth)):
return
closestPath = paths[closestPathIndex]
closestPointIndex = getWithLeastLength(closestPath, removedEndpointPoint)
if isAddedPointOnPathFree(closestPath, pixelTable, removedEndpointPoint, closestPointIndex, width):
addPointOnPath(closestPath, closestPathIndex, pixelTable, removedEndpointPoint, closestPointIndex, width)
return True
return isSidePointAdded(pixelTable, closestPath, closestPathIndex, closestPointIndex, layerExtrusionWidth, removedEndpointPoint, width)
| null | null | null | the closest removed endpoint to the path
| codeqa | def is Point Added Around Closest pixel Table layer Extrusion Width paths removed Endpoint Point width closest Distance Squared 1e+ 18 closest Path Index Nonefor path Index in xrange len paths path paths[path Index]for point Index in xrange len path point path[point Index]distance Squared abs point - removed Endpoint Point if distance Squared < closest Distance Squared closest Distance Squared distance Squaredclosest Path Index path Indexif closest Path Index None returnif closest Distance Squared < 0 8 * layer Extrusion Width * layer Extrusion Width returnclosest Path paths[closest Path Index]closest Point Index get With Least Length closest Path removed Endpoint Point if is Added Point On Path Free closest Path pixel Table removed Endpoint Point closest Point Index width add Point On Path closest Path closest Path Index pixel Table removed Endpoint Point closest Point Index width return Truereturn is Side Point Added pixel Table closest Path closest Path Index closest Point Index layer Extrusion Width removed Endpoint Point width
| null | null | null | null | Question:
What does the code add ?
Code:
def isPointAddedAroundClosest(pixelTable, layerExtrusionWidth, paths, removedEndpointPoint, width):
closestDistanceSquared = 1e+18
closestPathIndex = None
for pathIndex in xrange(len(paths)):
path = paths[pathIndex]
for pointIndex in xrange(len(path)):
point = path[pointIndex]
distanceSquared = abs((point - removedEndpointPoint))
if (distanceSquared < closestDistanceSquared):
closestDistanceSquared = distanceSquared
closestPathIndex = pathIndex
if (closestPathIndex == None):
return
if (closestDistanceSquared < ((0.8 * layerExtrusionWidth) * layerExtrusionWidth)):
return
closestPath = paths[closestPathIndex]
closestPointIndex = getWithLeastLength(closestPath, removedEndpointPoint)
if isAddedPointOnPathFree(closestPath, pixelTable, removedEndpointPoint, closestPointIndex, width):
addPointOnPath(closestPath, closestPathIndex, pixelTable, removedEndpointPoint, closestPointIndex, width)
return True
return isSidePointAdded(pixelTable, closestPath, closestPathIndex, closestPointIndex, layerExtrusionWidth, removedEndpointPoint, width)
|
null | null | null | How do them cache on the current model for use ?
| @receiver(pre_save, sender=User)
def user_pre_save_callback(sender, **kwargs):
user = kwargs['instance']
user._changed_fields = get_changed_fields_dict(user, sender)
| null | null | null | as a private field
| codeqa | @receiver pre save sender User def user pre save callback sender **kwargs user kwargs['instance']user changed fields get changed fields dict user sender
| null | null | null | null | Question:
How do them cache on the current model for use ?
Code:
@receiver(pre_save, sender=User)
def user_pre_save_callback(sender, **kwargs):
user = kwargs['instance']
user._changed_fields = get_changed_fields_dict(user, sender)
|
null | null | null | When do old fields on the user instance capture ?
| @receiver(pre_save, sender=User)
def user_pre_save_callback(sender, **kwargs):
user = kwargs['instance']
user._changed_fields = get_changed_fields_dict(user, sender)
| null | null | null | before save
| codeqa | @receiver pre save sender User def user pre save callback sender **kwargs user kwargs['instance']user changed fields get changed fields dict user sender
| null | null | null | null | Question:
When do old fields on the user instance capture ?
Code:
@receiver(pre_save, sender=User)
def user_pre_save_callback(sender, **kwargs):
user = kwargs['instance']
user._changed_fields = get_changed_fields_dict(user, sender)
|
null | null | null | What does the code return ?
| def get_items(xml):
try:
from bs4 import BeautifulSoup
except ImportError:
error = u'Missing dependency "BeautifulSoup4" and "lxml" required to import WordPress XML files.'
sys.exit(error)
with open(xml, encoding=u'utf-8') as infile:
xmlfile = infile.read()
soup = BeautifulSoup(xmlfile, u'xml')
items = soup.rss.channel.findAll(u'item')
return items
| null | null | null | a list of items
| codeqa | def get items xml try from bs 4 import Beautiful Soupexcept Import Error error u' Missingdependency" Beautiful Soup 4 "and"lxml"requiredtoimport Word Press XM Lfiles 'sys exit error with open xml encoding u'utf- 8 ' as infile xmlfile infile read soup Beautiful Soup xmlfile u'xml' items soup rss channel find All u'item' return items
| null | null | null | null | Question:
What does the code return ?
Code:
def get_items(xml):
try:
from bs4 import BeautifulSoup
except ImportError:
error = u'Missing dependency "BeautifulSoup4" and "lxml" required to import WordPress XML files.'
sys.exit(error)
with open(xml, encoding=u'utf-8') as infile:
xmlfile = infile.read()
soup = BeautifulSoup(xmlfile, u'xml')
items = soup.rss.channel.findAll(u'item')
return items
|
null | null | null | For what purpose does the code build the query based on the context ?
| def _select_namespaces_query(context, session):
LOG.debug('context.is_admin=%(is_admin)s; context.owner=%(owner)s', {'is_admin': context.is_admin, 'owner': context.owner})
query_ns = session.query(models.MetadefNamespace)
if context.is_admin:
return query_ns
else:
if (context.owner is not None):
query = query_ns.filter(or_((models.MetadefNamespace.owner == context.owner), (models.MetadefNamespace.visibility == 'public')))
else:
query = query_ns.filter((models.MetadefNamespace.visibility == 'public'))
return query
| null | null | null | to get all namespaces
| codeqa | def select namespaces query context session LOG debug 'context is admin % is admin s context owner % owner s' {'is admin' context is admin 'owner' context owner} query ns session query models Metadef Namespace if context is admin return query nselse if context owner is not None query query ns filter or models Metadef Namespace owner context owner models Metadef Namespace visibility 'public' else query query ns filter models Metadef Namespace visibility 'public' return query
| null | null | null | null | Question:
For what purpose does the code build the query based on the context ?
Code:
def _select_namespaces_query(context, session):
LOG.debug('context.is_admin=%(is_admin)s; context.owner=%(owner)s', {'is_admin': context.is_admin, 'owner': context.owner})
query_ns = session.query(models.MetadefNamespace)
if context.is_admin:
return query_ns
else:
if (context.owner is not None):
query = query_ns.filter(or_((models.MetadefNamespace.owner == context.owner), (models.MetadefNamespace.visibility == 'public')))
else:
query = query_ns.filter((models.MetadefNamespace.visibility == 'public'))
return query
|
null | null | null | What does the code build based on the context to get all namespaces ?
| def _select_namespaces_query(context, session):
LOG.debug('context.is_admin=%(is_admin)s; context.owner=%(owner)s', {'is_admin': context.is_admin, 'owner': context.owner})
query_ns = session.query(models.MetadefNamespace)
if context.is_admin:
return query_ns
else:
if (context.owner is not None):
query = query_ns.filter(or_((models.MetadefNamespace.owner == context.owner), (models.MetadefNamespace.visibility == 'public')))
else:
query = query_ns.filter((models.MetadefNamespace.visibility == 'public'))
return query
| null | null | null | the query
| codeqa | def select namespaces query context session LOG debug 'context is admin % is admin s context owner % owner s' {'is admin' context is admin 'owner' context owner} query ns session query models Metadef Namespace if context is admin return query nselse if context owner is not None query query ns filter or models Metadef Namespace owner context owner models Metadef Namespace visibility 'public' else query query ns filter models Metadef Namespace visibility 'public' return query
| null | null | null | null | Question:
What does the code build based on the context to get all namespaces ?
Code:
def _select_namespaces_query(context, session):
LOG.debug('context.is_admin=%(is_admin)s; context.owner=%(owner)s', {'is_admin': context.is_admin, 'owner': context.owner})
query_ns = session.query(models.MetadefNamespace)
if context.is_admin:
return query_ns
else:
if (context.owner is not None):
query = query_ns.filter(or_((models.MetadefNamespace.owner == context.owner), (models.MetadefNamespace.visibility == 'public')))
else:
query = query_ns.filter((models.MetadefNamespace.visibility == 'public'))
return query
|
null | null | null | How does the code build the query to get all namespaces ?
| def _select_namespaces_query(context, session):
LOG.debug('context.is_admin=%(is_admin)s; context.owner=%(owner)s', {'is_admin': context.is_admin, 'owner': context.owner})
query_ns = session.query(models.MetadefNamespace)
if context.is_admin:
return query_ns
else:
if (context.owner is not None):
query = query_ns.filter(or_((models.MetadefNamespace.owner == context.owner), (models.MetadefNamespace.visibility == 'public')))
else:
query = query_ns.filter((models.MetadefNamespace.visibility == 'public'))
return query
| null | null | null | based on the context
| codeqa | def select namespaces query context session LOG debug 'context is admin % is admin s context owner % owner s' {'is admin' context is admin 'owner' context owner} query ns session query models Metadef Namespace if context is admin return query nselse if context owner is not None query query ns filter or models Metadef Namespace owner context owner models Metadef Namespace visibility 'public' else query query ns filter models Metadef Namespace visibility 'public' return query
| null | null | null | null | Question:
How does the code build the query to get all namespaces ?
Code:
def _select_namespaces_query(context, session):
LOG.debug('context.is_admin=%(is_admin)s; context.owner=%(owner)s', {'is_admin': context.is_admin, 'owner': context.owner})
query_ns = session.query(models.MetadefNamespace)
if context.is_admin:
return query_ns
else:
if (context.owner is not None):
query = query_ns.filter(or_((models.MetadefNamespace.owner == context.owner), (models.MetadefNamespace.visibility == 'public')))
else:
query = query_ns.filter((models.MetadefNamespace.visibility == 'public'))
return query
|
null | null | null | Where is s the largest subset of elements that appear in pairs of sets given by sets and l ?
| def pairwise_most_common(sets):
from sympy.utilities.iterables import subsets
from collections import defaultdict
most = (-1)
for (i, j) in subsets(list(range(len(sets))), 2):
com = (sets[i] & sets[j])
if (com and (len(com) > most)):
best = defaultdict(list)
best_keys = []
most = len(com)
if (len(com) == most):
if (com not in best_keys):
best_keys.append(com)
best[best_keys.index(com)].append((i, j))
if (most == (-1)):
return []
for k in range(len(best)):
best_keys[k] = (best_keys[k], best[k])
best_keys.sort(key=(lambda x: len(x[1])))
return best_keys
| null | null | null | where
| codeqa | def pairwise most common sets from sympy utilities iterables import subsetsfrom collections import defaultdictmost -1 for i j in subsets list range len sets 2 com sets[i] & sets[j] if com and len com > most best defaultdict list best keys []most len com if len com most if com not in best keys best keys append com best[best keys index com ] append i j if most -1 return []for k in range len best best keys[k] best keys[k] best[k] best keys sort key lambda x len x[ 1 ] return best keys
| null | null | null | null | Question:
Where is s the largest subset of elements that appear in pairs of sets given by sets and l ?
Code:
def pairwise_most_common(sets):
from sympy.utilities.iterables import subsets
from collections import defaultdict
most = (-1)
for (i, j) in subsets(list(range(len(sets))), 2):
com = (sets[i] & sets[j])
if (com and (len(com) > most)):
best = defaultdict(list)
best_keys = []
most = len(com)
if (len(com) == most):
if (com not in best_keys):
best_keys.append(com)
best[best_keys.index(com)].append((i, j))
if (most == (-1)):
return []
for k in range(len(best)):
best_keys[k] = (best_keys[k], best[k])
best_keys.sort(key=(lambda x: len(x[1])))
return best_keys
|
null | null | null | Where is a list of tuples giving the indices of the pairs of sets in which those elements appeared ?
| def pairwise_most_common(sets):
from sympy.utilities.iterables import subsets
from collections import defaultdict
most = (-1)
for (i, j) in subsets(list(range(len(sets))), 2):
com = (sets[i] & sets[j])
if (com and (len(com) > most)):
best = defaultdict(list)
best_keys = []
most = len(com)
if (len(com) == most):
if (com not in best_keys):
best_keys.append(com)
best[best_keys.index(com)].append((i, j))
if (most == (-1)):
return []
for k in range(len(best)):
best_keys[k] = (best_keys[k], best[k])
best_keys.sort(key=(lambda x: len(x[1])))
return best_keys
| null | null | null | where
| codeqa | def pairwise most common sets from sympy utilities iterables import subsetsfrom collections import defaultdictmost -1 for i j in subsets list range len sets 2 com sets[i] & sets[j] if com and len com > most best defaultdict list best keys []most len com if len com most if com not in best keys best keys append com best[best keys index com ] append i j if most -1 return []for k in range len best best keys[k] best keys[k] best[k] best keys sort key lambda x len x[ 1 ] return best keys
| null | null | null | null | Question:
Where is a list of tuples giving the indices of the pairs of sets in which those elements appeared ?
Code:
def pairwise_most_common(sets):
from sympy.utilities.iterables import subsets
from collections import defaultdict
most = (-1)
for (i, j) in subsets(list(range(len(sets))), 2):
com = (sets[i] & sets[j])
if (com and (len(com) > most)):
best = defaultdict(list)
best_keys = []
most = len(com)
if (len(com) == most):
if (com not in best_keys):
best_keys.append(com)
best[best_keys.index(com)].append((i, j))
if (most == (-1)):
return []
for k in range(len(best)):
best_keys[k] = (best_keys[k], best[k])
best_keys.sort(key=(lambda x: len(x[1])))
return best_keys
|
null | null | null | What is where ?
| def pairwise_most_common(sets):
from sympy.utilities.iterables import subsets
from collections import defaultdict
most = (-1)
for (i, j) in subsets(list(range(len(sets))), 2):
com = (sets[i] & sets[j])
if (com and (len(com) > most)):
best = defaultdict(list)
best_keys = []
most = len(com)
if (len(com) == most):
if (com not in best_keys):
best_keys.append(com)
best[best_keys.index(com)].append((i, j))
if (most == (-1)):
return []
for k in range(len(best)):
best_keys[k] = (best_keys[k], best[k])
best_keys.sort(key=(lambda x: len(x[1])))
return best_keys
| null | null | null | a list of tuples giving the indices of the pairs of sets in which those elements appeared
| codeqa | def pairwise most common sets from sympy utilities iterables import subsetsfrom collections import defaultdictmost -1 for i j in subsets list range len sets 2 com sets[i] & sets[j] if com and len com > most best defaultdict list best keys []most len com if len com most if com not in best keys best keys append com best[best keys index com ] append i j if most -1 return []for k in range len best best keys[k] best keys[k] best[k] best keys sort key lambda x len x[ 1 ] return best keys
| null | null | null | null | Question:
What is where ?
Code:
def pairwise_most_common(sets):
from sympy.utilities.iterables import subsets
from collections import defaultdict
most = (-1)
for (i, j) in subsets(list(range(len(sets))), 2):
com = (sets[i] & sets[j])
if (com and (len(com) > most)):
best = defaultdict(list)
best_keys = []
most = len(com)
if (len(com) == most):
if (com not in best_keys):
best_keys.append(com)
best[best_keys.index(com)].append((i, j))
if (most == (-1)):
return []
for k in range(len(best)):
best_keys[k] = (best_keys[k], best[k])
best_keys.sort(key=(lambda x: len(x[1])))
return best_keys
|
null | null | null | Where did those elements appear ?
| def pairwise_most_common(sets):
from sympy.utilities.iterables import subsets
from collections import defaultdict
most = (-1)
for (i, j) in subsets(list(range(len(sets))), 2):
com = (sets[i] & sets[j])
if (com and (len(com) > most)):
best = defaultdict(list)
best_keys = []
most = len(com)
if (len(com) == most):
if (com not in best_keys):
best_keys.append(com)
best[best_keys.index(com)].append((i, j))
if (most == (-1)):
return []
for k in range(len(best)):
best_keys[k] = (best_keys[k], best[k])
best_keys.sort(key=(lambda x: len(x[1])))
return best_keys
| null | null | null | the pairs of sets
| codeqa | def pairwise most common sets from sympy utilities iterables import subsetsfrom collections import defaultdictmost -1 for i j in subsets list range len sets 2 com sets[i] & sets[j] if com and len com > most best defaultdict list best keys []most len com if len com most if com not in best keys best keys append com best[best keys index com ] append i j if most -1 return []for k in range len best best keys[k] best keys[k] best[k] best keys sort key lambda x len x[ 1 ] return best keys
| null | null | null | null | Question:
Where did those elements appear ?
Code:
def pairwise_most_common(sets):
from sympy.utilities.iterables import subsets
from collections import defaultdict
most = (-1)
for (i, j) in subsets(list(range(len(sets))), 2):
com = (sets[i] & sets[j])
if (com and (len(com) > most)):
best = defaultdict(list)
best_keys = []
most = len(com)
if (len(com) == most):
if (com not in best_keys):
best_keys.append(com)
best[best_keys.index(com)].append((i, j))
if (most == (-1)):
return []
for k in range(len(best)):
best_keys[k] = (best_keys[k], best[k])
best_keys.sort(key=(lambda x: len(x[1])))
return best_keys
|
null | null | null | What do tuples give ?
| def pairwise_most_common(sets):
from sympy.utilities.iterables import subsets
from collections import defaultdict
most = (-1)
for (i, j) in subsets(list(range(len(sets))), 2):
com = (sets[i] & sets[j])
if (com and (len(com) > most)):
best = defaultdict(list)
best_keys = []
most = len(com)
if (len(com) == most):
if (com not in best_keys):
best_keys.append(com)
best[best_keys.index(com)].append((i, j))
if (most == (-1)):
return []
for k in range(len(best)):
best_keys[k] = (best_keys[k], best[k])
best_keys.sort(key=(lambda x: len(x[1])))
return best_keys
| null | null | null | the indices of the pairs of sets in which those elements appeared
| codeqa | def pairwise most common sets from sympy utilities iterables import subsetsfrom collections import defaultdictmost -1 for i j in subsets list range len sets 2 com sets[i] & sets[j] if com and len com > most best defaultdict list best keys []most len com if len com most if com not in best keys best keys append com best[best keys index com ] append i j if most -1 return []for k in range len best best keys[k] best keys[k] best[k] best keys sort key lambda x len x[ 1 ] return best keys
| null | null | null | null | Question:
What do tuples give ?
Code:
def pairwise_most_common(sets):
from sympy.utilities.iterables import subsets
from collections import defaultdict
most = (-1)
for (i, j) in subsets(list(range(len(sets))), 2):
com = (sets[i] & sets[j])
if (com and (len(com) > most)):
best = defaultdict(list)
best_keys = []
most = len(com)
if (len(com) == most):
if (com not in best_keys):
best_keys.append(com)
best[best_keys.index(com)].append((i, j))
if (most == (-1)):
return []
for k in range(len(best)):
best_keys[k] = (best_keys[k], best[k])
best_keys.sort(key=(lambda x: len(x[1])))
return best_keys
|
null | null | null | What is giving the indices of the pairs of sets in which those elements appeared ?
| def pairwise_most_common(sets):
from sympy.utilities.iterables import subsets
from collections import defaultdict
most = (-1)
for (i, j) in subsets(list(range(len(sets))), 2):
com = (sets[i] & sets[j])
if (com and (len(com) > most)):
best = defaultdict(list)
best_keys = []
most = len(com)
if (len(com) == most):
if (com not in best_keys):
best_keys.append(com)
best[best_keys.index(com)].append((i, j))
if (most == (-1)):
return []
for k in range(len(best)):
best_keys[k] = (best_keys[k], best[k])
best_keys.sort(key=(lambda x: len(x[1])))
return best_keys
| null | null | null | tuples
| codeqa | def pairwise most common sets from sympy utilities iterables import subsetsfrom collections import defaultdictmost -1 for i j in subsets list range len sets 2 com sets[i] & sets[j] if com and len com > most best defaultdict list best keys []most len com if len com most if com not in best keys best keys append com best[best keys index com ] append i j if most -1 return []for k in range len best best keys[k] best keys[k] best[k] best keys sort key lambda x len x[ 1 ] return best keys
| null | null | null | null | Question:
What is giving the indices of the pairs of sets in which those elements appeared ?
Code:
def pairwise_most_common(sets):
from sympy.utilities.iterables import subsets
from collections import defaultdict
most = (-1)
for (i, j) in subsets(list(range(len(sets))), 2):
com = (sets[i] & sets[j])
if (com and (len(com) > most)):
best = defaultdict(list)
best_keys = []
most = len(com)
if (len(com) == most):
if (com not in best_keys):
best_keys.append(com)
best[best_keys.index(com)].append((i, j))
if (most == (-1)):
return []
for k in range(len(best)):
best_keys[k] = (best_keys[k], best[k])
best_keys.sort(key=(lambda x: len(x[1])))
return best_keys
|
null | null | null | Where do elements appear ?
| def pairwise_most_common(sets):
from sympy.utilities.iterables import subsets
from collections import defaultdict
most = (-1)
for (i, j) in subsets(list(range(len(sets))), 2):
com = (sets[i] & sets[j])
if (com and (len(com) > most)):
best = defaultdict(list)
best_keys = []
most = len(com)
if (len(com) == most):
if (com not in best_keys):
best_keys.append(com)
best[best_keys.index(com)].append((i, j))
if (most == (-1)):
return []
for k in range(len(best)):
best_keys[k] = (best_keys[k], best[k])
best_keys.sort(key=(lambda x: len(x[1])))
return best_keys
| null | null | null | in pairs of sets given by sets and l
| codeqa | def pairwise most common sets from sympy utilities iterables import subsetsfrom collections import defaultdictmost -1 for i j in subsets list range len sets 2 com sets[i] & sets[j] if com and len com > most best defaultdict list best keys []most len com if len com most if com not in best keys best keys append com best[best keys index com ] append i j if most -1 return []for k in range len best best keys[k] best keys[k] best[k] best keys sort key lambda x len x[ 1 ] return best keys
| null | null | null | null | Question:
Where do elements appear ?
Code:
def pairwise_most_common(sets):
from sympy.utilities.iterables import subsets
from collections import defaultdict
most = (-1)
for (i, j) in subsets(list(range(len(sets))), 2):
com = (sets[i] & sets[j])
if (com and (len(com) > most)):
best = defaultdict(list)
best_keys = []
most = len(com)
if (len(com) == most):
if (com not in best_keys):
best_keys.append(com)
best[best_keys.index(com)].append((i, j))
if (most == (-1)):
return []
for k in range(len(best)):
best_keys[k] = (best_keys[k], best[k])
best_keys.sort(key=(lambda x: len(x[1])))
return best_keys
|
null | null | null | What is the largest subset of elements that appear in pairs of sets given by sets and l where ?
| def pairwise_most_common(sets):
from sympy.utilities.iterables import subsets
from collections import defaultdict
most = (-1)
for (i, j) in subsets(list(range(len(sets))), 2):
com = (sets[i] & sets[j])
if (com and (len(com) > most)):
best = defaultdict(list)
best_keys = []
most = len(com)
if (len(com) == most):
if (com not in best_keys):
best_keys.append(com)
best[best_keys.index(com)].append((i, j))
if (most == (-1)):
return []
for k in range(len(best)):
best_keys[k] = (best_keys[k], best[k])
best_keys.sort(key=(lambda x: len(x[1])))
return best_keys
| null | null | null | s
| codeqa | def pairwise most common sets from sympy utilities iterables import subsetsfrom collections import defaultdictmost -1 for i j in subsets list range len sets 2 com sets[i] & sets[j] if com and len com > most best defaultdict list best keys []most len com if len com most if com not in best keys best keys append com best[best keys index com ] append i j if most -1 return []for k in range len best best keys[k] best keys[k] best[k] best keys sort key lambda x len x[ 1 ] return best keys
| null | null | null | null | Question:
What is the largest subset of elements that appear in pairs of sets given by sets and l where ?
Code:
def pairwise_most_common(sets):
from sympy.utilities.iterables import subsets
from collections import defaultdict
most = (-1)
for (i, j) in subsets(list(range(len(sets))), 2):
com = (sets[i] & sets[j])
if (com and (len(com) > most)):
best = defaultdict(list)
best_keys = []
most = len(com)
if (len(com) == most):
if (com not in best_keys):
best_keys.append(com)
best[best_keys.index(com)].append((i, j))
if (most == (-1)):
return []
for k in range(len(best)):
best_keys[k] = (best_keys[k], best[k])
best_keys.sort(key=(lambda x: len(x[1])))
return best_keys
|
null | null | null | What appeared the pairs of sets ?
| def pairwise_most_common(sets):
from sympy.utilities.iterables import subsets
from collections import defaultdict
most = (-1)
for (i, j) in subsets(list(range(len(sets))), 2):
com = (sets[i] & sets[j])
if (com and (len(com) > most)):
best = defaultdict(list)
best_keys = []
most = len(com)
if (len(com) == most):
if (com not in best_keys):
best_keys.append(com)
best[best_keys.index(com)].append((i, j))
if (most == (-1)):
return []
for k in range(len(best)):
best_keys[k] = (best_keys[k], best[k])
best_keys.sort(key=(lambda x: len(x[1])))
return best_keys
| null | null | null | those elements
| codeqa | def pairwise most common sets from sympy utilities iterables import subsetsfrom collections import defaultdictmost -1 for i j in subsets list range len sets 2 com sets[i] & sets[j] if com and len com > most best defaultdict list best keys []most len com if len com most if com not in best keys best keys append com best[best keys index com ] append i j if most -1 return []for k in range len best best keys[k] best keys[k] best[k] best keys sort key lambda x len x[ 1 ] return best keys
| null | null | null | null | Question:
What appeared the pairs of sets ?
Code:
def pairwise_most_common(sets):
from sympy.utilities.iterables import subsets
from collections import defaultdict
most = (-1)
for (i, j) in subsets(list(range(len(sets))), 2):
com = (sets[i] & sets[j])
if (com and (len(com) > most)):
best = defaultdict(list)
best_keys = []
most = len(com)
if (len(com) == most):
if (com not in best_keys):
best_keys.append(com)
best[best_keys.index(com)].append((i, j))
if (most == (-1)):
return []
for k in range(len(best)):
best_keys[k] = (best_keys[k], best[k])
best_keys.sort(key=(lambda x: len(x[1])))
return best_keys
|
null | null | null | What do return image array show ?
| def make_diff_image(im1, im2):
ds = im1.shape
es = im2.shape
diff = np.empty((max(ds[0], es[0]), max(ds[1], es[1]), 4), dtype=int)
diff[..., :3] = 128
diff[..., 3] = 255
diff[:ds[0], :ds[1], :min(ds[2], 3)] += im1[..., :3]
diff[:es[0], :es[1], :min(es[2], 3)] -= im2[..., :3]
diff = np.clip(diff, 0, 255).astype(np.ubyte)
return diff
| null | null | null | the differences between im1 and im2
| codeqa | def make diff image im 1 im 2 ds im 1 shapees im 2 shapediff np empty max ds[ 0 ] es[ 0 ] max ds[ 1 ] es[ 1 ] 4 dtype int diff[ 3] 128 diff[ 3] 255 diff[ ds[ 0 ] ds[ 1 ] min ds[ 2 ] 3 ] + im 1 [ 3]diff[ es[ 0 ] es[ 1 ] min es[ 2 ] 3 ] - im 2 [ 3]diff np clip diff 0 255 astype np ubyte return diff
| null | null | null | null | Question:
What do return image array show ?
Code:
def make_diff_image(im1, im2):
ds = im1.shape
es = im2.shape
diff = np.empty((max(ds[0], es[0]), max(ds[1], es[1]), 4), dtype=int)
diff[..., :3] = 128
diff[..., 3] = 255
diff[:ds[0], :ds[1], :min(ds[2], 3)] += im1[..., :3]
diff[:es[0], :es[1], :min(es[2], 3)] -= im2[..., :3]
diff = np.clip(diff, 0, 255).astype(np.ubyte)
return diff
|
null | null | null | What is showing the differences between im1 and im2 ?
| def make_diff_image(im1, im2):
ds = im1.shape
es = im2.shape
diff = np.empty((max(ds[0], es[0]), max(ds[1], es[1]), 4), dtype=int)
diff[..., :3] = 128
diff[..., 3] = 255
diff[:ds[0], :ds[1], :min(ds[2], 3)] += im1[..., :3]
diff[:es[0], :es[1], :min(es[2], 3)] -= im2[..., :3]
diff = np.clip(diff, 0, 255).astype(np.ubyte)
return diff
| null | null | null | return image array
| codeqa | def make diff image im 1 im 2 ds im 1 shapees im 2 shapediff np empty max ds[ 0 ] es[ 0 ] max ds[ 1 ] es[ 1 ] 4 dtype int diff[ 3] 128 diff[ 3] 255 diff[ ds[ 0 ] ds[ 1 ] min ds[ 2 ] 3 ] + im 1 [ 3]diff[ es[ 0 ] es[ 1 ] min es[ 2 ] 3 ] - im 2 [ 3]diff np clip diff 0 255 astype np ubyte return diff
| null | null | null | null | Question:
What is showing the differences between im1 and im2 ?
Code:
def make_diff_image(im1, im2):
ds = im1.shape
es = im2.shape
diff = np.empty((max(ds[0], es[0]), max(ds[1], es[1]), 4), dtype=int)
diff[..., :3] = 128
diff[..., 3] = 255
diff[:ds[0], :ds[1], :min(ds[2], 3)] += im1[..., :3]
diff[:es[0], :es[1], :min(es[2], 3)] -= im2[..., :3]
diff = np.clip(diff, 0, 255).astype(np.ubyte)
return diff
|
null | null | null | What is done in widgets new ?
| def initialize_settings(instance):
provider = default_provider.get_provider(instance.__class__)
if provider:
provider.initialize(instance)
| null | null | null | this
| codeqa | def initialize settings instance provider default provider get provider instance class if provider provider initialize instance
| null | null | null | null | Question:
What is done in widgets new ?
Code:
def initialize_settings(instance):
provider = default_provider.get_provider(instance.__class__)
if provider:
provider.initialize(instance)
|
null | null | null | Where is this done usually ?
| def initialize_settings(instance):
provider = default_provider.get_provider(instance.__class__)
if provider:
provider.initialize(instance)
| null | null | null | in widgets new
| codeqa | def initialize settings instance provider default provider get provider instance class if provider provider initialize instance
| null | null | null | null | Question:
Where is this done usually ?
Code:
def initialize_settings(instance):
provider = default_provider.get_provider(instance.__class__)
if provider:
provider.initialize(instance)
|
null | null | null | When is this done in widgets new ?
| def initialize_settings(instance):
provider = default_provider.get_provider(instance.__class__)
if provider:
provider.initialize(instance)
| null | null | null | usually
| codeqa | def initialize settings instance provider default provider get provider instance class if provider provider initialize instance
| null | null | null | null | Question:
When is this done in widgets new ?
Code:
def initialize_settings(instance):
provider = default_provider.get_provider(instance.__class__)
if provider:
provider.initialize(instance)
|
null | null | null | What does the code calculate along the given axis ?
| @docfiller
def maximum_filter1d(input, size, axis=(-1), output=None, mode='reflect', cval=0.0, origin=0):
input = numpy.asarray(input)
if numpy.iscomplexobj(input):
raise TypeError('Complex type not supported')
axis = _ni_support._check_axis(axis, input.ndim)
if (size < 1):
raise RuntimeError('incorrect filter size')
(output, return_value) = _ni_support._get_output(output, input)
if ((((size // 2) + origin) < 0) or (((size // 2) + origin) >= size)):
raise ValueError('invalid origin')
mode = _ni_support._extend_mode_to_code(mode)
_nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval, origin, 0)
return return_value
| null | null | null | a one - dimensional maximum filter
| codeqa | @docfillerdef maximum filter 1 d input size axis -1 output None mode 'reflect' cval 0 0 origin 0 input numpy asarray input if numpy iscomplexobj input raise Type Error ' Complextypenotsupported' axis ni support check axis axis input ndim if size < 1 raise Runtime Error 'incorrectfiltersize' output return value ni support get output output input if size // 2 + origin < 0 or size // 2 + origin > size raise Value Error 'invalidorigin' mode ni support extend mode to code mode nd image min or max filter 1 d input size axis output mode cval origin 0 return return value
| null | null | null | null | Question:
What does the code calculate along the given axis ?
Code:
@docfiller
def maximum_filter1d(input, size, axis=(-1), output=None, mode='reflect', cval=0.0, origin=0):
input = numpy.asarray(input)
if numpy.iscomplexobj(input):
raise TypeError('Complex type not supported')
axis = _ni_support._check_axis(axis, input.ndim)
if (size < 1):
raise RuntimeError('incorrect filter size')
(output, return_value) = _ni_support._get_output(output, input)
if ((((size // 2) + origin) < 0) or (((size // 2) + origin) >= size)):
raise ValueError('invalid origin')
mode = _ni_support._extend_mode_to_code(mode)
_nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval, origin, 0)
return return_value
|
null | null | null | What does a class return ?
| def import_class(import_str):
(mod_str, _sep, class_str) = import_str.rpartition('.')
__import__(mod_str)
return getattr(sys.modules[mod_str], class_str)
| null | null | null | from a string including module and class
| codeqa | def import class import str mod str sep class str import str rpartition ' ' import mod str return getattr sys modules[mod str] class str
| null | null | null | null | Question:
What does a class return ?
Code:
def import_class(import_str):
(mod_str, _sep, class_str) = import_str.rpartition('.')
__import__(mod_str)
return getattr(sys.modules[mod_str], class_str)
|
null | null | null | What returns from a string including module and class ?
| def import_class(import_str):
(mod_str, _sep, class_str) = import_str.rpartition('.')
__import__(mod_str)
return getattr(sys.modules[mod_str], class_str)
| null | null | null | a class
| codeqa | def import class import str mod str sep class str import str rpartition ' ' import mod str return getattr sys modules[mod str] class str
| null | null | null | null | Question:
What returns from a string including module and class ?
Code:
def import_class(import_str):
(mod_str, _sep, class_str) = import_str.rpartition('.')
__import__(mod_str)
return getattr(sys.modules[mod_str], class_str)
|
null | null | null | Who have the comma and whitespace around them ?
| def test_param_endings():
sig = Script('def x(a, b=5, c=""): pass\n x(').call_signatures()[0]
assert ([p.description for p in sig.params] == ['a', 'b=5', 'c=""'])
| null | null | null | they
| codeqa | def test param endings sig Script 'defx a b 5 c "" pass\nx ' call signatures [0 ]assert [p description for p in sig params] ['a' 'b 5' 'c ""']
| null | null | null | null | Question:
Who have the comma and whitespace around them ?
Code:
def test_param_endings():
sig = Script('def x(a, b=5, c=""): pass\n x(').call_signatures()[0]
assert ([p.description for p in sig.params] == ['a', 'b=5', 'c=""'])
|
null | null | null | Where do they have the comma and whitespace ?
| def test_param_endings():
sig = Script('def x(a, b=5, c=""): pass\n x(').call_signatures()[0]
assert ([p.description for p in sig.params] == ['a', 'b=5', 'c=""'])
| null | null | null | around them
| codeqa | def test param endings sig Script 'defx a b 5 c "" pass\nx ' call signatures [0 ]assert [p description for p in sig params] ['a' 'b 5' 'c ""']
| null | null | null | null | Question:
Where do they have the comma and whitespace ?
Code:
def test_param_endings():
sig = Script('def x(a, b=5, c=""): pass\n x(').call_signatures()[0]
assert ([p.description for p in sig.params] == ['a', 'b=5', 'c=""'])
|
null | null | null | What is containing the filenames for a complete set of profile images ?
| def get_profile_image_names(username):
name = _make_profile_image_name(username)
return {size: _get_profile_image_filename(name, size) for size in _PROFILE_IMAGE_SIZES}
| null | null | null | a dict
| codeqa | def get profile image names username name make profile image name username return {size get profile image filename name size for size in PROFILE IMAGE SIZES}
| null | null | null | null | Question:
What is containing the filenames for a complete set of profile images ?
Code:
def get_profile_image_names(username):
name = _make_profile_image_name(username)
return {size: _get_profile_image_filename(name, size) for size in _PROFILE_IMAGE_SIZES}
|
null | null | null | How do for special characters escape ?
| def yaml_squote(text):
with io.StringIO() as ostream:
yemitter = yaml.emitter.Emitter(ostream, width=six.MAXSIZE)
yemitter.write_single_quoted(six.text_type(text))
return ostream.getvalue()
| null | null | null | correct
| codeqa | def yaml squote text with io String IO as ostream yemitter yaml emitter Emitter ostream width six MAXSIZE yemitter write single quoted six text type text return ostream getvalue
| null | null | null | null | Question:
How do for special characters escape ?
Code:
def yaml_squote(text):
with io.StringIO() as ostream:
yemitter = yaml.emitter.Emitter(ostream, width=six.MAXSIZE)
yemitter.write_single_quoted(six.text_type(text))
return ostream.getvalue()
|
null | null | null | How do an image crop ?
| def crop(x, wrg, hrg, is_random=False, row_index=0, col_index=1, channel_index=2):
(h, w) = (x.shape[row_index], x.shape[col_index])
assert ((h > hrg) and (w > wrg)), 'The size of cropping should smaller than the original image'
if is_random:
h_offset = int((np.random.uniform(0, (h - hrg)) - 1))
w_offset = int((np.random.uniform(0, (w - wrg)) - 1))
return x[h_offset:(hrg + h_offset), w_offset:(wrg + w_offset)]
else:
h_offset = int(np.floor(((h - hrg) / 2.0)))
w_offset = int(np.floor(((w - wrg) / 2.0)))
h_end = (h_offset + hrg)
w_end = (w_offset + wrg)
return x[h_offset:h_end, w_offset:w_end]
| null | null | null | randomly or centrally
| codeqa | def crop x wrg hrg is random False row index 0 col index 1 channel index 2 h w x shape[row index] x shape[col index] assert h > hrg and w > wrg ' Thesizeofcroppingshouldsmallerthantheoriginalimage'if is random h offset int np random uniform 0 h - hrg - 1 w offset int np random uniform 0 w - wrg - 1 return x[h offset hrg + h offset w offset wrg + w offset ]else h offset int np floor h - hrg / 2 0 w offset int np floor w - wrg / 2 0 h end h offset + hrg w end w offset + wrg return x[h offset h end w offset w end]
| null | null | null | null | Question:
How do an image crop ?
Code:
def crop(x, wrg, hrg, is_random=False, row_index=0, col_index=1, channel_index=2):
(h, w) = (x.shape[row_index], x.shape[col_index])
assert ((h > hrg) and (w > wrg)), 'The size of cropping should smaller than the original image'
if is_random:
h_offset = int((np.random.uniform(0, (h - hrg)) - 1))
w_offset = int((np.random.uniform(0, (w - wrg)) - 1))
return x[h_offset:(hrg + h_offset), w_offset:(wrg + w_offset)]
else:
h_offset = int(np.floor(((h - hrg) / 2.0)))
w_offset = int(np.floor(((w - wrg) / 2.0)))
h_end = (h_offset + hrg)
w_end = (w_offset + wrg)
return x[h_offset:h_end, w_offset:w_end]
|
null | null | null | How does the code create a message digest ?
| def pkcs1Digest(data, messageLength):
digest = sha1(data).digest()
return pkcs1Pad((ID_SHA1 + digest), messageLength)
| null | null | null | using the sha1 hash algorithm
| codeqa | def pkcs 1 Digest data message Length digest sha 1 data digest return pkcs 1 Pad ID SHA 1 + digest message Length
| null | null | null | null | Question:
How does the code create a message digest ?
Code:
def pkcs1Digest(data, messageLength):
digest = sha1(data).digest()
return pkcs1Pad((ID_SHA1 + digest), messageLength)
|
null | null | null | What does the code create using the sha1 hash algorithm using the sha1 hash algorithm ?
| def pkcs1Digest(data, messageLength):
digest = sha1(data).digest()
return pkcs1Pad((ID_SHA1 + digest), messageLength)
| null | null | null | a message digest
| codeqa | def pkcs 1 Digest data message Length digest sha 1 data digest return pkcs 1 Pad ID SHA 1 + digest message Length
| null | null | null | null | Question:
What does the code create using the sha1 hash algorithm using the sha1 hash algorithm ?
Code:
def pkcs1Digest(data, messageLength):
digest = sha1(data).digest()
return pkcs1Pad((ID_SHA1 + digest), messageLength)
|
null | null | null | What is turning a function into a task webhook ?
| def task_webhook(fun):
@wraps(fun)
def _inner(*args, **kwargs):
try:
retval = fun(*args, **kwargs)
except Exception as exc:
response = {'status': 'failure', 'reason': safe_repr(exc)}
else:
response = {'status': 'success', 'retval': retval}
return JsonResponse(response)
return _inner
| null | null | null | decorator
| codeqa | def task webhook fun @wraps fun def inner *args **kwargs try retval fun *args **kwargs except Exception as exc response {'status' 'failure' 'reason' safe repr exc }else response {'status' 'success' 'retval' retval}return Json Response response return inner
| null | null | null | null | Question:
What is turning a function into a task webhook ?
Code:
def task_webhook(fun):
@wraps(fun)
def _inner(*args, **kwargs):
try:
retval = fun(*args, **kwargs)
except Exception as exc:
response = {'status': 'failure', 'reason': safe_repr(exc)}
else:
response = {'status': 'success', 'retval': retval}
return JsonResponse(response)
return _inner
|
null | null | null | What do decorator turn into a task webhook ?
| def task_webhook(fun):
@wraps(fun)
def _inner(*args, **kwargs):
try:
retval = fun(*args, **kwargs)
except Exception as exc:
response = {'status': 'failure', 'reason': safe_repr(exc)}
else:
response = {'status': 'success', 'retval': retval}
return JsonResponse(response)
return _inner
| null | null | null | a function
| codeqa | def task webhook fun @wraps fun def inner *args **kwargs try retval fun *args **kwargs except Exception as exc response {'status' 'failure' 'reason' safe repr exc }else response {'status' 'success' 'retval' retval}return Json Response response return inner
| null | null | null | null | Question:
What do decorator turn into a task webhook ?
Code:
def task_webhook(fun):
@wraps(fun)
def _inner(*args, **kwargs):
try:
retval = fun(*args, **kwargs)
except Exception as exc:
response = {'status': 'failure', 'reason': safe_repr(exc)}
else:
response = {'status': 'success', 'retval': retval}
return JsonResponse(response)
return _inner
|
null | null | null | What generates oriented forests ?
| def generate_oriented_forest(n):
P = list(range((-1), n))
while True:
(yield P[1:])
if (P[n] > 0):
P[n] = P[P[n]]
else:
for p in range((n - 1), 0, (-1)):
if (P[p] != 0):
target = (P[p] - 1)
for q in range((p - 1), 0, (-1)):
if (P[q] == target):
break
offset = (p - q)
for i in range(p, (n + 1)):
P[i] = P[(i - offset)]
break
else:
break
| null | null | null | this algorithm
| codeqa | def generate oriented forest n P list range -1 n while True yield P[ 1 ] if P[n] > 0 P[n] P[P[n]]else for p in range n - 1 0 -1 if P[p] 0 target P[p] - 1 for q in range p - 1 0 -1 if P[q] target breakoffset p - q for i in range p n + 1 P[i] P[ i - offset ]breakelse break
| null | null | null | null | Question:
What generates oriented forests ?
Code:
def generate_oriented_forest(n):
P = list(range((-1), n))
while True:
(yield P[1:])
if (P[n] > 0):
P[n] = P[P[n]]
else:
for p in range((n - 1), 0, (-1)):
if (P[p] != 0):
target = (P[p] - 1)
for q in range((p - 1), 0, (-1)):
if (P[q] == target):
break
offset = (p - q)
for i in range(p, (n + 1)):
P[i] = P[(i - offset)]
break
else:
break
|
null | null | null | What does this algorithm generate ?
| def generate_oriented_forest(n):
P = list(range((-1), n))
while True:
(yield P[1:])
if (P[n] > 0):
P[n] = P[P[n]]
else:
for p in range((n - 1), 0, (-1)):
if (P[p] != 0):
target = (P[p] - 1)
for q in range((p - 1), 0, (-1)):
if (P[q] == target):
break
offset = (p - q)
for i in range(p, (n + 1)):
P[i] = P[(i - offset)]
break
else:
break
| null | null | null | oriented forests
| codeqa | def generate oriented forest n P list range -1 n while True yield P[ 1 ] if P[n] > 0 P[n] P[P[n]]else for p in range n - 1 0 -1 if P[p] 0 target P[p] - 1 for q in range p - 1 0 -1 if P[q] target breakoffset p - q for i in range p n + 1 P[i] P[ i - offset ]breakelse break
| null | null | null | null | Question:
What does this algorithm generate ?
Code:
def generate_oriented_forest(n):
P = list(range((-1), n))
while True:
(yield P[1:])
if (P[n] > 0):
P[n] = P[P[n]]
else:
for p in range((n - 1), 0, (-1)):
if (P[p] != 0):
target = (P[p] - 1)
for q in range((p - 1), 0, (-1)):
if (P[q] == target):
break
offset = (p - q)
for i in range(p, (n + 1)):
P[i] = P[(i - offset)]
break
else:
break
|
null | null | null | What did function use ?
| def getdtype(dtype, a=None, default=None):
if (dtype is None):
try:
newdtype = a.dtype
except AttributeError:
if (default is not None):
newdtype = np.dtype(default)
else:
raise TypeError('could not interpret data type')
else:
newdtype = np.dtype(dtype)
if (newdtype == np.object_):
warnings.warn('object dtype is not supported by sparse matrices')
return newdtype
| null | null | null | to simplify argument processing
| codeqa | def getdtype dtype a None default None if dtype is None try newdtype a dtypeexcept Attribute Error if default is not None newdtype np dtype default else raise Type Error 'couldnotinterpretdatatype' else newdtype np dtype dtype if newdtype np object warnings warn 'objectdtypeisnotsupportedbysparsematrices' return newdtype
| null | null | null | null | Question:
What did function use ?
Code:
def getdtype(dtype, a=None, default=None):
if (dtype is None):
try:
newdtype = a.dtype
except AttributeError:
if (default is not None):
newdtype = np.dtype(default)
else:
raise TypeError('could not interpret data type')
else:
newdtype = np.dtype(dtype)
if (newdtype == np.object_):
warnings.warn('object dtype is not supported by sparse matrices')
return newdtype
|
null | null | null | What used to simplify argument processing ?
| def getdtype(dtype, a=None, default=None):
if (dtype is None):
try:
newdtype = a.dtype
except AttributeError:
if (default is not None):
newdtype = np.dtype(default)
else:
raise TypeError('could not interpret data type')
else:
newdtype = np.dtype(dtype)
if (newdtype == np.object_):
warnings.warn('object dtype is not supported by sparse matrices')
return newdtype
| null | null | null | function
| codeqa | def getdtype dtype a None default None if dtype is None try newdtype a dtypeexcept Attribute Error if default is not None newdtype np dtype default else raise Type Error 'couldnotinterpretdatatype' else newdtype np dtype dtype if newdtype np object warnings warn 'objectdtypeisnotsupportedbysparsematrices' return newdtype
| null | null | null | null | Question:
What used to simplify argument processing ?
Code:
def getdtype(dtype, a=None, default=None):
if (dtype is None):
try:
newdtype = a.dtype
except AttributeError:
if (default is not None):
newdtype = np.dtype(default)
else:
raise TypeError('could not interpret data type')
else:
newdtype = np.dtype(dtype)
if (newdtype == np.object_):
warnings.warn('object dtype is not supported by sparse matrices')
return newdtype
|
null | null | null | How do authentication not require ?
| def isunauthenticated(f):
return getattr(f, 'unauthenticated', False)
| null | null | null | with the @unauthenticated decorator
| codeqa | def isunauthenticated f return getattr f 'unauthenticated' False
| null | null | null | null | Question:
How do authentication not require ?
Code:
def isunauthenticated(f):
return getattr(f, 'unauthenticated', False)
|
null | null | null | What does returns model class connect ?
| def get_group_obj_perms_model(obj):
from guardian.models import GroupObjectPermissionBase
from guardian.models import GroupObjectPermission
return get_obj_perms_model(obj, GroupObjectPermissionBase, GroupObjectPermission)
| null | null | null | given obj and group class
| codeqa | def get group obj perms model obj from guardian models import Group Object Permission Basefrom guardian models import Group Object Permissionreturn get obj perms model obj Group Object Permission Base Group Object Permission
| null | null | null | null | Question:
What does returns model class connect ?
Code:
def get_group_obj_perms_model(obj):
from guardian.models import GroupObjectPermissionBase
from guardian.models import GroupObjectPermission
return get_obj_perms_model(obj, GroupObjectPermissionBase, GroupObjectPermission)
|
null | null | null | What connects given obj and group class ?
| def get_group_obj_perms_model(obj):
from guardian.models import GroupObjectPermissionBase
from guardian.models import GroupObjectPermission
return get_obj_perms_model(obj, GroupObjectPermissionBase, GroupObjectPermission)
| null | null | null | returns model class
| codeqa | def get group obj perms model obj from guardian models import Group Object Permission Basefrom guardian models import Group Object Permissionreturn get obj perms model obj Group Object Permission Base Group Object Permission
| null | null | null | null | Question:
What connects given obj and group class ?
Code:
def get_group_obj_perms_model(obj):
from guardian.models import GroupObjectPermissionBase
from guardian.models import GroupObjectPermission
return get_obj_perms_model(obj, GroupObjectPermissionBase, GroupObjectPermission)
|
null | null | null | What did the code instruct the agent ?
| def agent_leave(consul_url=None, node=None):
ret = {}
query_params = {}
if (not consul_url):
consul_url = _get_config()
if (not consul_url):
log.error('No Consul URL found.')
ret['message'] = 'No Consul URL found.'
ret['res'] = False
return ret
if (not node):
raise SaltInvocationError('Required argument "node" is missing.')
function = 'agent/force-leave/{0}'.format(node)
res = _query(consul_url=consul_url, function=function, method='GET', query_params=query_params)
if res['res']:
ret['res'] = True
ret['message'] = 'Node {0} put in leave state.'.format(node)
else:
ret['res'] = False
ret['message'] = 'Unable to change state for {0}.'.format(node)
return ret
| null | null | null | to force a node into the left state
| codeqa | def agent leave consul url None node None ret {}query params {}if not consul url consul url get config if not consul url log error ' No Consul UR Lfound ' ret['message'] ' No Consul UR Lfound 'ret['res'] Falsereturn retif not node raise Salt Invocation Error ' Requiredargument"node"ismissing ' function 'agent/force-leave/{ 0 }' format node res query consul url consul url function function method 'GET' query params query params if res['res'] ret['res'] Trueret['message'] ' Node{ 0 }putinleavestate ' format node else ret['res'] Falseret['message'] ' Unabletochangestatefor{ 0 } ' format node return ret
| null | null | null | null | Question:
What did the code instruct the agent ?
Code:
def agent_leave(consul_url=None, node=None):
ret = {}
query_params = {}
if (not consul_url):
consul_url = _get_config()
if (not consul_url):
log.error('No Consul URL found.')
ret['message'] = 'No Consul URL found.'
ret['res'] = False
return ret
if (not node):
raise SaltInvocationError('Required argument "node" is missing.')
function = 'agent/force-leave/{0}'.format(node)
res = _query(consul_url=consul_url, function=function, method='GET', query_params=query_params)
if res['res']:
ret['res'] = True
ret['message'] = 'Node {0} put in leave state.'.format(node)
else:
ret['res'] = False
ret['message'] = 'Unable to change state for {0}.'.format(node)
return ret
|
null | null | null | What did the code use ?
| def agent_leave(consul_url=None, node=None):
ret = {}
query_params = {}
if (not consul_url):
consul_url = _get_config()
if (not consul_url):
log.error('No Consul URL found.')
ret['message'] = 'No Consul URL found.'
ret['res'] = False
return ret
if (not node):
raise SaltInvocationError('Required argument "node" is missing.')
function = 'agent/force-leave/{0}'.format(node)
res = _query(consul_url=consul_url, function=function, method='GET', query_params=query_params)
if res['res']:
ret['res'] = True
ret['message'] = 'Node {0} put in leave state.'.format(node)
else:
ret['res'] = False
ret['message'] = 'Unable to change state for {0}.'.format(node)
return ret
| null | null | null | to instruct the agent to force a node into the left state
| codeqa | def agent leave consul url None node None ret {}query params {}if not consul url consul url get config if not consul url log error ' No Consul UR Lfound ' ret['message'] ' No Consul UR Lfound 'ret['res'] Falsereturn retif not node raise Salt Invocation Error ' Requiredargument"node"ismissing ' function 'agent/force-leave/{ 0 }' format node res query consul url consul url function function method 'GET' query params query params if res['res'] ret['res'] Trueret['message'] ' Node{ 0 }putinleavestate ' format node else ret['res'] Falseret['message'] ' Unabletochangestatefor{ 0 } ' format node return ret
| null | null | null | null | Question:
What did the code use ?
Code:
def agent_leave(consul_url=None, node=None):
ret = {}
query_params = {}
if (not consul_url):
consul_url = _get_config()
if (not consul_url):
log.error('No Consul URL found.')
ret['message'] = 'No Consul URL found.'
ret['res'] = False
return ret
if (not node):
raise SaltInvocationError('Required argument "node" is missing.')
function = 'agent/force-leave/{0}'.format(node)
res = _query(consul_url=consul_url, function=function, method='GET', query_params=query_params)
if res['res']:
ret['res'] = True
ret['message'] = 'Node {0} put in leave state.'.format(node)
else:
ret['res'] = False
ret['message'] = 'Unable to change state for {0}.'.format(node)
return ret
|
null | null | null | What do the agent force into the left state ?
| def agent_leave(consul_url=None, node=None):
ret = {}
query_params = {}
if (not consul_url):
consul_url = _get_config()
if (not consul_url):
log.error('No Consul URL found.')
ret['message'] = 'No Consul URL found.'
ret['res'] = False
return ret
if (not node):
raise SaltInvocationError('Required argument "node" is missing.')
function = 'agent/force-leave/{0}'.format(node)
res = _query(consul_url=consul_url, function=function, method='GET', query_params=query_params)
if res['res']:
ret['res'] = True
ret['message'] = 'Node {0} put in leave state.'.format(node)
else:
ret['res'] = False
ret['message'] = 'Unable to change state for {0}.'.format(node)
return ret
| null | null | null | a node
| codeqa | def agent leave consul url None node None ret {}query params {}if not consul url consul url get config if not consul url log error ' No Consul UR Lfound ' ret['message'] ' No Consul UR Lfound 'ret['res'] Falsereturn retif not node raise Salt Invocation Error ' Requiredargument"node"ismissing ' function 'agent/force-leave/{ 0 }' format node res query consul url consul url function function method 'GET' query params query params if res['res'] ret['res'] Trueret['message'] ' Node{ 0 }putinleavestate ' format node else ret['res'] Falseret['message'] ' Unabletochangestatefor{ 0 } ' format node return ret
| null | null | null | null | Question:
What do the agent force into the left state ?
Code:
def agent_leave(consul_url=None, node=None):
ret = {}
query_params = {}
if (not consul_url):
consul_url = _get_config()
if (not consul_url):
log.error('No Consul URL found.')
ret['message'] = 'No Consul URL found.'
ret['res'] = False
return ret
if (not node):
raise SaltInvocationError('Required argument "node" is missing.')
function = 'agent/force-leave/{0}'.format(node)
res = _query(consul_url=consul_url, function=function, method='GET', query_params=query_params)
if res['res']:
ret['res'] = True
ret['message'] = 'Node {0} put in leave state.'.format(node)
else:
ret['res'] = False
ret['message'] = 'Unable to change state for {0}.'.format(node)
return ret
|
null | null | null | What did the code instruct to force a node into the left state ?
| def agent_leave(consul_url=None, node=None):
ret = {}
query_params = {}
if (not consul_url):
consul_url = _get_config()
if (not consul_url):
log.error('No Consul URL found.')
ret['message'] = 'No Consul URL found.'
ret['res'] = False
return ret
if (not node):
raise SaltInvocationError('Required argument "node" is missing.')
function = 'agent/force-leave/{0}'.format(node)
res = _query(consul_url=consul_url, function=function, method='GET', query_params=query_params)
if res['res']:
ret['res'] = True
ret['message'] = 'Node {0} put in leave state.'.format(node)
else:
ret['res'] = False
ret['message'] = 'Unable to change state for {0}.'.format(node)
return ret
| null | null | null | the agent
| codeqa | def agent leave consul url None node None ret {}query params {}if not consul url consul url get config if not consul url log error ' No Consul UR Lfound ' ret['message'] ' No Consul UR Lfound 'ret['res'] Falsereturn retif not node raise Salt Invocation Error ' Requiredargument"node"ismissing ' function 'agent/force-leave/{ 0 }' format node res query consul url consul url function function method 'GET' query params query params if res['res'] ret['res'] Trueret['message'] ' Node{ 0 }putinleavestate ' format node else ret['res'] Falseret['message'] ' Unabletochangestatefor{ 0 } ' format node return ret
| null | null | null | null | Question:
What did the code instruct to force a node into the left state ?
Code:
def agent_leave(consul_url=None, node=None):
ret = {}
query_params = {}
if (not consul_url):
consul_url = _get_config()
if (not consul_url):
log.error('No Consul URL found.')
ret['message'] = 'No Consul URL found.'
ret['res'] = False
return ret
if (not node):
raise SaltInvocationError('Required argument "node" is missing.')
function = 'agent/force-leave/{0}'.format(node)
res = _query(consul_url=consul_url, function=function, method='GET', query_params=query_params)
if res['res']:
ret['res'] = True
ret['message'] = 'Node {0} put in leave state.'.format(node)
else:
ret['res'] = False
ret['message'] = 'Unable to change state for {0}.'.format(node)
return ret
|
null | null | null | What forces a node into the left state ?
| def agent_leave(consul_url=None, node=None):
ret = {}
query_params = {}
if (not consul_url):
consul_url = _get_config()
if (not consul_url):
log.error('No Consul URL found.')
ret['message'] = 'No Consul URL found.'
ret['res'] = False
return ret
if (not node):
raise SaltInvocationError('Required argument "node" is missing.')
function = 'agent/force-leave/{0}'.format(node)
res = _query(consul_url=consul_url, function=function, method='GET', query_params=query_params)
if res['res']:
ret['res'] = True
ret['message'] = 'Node {0} put in leave state.'.format(node)
else:
ret['res'] = False
ret['message'] = 'Unable to change state for {0}.'.format(node)
return ret
| null | null | null | the agent
| codeqa | def agent leave consul url None node None ret {}query params {}if not consul url consul url get config if not consul url log error ' No Consul UR Lfound ' ret['message'] ' No Consul UR Lfound 'ret['res'] Falsereturn retif not node raise Salt Invocation Error ' Requiredargument"node"ismissing ' function 'agent/force-leave/{ 0 }' format node res query consul url consul url function function method 'GET' query params query params if res['res'] ret['res'] Trueret['message'] ' Node{ 0 }putinleavestate ' format node else ret['res'] Falseret['message'] ' Unabletochangestatefor{ 0 } ' format node return ret
| null | null | null | null | Question:
What forces a node into the left state ?
Code:
def agent_leave(consul_url=None, node=None):
ret = {}
query_params = {}
if (not consul_url):
consul_url = _get_config()
if (not consul_url):
log.error('No Consul URL found.')
ret['message'] = 'No Consul URL found.'
ret['res'] = False
return ret
if (not node):
raise SaltInvocationError('Required argument "node" is missing.')
function = 'agent/force-leave/{0}'.format(node)
res = _query(consul_url=consul_url, function=function, method='GET', query_params=query_params)
if res['res']:
ret['res'] = True
ret['message'] = 'Node {0} put in leave state.'.format(node)
else:
ret['res'] = False
ret['message'] = 'Unable to change state for {0}.'.format(node)
return ret
|
null | null | null | Where does random integer value return ?
| def randomRange(start=0, stop=1000, seed=None):
if (seed is not None):
_ = getCurrentThreadData().random
_.seed(seed)
randint = _.randint
else:
randint = random.randint
return int(randint(start, stop))
| null | null | null | in given range
| codeqa | def random Range start 0 stop 1000 seed None if seed is not None get Current Thread Data random seed seed randint randintelse randint random randintreturn int randint start stop
| null | null | null | null | Question:
Where does random integer value return ?
Code:
def randomRange(start=0, stop=1000, seed=None):
if (seed is not None):
_ = getCurrentThreadData().random
_.seed(seed)
randint = _.randint
else:
randint = random.randint
return int(randint(start, stop))
|
null | null | null | What returns in given range ?
| def randomRange(start=0, stop=1000, seed=None):
if (seed is not None):
_ = getCurrentThreadData().random
_.seed(seed)
randint = _.randint
else:
randint = random.randint
return int(randint(start, stop))
| null | null | null | random integer value
| codeqa | def random Range start 0 stop 1000 seed None if seed is not None get Current Thread Data random seed seed randint randintelse randint random randintreturn int randint start stop
| null | null | null | null | Question:
What returns in given range ?
Code:
def randomRange(start=0, stop=1000, seed=None):
if (seed is not None):
_ = getCurrentThreadData().random
_.seed(seed)
randint = _.randint
else:
randint = random.randint
return int(randint(start, stop))
|
null | null | null | How do t reshape with n_ones 1s ?
| @constructor
def shape_padleft(t, n_ones=1):
_t = as_tensor_variable(t)
pattern = ((['x'] * n_ones) + [i for i in xrange(_t.type.ndim)])
return DimShuffle(_t.broadcastable, pattern)(_t)
| null | null | null | by left - padding the shape
| codeqa | @constructordef shape padleft t n ones 1 t as tensor variable t pattern ['x'] * n ones + [i for i in xrange t type ndim ] return Dim Shuffle t broadcastable pattern t
| null | null | null | null | Question:
How do t reshape with n_ones 1s ?
Code:
@constructor
def shape_padleft(t, n_ones=1):
_t = as_tensor_variable(t)
pattern = ((['x'] * n_ones) + [i for i in xrange(_t.type.ndim)])
return DimShuffle(_t.broadcastable, pattern)(_t)
|
null | null | null | What do t reshape by left - padding the shape ?
| @constructor
def shape_padleft(t, n_ones=1):
_t = as_tensor_variable(t)
pattern = ((['x'] * n_ones) + [i for i in xrange(_t.type.ndim)])
return DimShuffle(_t.broadcastable, pattern)(_t)
| null | null | null | with n_ones 1s
| codeqa | @constructordef shape padleft t n ones 1 t as tensor variable t pattern ['x'] * n ones + [i for i in xrange t type ndim ] return Dim Shuffle t broadcastable pattern t
| null | null | null | null | Question:
What do t reshape by left - padding the shape ?
Code:
@constructor
def shape_padleft(t, n_ones=1):
_t = as_tensor_variable(t)
pattern = ((['x'] * n_ones) + [i for i in xrange(_t.type.ndim)])
return DimShuffle(_t.broadcastable, pattern)(_t)
|
null | null | null | What reshapes with n_ones 1s by left - padding the shape ?
| @constructor
def shape_padleft(t, n_ones=1):
_t = as_tensor_variable(t)
pattern = ((['x'] * n_ones) + [i for i in xrange(_t.type.ndim)])
return DimShuffle(_t.broadcastable, pattern)(_t)
| null | null | null | t
| codeqa | @constructordef shape padleft t n ones 1 t as tensor variable t pattern ['x'] * n ones + [i for i in xrange t type ndim ] return Dim Shuffle t broadcastable pattern t
| null | null | null | null | Question:
What reshapes with n_ones 1s by left - padding the shape ?
Code:
@constructor
def shape_padleft(t, n_ones=1):
_t = as_tensor_variable(t)
pattern = ((['x'] * n_ones) + [i for i in xrange(_t.type.ndim)])
return DimShuffle(_t.broadcastable, pattern)(_t)
|
null | null | null | What did the code read ?
| def jit_graph(data):
G = nx.Graph()
for node in data:
G.add_node(node['id'], **node['data'])
if (node.get('adjacencies') is not None):
for adj in node['adjacencies']:
G.add_edge(node['id'], adj['nodeTo'], **adj['data'])
return G
| null | null | null | a graph
| codeqa | def jit graph data G nx Graph for node in data G add node node['id'] **node['data'] if node get 'adjacencies' is not None for adj in node['adjacencies'] G add edge node['id'] adj['node To'] **adj['data'] return G
| null | null | null | null | Question:
What did the code read ?
Code:
def jit_graph(data):
G = nx.Graph()
for node in data:
G.add_node(node['id'], **node['data'])
if (node.get('adjacencies') is not None):
for adj in node['adjacencies']:
G.add_edge(node['id'], adj['nodeTo'], **adj['data'])
return G
|
null | null | null | What did the code use ?
| def deprecated(msg=None, stacklevel=2):
def deprecated_dec(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
warnings.warn((msg or ('Function %s is deprecated.' % fn.__name__)), category=DeprecationWarning, stacklevel=stacklevel)
return fn(*args, **kwargs)
return wrapper
return deprecated_dec
| null | null | null | to mark a function as deprecated
| codeqa | def deprecated msg None stacklevel 2 def deprecated dec fn @wraps fn def wrapper *args **kwargs warnings warn msg or ' Function%sisdeprecated ' % fn name category Deprecation Warning stacklevel stacklevel return fn *args **kwargs return wrapperreturn deprecated dec
| null | null | null | null | Question:
What did the code use ?
Code:
def deprecated(msg=None, stacklevel=2):
def deprecated_dec(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
warnings.warn((msg or ('Function %s is deprecated.' % fn.__name__)), category=DeprecationWarning, stacklevel=stacklevel)
return fn(*args, **kwargs)
return wrapper
return deprecated_dec
|
null | null | null | What be overwritten in the according tests ?
| @pytest.fixture
def make_fake_project_dir(request):
os.makedirs('fake-project')
| null | null | null | a fake project
| codeqa | @pytest fixturedef make fake project dir request os makedirs 'fake-project'
| null | null | null | null | Question:
What be overwritten in the according tests ?
Code:
@pytest.fixture
def make_fake_project_dir(request):
os.makedirs('fake-project')
|
null | null | null | What does the code create ?
| @pytest.fixture
def make_fake_project_dir(request):
os.makedirs('fake-project')
| null | null | null | a fake project to be overwritten in the according tests
| codeqa | @pytest fixturedef make fake project dir request os makedirs 'fake-project'
| null | null | null | null | Question:
What does the code create ?
Code:
@pytest.fixture
def make_fake_project_dir(request):
os.makedirs('fake-project')
|
null | null | null | Where be a fake project overwritten ?
| @pytest.fixture
def make_fake_project_dir(request):
os.makedirs('fake-project')
| null | null | null | in the according tests
| codeqa | @pytest fixturedef make fake project dir request os makedirs 'fake-project'
| null | null | null | null | Question:
Where be a fake project overwritten ?
Code:
@pytest.fixture
def make_fake_project_dir(request):
os.makedirs('fake-project')
|
null | null | null | What does the code delete ?
| def delete_folder(folder):
if os.path.exists(folder):
try:
shutil.rmtree(folder)
except OSError:
raise CuckooOperationalError('Unable to delete folder: {0}'.format(folder))
| null | null | null | a folder and all its subdirectories
| codeqa | def delete folder folder if os path exists folder try shutil rmtree folder except OS Error raise Cuckoo Operational Error ' Unabletodeletefolder {0 }' format folder
| null | null | null | null | Question:
What does the code delete ?
Code:
def delete_folder(folder):
if os.path.exists(folder):
try:
shutil.rmtree(folder)
except OSError:
raise CuckooOperationalError('Unable to delete folder: {0}'.format(folder))
|
null | null | null | What does the code require ?
| def server(package_name='nginx'):
family = distrib_family()
if (family == 'debian'):
_server_debian(package_name)
else:
raise UnsupportedFamily(supported=['debian'])
| null | null | null | the nginx web server to be installed and running
| codeqa | def server package name 'nginx' family distrib family if family 'debian' server debian package name else raise Unsupported Family supported ['debian']
| null | null | null | null | Question:
What does the code require ?
Code:
def server(package_name='nginx'):
family = distrib_family()
if (family == 'debian'):
_server_debian(package_name)
else:
raise UnsupportedFamily(supported=['debian'])
|
null | null | null | What does the code do ?
| def indentXML(elem, level=0):
i = (u'\n' + (level * u' '))
if len(elem):
if ((not elem.text) or (not elem.text.strip())):
elem.text = (i + u' ')
if ((not elem.tail) or (not elem.tail.strip())):
elem.tail = i
for elem in elem:
indentXML(elem, (level + 1))
if ((not elem.tail) or (not elem.tail.strip())):
elem.tail = i
elif (level and ((not elem.tail) or (not elem.tail.strip()))):
elem.tail = i
| null | null | null | our pretty printing
| codeqa | def indent XML elem level 0 i u'\n' + level * u'' if len elem if not elem text or not elem text strip elem text i + u'' if not elem tail or not elem tail strip elem tail ifor elem in elem indent XML elem level + 1 if not elem tail or not elem tail strip elem tail ielif level and not elem tail or not elem tail strip elem tail i
| null | null | null | null | Question:
What does the code do ?
Code:
def indentXML(elem, level=0):
i = (u'\n' + (level * u' '))
if len(elem):
if ((not elem.text) or (not elem.text.strip())):
elem.text = (i + u' ')
if ((not elem.tail) or (not elem.tail.strip())):
elem.tail = i
for elem in elem:
indentXML(elem, (level + 1))
if ((not elem.tail) or (not elem.tail.strip())):
elem.tail = i
elif (level and ((not elem.tail) or (not elem.tail.strip()))):
elem.tail = i
|
null | null | null | How do commands run ?
| def run_parallel(commands, timeout=None, ignore_status=False, stdout_tee=None, stderr_tee=None):
bg_jobs = []
for command in commands:
bg_jobs.append(BgJob(command, stdout_tee, stderr_tee, stderr_level=get_stderr_level(ignore_status)))
join_bg_jobs(bg_jobs, timeout)
for bg_job in bg_jobs:
if ((not ignore_status) and bg_job.result.exit_status):
raise error.CmdError(command, bg_job.result, 'Command returned non-zero exit status')
return [bg_job.result for bg_job in bg_jobs]
| null | null | null | in parallel
| codeqa | def run parallel commands timeout None ignore status False stdout tee None stderr tee None bg jobs []for command in commands bg jobs append Bg Job command stdout tee stderr tee stderr level get stderr level ignore status join bg jobs bg jobs timeout for bg job in bg jobs if not ignore status and bg job result exit status raise error Cmd Error command bg job result ' Commandreturnednon-zeroexitstatus' return [bg job result for bg job in bg jobs]
| null | null | null | null | Question:
How do commands run ?
Code:
def run_parallel(commands, timeout=None, ignore_status=False, stdout_tee=None, stderr_tee=None):
bg_jobs = []
for command in commands:
bg_jobs.append(BgJob(command, stdout_tee, stderr_tee, stderr_level=get_stderr_level(ignore_status)))
join_bg_jobs(bg_jobs, timeout)
for bg_job in bg_jobs:
if ((not ignore_status) and bg_job.result.exit_status):
raise error.CmdError(command, bg_job.result, 'Command returned non-zero exit status')
return [bg_job.result for bg_job in bg_jobs]
|
null | null | null | What does the code run ?
| @snippet
def client_run_sync_query(client, _):
LIMIT = 100
LIMITED = ('%s LIMIT %d' % (QUERY, LIMIT))
TIMEOUT_MS = 1000
query = client.run_sync_query(LIMITED)
query.timeout_ms = TIMEOUT_MS
query.run()
assert query.complete
assert (len(query.rows) == LIMIT)
assert ([field.name for field in query.schema] == ['name'])
| null | null | null | a synchronous query
| codeqa | @snippetdef client run sync query client LIMIT 100 LIMITED '%s LIMIT%d' % QUERY LIMIT TIMEOUT MS 1000 query client run sync query LIMITED query timeout ms TIMEOUT M Squery run assert query completeassert len query rows LIMIT assert [field name for field in query schema] ['name']
| null | null | null | null | Question:
What does the code run ?
Code:
@snippet
def client_run_sync_query(client, _):
LIMIT = 100
LIMITED = ('%s LIMIT %d' % (QUERY, LIMIT))
TIMEOUT_MS = 1000
query = client.run_sync_query(LIMITED)
query.timeout_ms = TIMEOUT_MS
query.run()
assert query.complete
assert (len(query.rows) == LIMIT)
assert ([field.name for field in query.schema] == ['name'])
|
null | null | null | When does the linear interpolation between a and b return ?
| def lerp(a, b, t):
if (t < 0.0):
return a
if (t > 1.0):
return b
return (a + ((b - a) * t))
| null | null | null | at time t between 0
| codeqa | def lerp a b t if t < 0 0 return aif t > 1 0 return breturn a + b - a * t
| null | null | null | null | Question:
When does the linear interpolation between a and b return ?
Code:
def lerp(a, b, t):
if (t < 0.0):
return a
if (t > 1.0):
return b
return (a + ((b - a) * t))
|
null | null | null | When is the interpreter shutting ?
| def shutting_down(globals=globals):
v = globals().get('_shutting_down')
return ((v is True) or (v is None))
| null | null | null | currently
| codeqa | def shutting down globals globals v globals get ' shutting down' return v is True or v is None
| null | null | null | null | Question:
When is the interpreter shutting ?
Code:
def shutting_down(globals=globals):
v = globals().get('_shutting_down')
return ((v is True) or (v is None))
|
null | null | null | What does this provide ?
| def get_health(**kwargs):
with _IpmiCommand(**kwargs) as s:
return s.get_health()
| null | null | null | a summary of the health of the managed system
| codeqa | def get health **kwargs with Ipmi Command **kwargs as s return s get health
| null | null | null | null | Question:
What does this provide ?
Code:
def get_health(**kwargs):
with _IpmiCommand(**kwargs) as s:
return s.get_health()
|
null | null | null | What provides a summary of the health of the managed system ?
| def get_health(**kwargs):
with _IpmiCommand(**kwargs) as s:
return s.get_health()
| null | null | null | this
| codeqa | def get health **kwargs with Ipmi Command **kwargs as s return s get health
| null | null | null | null | Question:
What provides a summary of the health of the managed system ?
Code:
def get_health(**kwargs):
with _IpmiCommand(**kwargs) as s:
return s.get_health()
|
null | null | null | What does the code return ?
| def _get_candidate_pos(version):
return [i for (i, part) in enumerate(version) if (part in CANDIDATE_MARKERS)][0]
| null | null | null | the position of the candidate marker
| codeqa | def get candidate pos version return [i for i part in enumerate version if part in CANDIDATE MARKERS ][ 0 ]
| null | null | null | null | Question:
What does the code return ?
Code:
def _get_candidate_pos(version):
return [i for (i, part) in enumerate(version) if (part in CANDIDATE_MARKERS)][0]
|
null | null | null | What did both logins and method calls shut ?
| def finished(ignored):
reactor.stop()
| null | null | null | the reactor
| codeqa | def finished ignored reactor stop
| null | null | null | null | Question:
What did both logins and method calls shut ?
Code:
def finished(ignored):
reactor.stop()
|
null | null | null | What shuts the reactor ?
| def finished(ignored):
reactor.stop()
| null | null | null | both logins and method calls
| codeqa | def finished ignored reactor stop
| null | null | null | null | Question:
What shuts the reactor ?
Code:
def finished(ignored):
reactor.stop()
|
null | null | null | For what purpose have both logins and method calls finished when ?
| def finished(ignored):
reactor.stop()
| null | null | null | to shut down the reactor
| codeqa | def finished ignored reactor stop
| null | null | null | null | Question:
For what purpose have both logins and method calls finished when ?
Code:
def finished(ignored):
reactor.stop()
|
null | null | null | What does the code create ?
| def create_record(name, zone_id, type, data, profile):
conn = _get_driver(profile=profile)
record_type = _string_to_record_type(type)
zone = conn.get_zone(zone_id)
return conn.create_record(name, zone, record_type, data)
| null | null | null | a new record
| codeqa | def create record name zone id type data profile conn get driver profile profile record type string to record type type zone conn get zone zone id return conn create record name zone record type data
| null | null | null | null | Question:
What does the code create ?
Code:
def create_record(name, zone_id, type, data, profile):
conn = _get_driver(profile=profile)
record_type = _string_to_record_type(type)
zone = conn.get_zone(zone_id)
return conn.create_record(name, zone, record_type, data)
|
null | null | null | What does generator read ?
| def _file_reader(fh):
while True:
chunk = fh.read(DOWNLOAD_CHUNK_SIZE)
if (chunk == ''):
fh.close()
break
(yield chunk)
| null | null | null | a file
| codeqa | def file reader fh while True chunk fh read DOWNLOAD CHUNK SIZE if chunk '' fh close break yield chunk
| null | null | null | null | Question:
What does generator read ?
Code:
def _file_reader(fh):
while True:
chunk = fh.read(DOWNLOAD_CHUNK_SIZE)
if (chunk == ''):
fh.close()
break
(yield chunk)
|
null | null | null | What reads a file ?
| def _file_reader(fh):
while True:
chunk = fh.read(DOWNLOAD_CHUNK_SIZE)
if (chunk == ''):
fh.close()
break
(yield chunk)
| null | null | null | generator
| codeqa | def file reader fh while True chunk fh read DOWNLOAD CHUNK SIZE if chunk '' fh close break yield chunk
| null | null | null | null | Question:
What reads a file ?
Code:
def _file_reader(fh):
while True:
chunk = fh.read(DOWNLOAD_CHUNK_SIZE)
if (chunk == ''):
fh.close()
break
(yield chunk)
|
null | null | null | For what purpose are flags passed ?
| def check_dna_chars_primers(header, mapping_data, errors, disable_primer_check=False):
valid_dna_chars = DNASequence.iupac_characters()
valid_dna_chars.add(',')
header_fields_to_check = ['ReversePrimer']
if (not disable_primer_check):
header_fields_to_check.append('LinkerPrimerSequence')
check_indices = []
for curr_field in range(len(header)):
if (header[curr_field] in header_fields_to_check):
check_indices.append(curr_field)
correction_ix = 1
for curr_data in range(len(mapping_data)):
for curr_ix in check_indices:
if (len(mapping_data[curr_data][curr_ix]) == 0):
errors.append(('Missing expected DNA sequence DCTB %d,%d' % ((curr_data + correction_ix), curr_ix)))
for curr_data in range(len(mapping_data)):
for curr_ix in check_indices:
for curr_nt in mapping_data[curr_data][curr_ix]:
if (curr_nt not in valid_dna_chars):
errors.append(('Invalid DNA sequence detected: %s DCTB %d,%d' % (mapping_data[curr_data][curr_ix], (curr_data + correction_ix), curr_ix)))
continue
return errors
| null | null | null | to suppress barcode or primer checks
| codeqa | def check dna chars primers header mapping data errors disable primer check False valid dna chars DNA Sequence iupac characters valid dna chars add ' ' header fields to check [' Reverse Primer']if not disable primer check header fields to check append ' Linker Primer Sequence' check indices []for curr field in range len header if header[curr field] in header fields to check check indices append curr field correction ix 1for curr data in range len mapping data for curr ix in check indices if len mapping data[curr data][curr ix] 0 errors append ' Missingexpected DN Asequence DCTB %d %d' % curr data + correction ix curr ix for curr data in range len mapping data for curr ix in check indices for curr nt in mapping data[curr data][curr ix] if curr nt not in valid dna chars errors append ' Invalid DN Asequencedetected %s DCTB %d %d' % mapping data[curr data][curr ix] curr data + correction ix curr ix continuereturn errors
| null | null | null | null | Question:
For what purpose are flags passed ?
Code:
def check_dna_chars_primers(header, mapping_data, errors, disable_primer_check=False):
valid_dna_chars = DNASequence.iupac_characters()
valid_dna_chars.add(',')
header_fields_to_check = ['ReversePrimer']
if (not disable_primer_check):
header_fields_to_check.append('LinkerPrimerSequence')
check_indices = []
for curr_field in range(len(header)):
if (header[curr_field] in header_fields_to_check):
check_indices.append(curr_field)
correction_ix = 1
for curr_data in range(len(mapping_data)):
for curr_ix in check_indices:
if (len(mapping_data[curr_data][curr_ix]) == 0):
errors.append(('Missing expected DNA sequence DCTB %d,%d' % ((curr_data + correction_ix), curr_ix)))
for curr_data in range(len(mapping_data)):
for curr_ix in check_indices:
for curr_nt in mapping_data[curr_data][curr_ix]:
if (curr_nt not in valid_dna_chars):
errors.append(('Invalid DNA sequence detected: %s DCTB %d,%d' % (mapping_data[curr_data][curr_ix], (curr_data + correction_ix), curr_ix)))
continue
return errors
|
null | null | null | What do some polite text exhort to consider it as an alternative ?
| def _getReplacementString(replacement):
if callable(replacement):
replacement = _fullyQualifiedName(replacement)
return ('please use %s instead' % (replacement,))
| null | null | null | the user
| codeqa | def get Replacement String replacement if callable replacement replacement fully Qualified Name replacement return 'pleaseuse%sinstead' % replacement
| null | null | null | null | Question:
What do some polite text exhort to consider it as an alternative ?
Code:
def _getReplacementString(replacement):
if callable(replacement):
replacement = _fullyQualifiedName(replacement)
return ('please use %s instead' % (replacement,))
|
null | null | null | What considers it as an alternative ?
| def _getReplacementString(replacement):
if callable(replacement):
replacement = _fullyQualifiedName(replacement)
return ('please use %s instead' % (replacement,))
| null | null | null | the user
| codeqa | def get Replacement String replacement if callable replacement replacement fully Qualified Name replacement return 'pleaseuse%sinstead' % replacement
| null | null | null | null | Question:
What considers it as an alternative ?
Code:
def _getReplacementString(replacement):
if callable(replacement):
replacement = _fullyQualifiedName(replacement)
return ('please use %s instead' % (replacement,))
|
null | null | null | What do some polite text exhort the user ?
| def _getReplacementString(replacement):
if callable(replacement):
replacement = _fullyQualifiedName(replacement)
return ('please use %s instead' % (replacement,))
| null | null | null | to consider it as an alternative
| codeqa | def get Replacement String replacement if callable replacement replacement fully Qualified Name replacement return 'pleaseuse%sinstead' % replacement
| null | null | null | null | Question:
What do some polite text exhort the user ?
Code:
def _getReplacementString(replacement):
if callable(replacement):
replacement = _fullyQualifiedName(replacement)
return ('please use %s instead' % (replacement,))
|
null | null | null | What is exhorting the user to consider it as an alternative ?
| def _getReplacementString(replacement):
if callable(replacement):
replacement = _fullyQualifiedName(replacement)
return ('please use %s instead' % (replacement,))
| null | null | null | some polite text
| codeqa | def get Replacement String replacement if callable replacement replacement fully Qualified Name replacement return 'pleaseuse%sinstead' % replacement
| null | null | null | null | Question:
What is exhorting the user to consider it as an alternative ?
Code:
def _getReplacementString(replacement):
if callable(replacement):
replacement = _fullyQualifiedName(replacement)
return ('please use %s instead' % (replacement,))
|
null | null | null | What made in the buffer ?
| @contextmanager
def use_proxy_buffer(snippets_stack, vstate):
buffer_proxy = VimBufferProxy(snippets_stack, vstate)
old_buffer = _vim.buf
try:
_vim.buf = buffer_proxy
(yield)
finally:
_vim.buf = old_buffer
buffer_proxy.validate_buffer()
| null | null | null | all changes
| codeqa | @contextmanagerdef use proxy buffer snippets stack vstate buffer proxy Vim Buffer Proxy snippets stack vstate old buffer vim buftry vim buf buffer proxy yield finally vim buf old bufferbuffer proxy validate buffer
| null | null | null | null | Question:
What made in the buffer ?
Code:
@contextmanager
def use_proxy_buffer(snippets_stack, vstate):
buffer_proxy = VimBufferProxy(snippets_stack, vstate)
old_buffer = _vim.buf
try:
_vim.buf = buffer_proxy
(yield)
finally:
_vim.buf = old_buffer
buffer_proxy.validate_buffer()
|
null | null | null | What should accept any default options here ?
| def handle_default_options(options):
if options.settings:
os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
if options.pythonpath:
sys.path.insert(0, options.pythonpath)
| null | null | null | all commands
| codeqa | def handle default options options if options settings os environ['DJANGO SETTINGS MODULE'] options settingsif options pythonpath sys path insert 0 options pythonpath
| null | null | null | null | Question:
What should accept any default options here ?
Code:
def handle_default_options(options):
if options.settings:
os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
if options.pythonpath:
sys.path.insert(0, options.pythonpath)
|
null | null | null | Who can handle them before searching for user commands ?
| def handle_default_options(options):
if options.settings:
os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
if options.pythonpath:
sys.path.insert(0, options.pythonpath)
| null | null | null | managementutility
| codeqa | def handle default options options if options settings os environ['DJANGO SETTINGS MODULE'] options settingsif options pythonpath sys path insert 0 options pythonpath
| null | null | null | null | Question:
Who can handle them before searching for user commands ?
Code:
def handle_default_options(options):
if options.settings:
os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
if options.pythonpath:
sys.path.insert(0, options.pythonpath)
|
null | null | null | What does the code convert to text ?
| def to_text(value):
text = _by_value.get(value)
if (text is None):
text = str(value)
return text
| null | null | null | an opcode
| codeqa | def to text value text by value get value if text is None text str value return text
| null | null | null | null | Question:
What does the code convert to text ?
Code:
def to_text(value):
text = _by_value.get(value)
if (text is None):
text = str(value)
return text
|
null | null | null | What does the code build ?
| def _build_config_tree(name, configuration):
(type_, id_, options) = _get_type_id_options(name, configuration)
global _INDENT, _current_statement
_INDENT = ''
if (type_ == 'config'):
_current_statement = GivenStatement(options)
elif (type_ == 'log'):
_current_statement = UnnamedStatement(type='log')
_parse_log_statement(options)
else:
if _is_statement_unnamed(type_):
_current_statement = UnnamedStatement(type=type_)
else:
_current_statement = NamedStatement(type=type_, id=id_)
_parse_statement(options)
| null | null | null | the configuration tree
| codeqa | def build config tree name configuration type id options get type id options name configuration global INDENT current statement INDENT ''if type 'config' current statement Given Statement options elif type 'log' current statement Unnamed Statement type 'log' parse log statement options else if is statement unnamed type current statement Unnamed Statement type type else current statement Named Statement type type id id parse statement options
| null | null | null | null | Question:
What does the code build ?
Code:
def _build_config_tree(name, configuration):
(type_, id_, options) = _get_type_id_options(name, configuration)
global _INDENT, _current_statement
_INDENT = ''
if (type_ == 'config'):
_current_statement = GivenStatement(options)
elif (type_ == 'log'):
_current_statement = UnnamedStatement(type='log')
_parse_log_statement(options)
else:
if _is_statement_unnamed(type_):
_current_statement = UnnamedStatement(type=type_)
else:
_current_statement = NamedStatement(type=type_, id=id_)
_parse_statement(options)
|
null | null | null | What does the code create ?
| def _filer_file_from_upload(model, request, path, upload_data, sha1=None):
if sha1:
upload = model.objects.filter(sha1=sha1).first()
if upload:
return upload
file_form_cls = modelform_factory(model=model, fields=('original_filename', 'owner', 'file'))
upload_form = file_form_cls(data={'original_filename': upload_data.name, 'owner': (request.user.pk if (request and (not request.user.is_anonymous())) else None)}, files={'file': upload_data})
upload = upload_form.save(commit=False)
upload.is_public = True
if isinstance(path, Folder):
upload.folder = path
else:
upload.folder = filer_folder_from_path(path)
upload.save()
return upload
| null | null | null | some sort of filer file from the given upload data
| codeqa | def filer file from upload model request path upload data sha 1 None if sha 1 upload model objects filter sha 1 sha 1 first if upload return uploadfile form cls modelform factory model model fields 'original filename' 'owner' 'file' upload form file form cls data {'original filename' upload data name 'owner' request user pk if request and not request user is anonymous else None } files {'file' upload data} upload upload form save commit False upload is public Trueif isinstance path Folder upload folder pathelse upload folder filer folder from path path upload save return upload
| null | null | null | null | Question:
What does the code create ?
Code:
def _filer_file_from_upload(model, request, path, upload_data, sha1=None):
if sha1:
upload = model.objects.filter(sha1=sha1).first()
if upload:
return upload
file_form_cls = modelform_factory(model=model, fields=('original_filename', 'owner', 'file'))
upload_form = file_form_cls(data={'original_filename': upload_data.name, 'owner': (request.user.pk if (request and (not request.user.is_anonymous())) else None)}, files={'file': upload_data})
upload = upload_form.save(commit=False)
upload.is_public = True
if isinstance(path, Folder):
upload.folder = path
else:
upload.folder = filer_folder_from_path(path)
upload.save()
return upload
|
null | null | null | Where are the offsets in a byte code are start of lines ?
| def findlinestarts(code):
byte_increments = [ord(c) for c in code.co_lnotab[0::2]]
line_increments = [ord(c) for c in code.co_lnotab[1::2]]
lastlineno = None
lineno = code.co_firstlineno
addr = 0
for (byte_incr, line_incr) in zip(byte_increments, line_increments):
if byte_incr:
if (lineno != lastlineno):
(yield (addr, lineno))
lastlineno = lineno
addr += byte_incr
lineno += line_incr
if (lineno != lastlineno):
(yield (addr, lineno))
| null | null | null | in the source
| codeqa | def findlinestarts code byte increments [ord c for c in code co lnotab[ 0 2]]line increments [ord c for c in code co lnotab[ 1 2]]lastlineno Nonelineno code co firstlinenoaddr 0for byte incr line incr in zip byte increments line increments if byte incr if lineno lastlineno yield addr lineno lastlineno linenoaddr + byte incrlineno + line incrif lineno lastlineno yield addr lineno
| null | null | null | null | Question:
Where are the offsets in a byte code are start of lines ?
Code:
def findlinestarts(code):
byte_increments = [ord(c) for c in code.co_lnotab[0::2]]
line_increments = [ord(c) for c in code.co_lnotab[1::2]]
lastlineno = None
lineno = code.co_firstlineno
addr = 0
for (byte_incr, line_incr) in zip(byte_increments, line_increments):
if byte_incr:
if (lineno != lastlineno):
(yield (addr, lineno))
lastlineno = lineno
addr += byte_incr
lineno += line_incr
if (lineno != lastlineno):
(yield (addr, lineno))
|
null | null | null | What does the code convert to hex escape format ?
| def to_hexstr(str_):
return ''.join([('\\x%02x' % ord(i)) for i in bytes_iterator(str_)])
| null | null | null | a binary string
| codeqa | def to hexstr str return '' join [ '\\x% 02 x' % ord i for i in bytes iterator str ]
| null | null | null | null | Question:
What does the code convert to hex escape format ?
Code:
def to_hexstr(str_):
return ''.join([('\\x%02x' % ord(i)) for i in bytes_iterator(str_)])
|
null | null | null | Where does the code run the designated module ?
| def _run_module_as_main(mod_name, set_argv0=True):
try:
(mod_name, loader, code, fname) = _get_module_details(mod_name)
except ImportError as exc:
if set_argv0:
info = str(exc)
else:
info = ("can't find '__main__.py' in %r" % sys.argv[0])
msg = ('%s: %s' % (sys.executable, info))
sys.exit(msg)
pkg_name = mod_name.rpartition('.')[0]
main_globals = sys.modules['__main__'].__dict__
if set_argv0:
sys.argv[0] = fname
return _run_code(code, main_globals, None, '__main__', fname, loader, pkg_name)
| null | null | null | in the _ _ main _ _ namespace
| codeqa | def run module as main mod name set argv 0 True try mod name loader code fname get module details mod name except Import Error as exc if set argv 0 info str exc else info "can'tfind' main py'in%r" % sys argv[ 0 ] msg '%s %s' % sys executable info sys exit msg pkg name mod name rpartition ' ' [0 ]main globals sys modules[' main '] dict if set argv 0 sys argv[ 0 ] fnamereturn run code code main globals None ' main ' fname loader pkg name
| null | null | null | null | Question:
Where does the code run the designated module ?
Code:
def _run_module_as_main(mod_name, set_argv0=True):
try:
(mod_name, loader, code, fname) = _get_module_details(mod_name)
except ImportError as exc:
if set_argv0:
info = str(exc)
else:
info = ("can't find '__main__.py' in %r" % sys.argv[0])
msg = ('%s: %s' % (sys.executable, info))
sys.exit(msg)
pkg_name = mod_name.rpartition('.')[0]
main_globals = sys.modules['__main__'].__dict__
if set_argv0:
sys.argv[0] = fname
return _run_code(code, main_globals, None, '__main__', fname, loader, pkg_name)
|
null | null | null | What does the code run in the _ _ main _ _ namespace ?
| def _run_module_as_main(mod_name, set_argv0=True):
try:
(mod_name, loader, code, fname) = _get_module_details(mod_name)
except ImportError as exc:
if set_argv0:
info = str(exc)
else:
info = ("can't find '__main__.py' in %r" % sys.argv[0])
msg = ('%s: %s' % (sys.executable, info))
sys.exit(msg)
pkg_name = mod_name.rpartition('.')[0]
main_globals = sys.modules['__main__'].__dict__
if set_argv0:
sys.argv[0] = fname
return _run_code(code, main_globals, None, '__main__', fname, loader, pkg_name)
| null | null | null | the designated module
| codeqa | def run module as main mod name set argv 0 True try mod name loader code fname get module details mod name except Import Error as exc if set argv 0 info str exc else info "can'tfind' main py'in%r" % sys argv[ 0 ] msg '%s %s' % sys executable info sys exit msg pkg name mod name rpartition ' ' [0 ]main globals sys modules[' main '] dict if set argv 0 sys argv[ 0 ] fnamereturn run code code main globals None ' main ' fname loader pkg name
| null | null | null | null | Question:
What does the code run in the _ _ main _ _ namespace ?
Code:
def _run_module_as_main(mod_name, set_argv0=True):
try:
(mod_name, loader, code, fname) = _get_module_details(mod_name)
except ImportError as exc:
if set_argv0:
info = str(exc)
else:
info = ("can't find '__main__.py' in %r" % sys.argv[0])
msg = ('%s: %s' % (sys.executable, info))
sys.exit(msg)
pkg_name = mod_name.rpartition('.')[0]
main_globals = sys.modules['__main__'].__dict__
if set_argv0:
sys.argv[0] = fname
return _run_code(code, main_globals, None, '__main__', fname, loader, pkg_name)
|
null | null | null | What does the code count ?
| def count_tied_groups(x, use_missing=False):
nmasked = ma.getmask(x).sum()
data = ma.compressed(x).copy()
(ties, counts) = find_repeats(data)
nties = {}
if len(ties):
nties = dict(zip(np.unique(counts), itertools.repeat(1)))
nties.update(dict(zip(*find_repeats(counts))))
if (nmasked and use_missing):
try:
nties[nmasked] += 1
except KeyError:
nties[nmasked] = 1
return nties
| null | null | null | the number of tied values
| codeqa | def count tied groups x use missing False nmasked ma getmask x sum data ma compressed x copy ties counts find repeats data nties {}if len ties nties dict zip np unique counts itertools repeat 1 nties update dict zip *find repeats counts if nmasked and use missing try nties[nmasked] + 1except Key Error nties[nmasked] 1return nties
| null | null | null | null | Question:
What does the code count ?
Code:
def count_tied_groups(x, use_missing=False):
nmasked = ma.getmask(x).sum()
data = ma.compressed(x).copy()
(ties, counts) = find_repeats(data)
nties = {}
if len(ties):
nties = dict(zip(np.unique(counts), itertools.repeat(1)))
nties.update(dict(zip(*find_repeats(counts))))
if (nmasked and use_missing):
try:
nties[nmasked] += 1
except KeyError:
nties[nmasked] = 1
return nties
|
null | null | null | What does the code get ?
| def get_rules(jsx, dotted, template_string):
rules = []
for (token_type, rule) in _rules:
if ((not jsx) and token_type and ('jsx' in token_type)):
continue
if ((not template_string) and (token_type == 'template_string')):
continue
if (token_type == 'dotted_name'):
if (not dotted):
continue
token_type = 'name'
rules.append((token_type, rule))
return rules
| null | null | null | a tokenization rule list
| codeqa | def get rules jsx dotted template string rules []for token type rule in rules if not jsx and token type and 'jsx' in token type continueif not template string and token type 'template string' continueif token type 'dotted name' if not dotted continuetoken type 'name'rules append token type rule return rules
| null | null | null | null | Question:
What does the code get ?
Code:
def get_rules(jsx, dotted, template_string):
rules = []
for (token_type, rule) in _rules:
if ((not jsx) and token_type and ('jsx' in token_type)):
continue
if ((not template_string) and (token_type == 'template_string')):
continue
if (token_type == 'dotted_name'):
if (not dotted):
continue
token_type = 'name'
rules.append((token_type, rule))
return rules
|
null | null | null | What returns a user attribute that matches the contact_types argument ?
| def getUserContact(master, contact_types, uid):
d = master.db.users.getUser(uid)
d.addCallback(_extractContact, contact_types, uid)
return d
| null | null | null | a simple getter function
| codeqa | def get User Contact master contact types uid d master db users get User uid d add Callback extract Contact contact types uid return d
| null | null | null | null | Question:
What returns a user attribute that matches the contact_types argument ?
Code:
def getUserContact(master, contact_types, uid):
d = master.db.users.getUser(uid)
d.addCallback(_extractContact, contact_types, uid)
return d
|
null | null | null | What does a simple getter function return ?
| def getUserContact(master, contact_types, uid):
d = master.db.users.getUser(uid)
d.addCallback(_extractContact, contact_types, uid)
return d
| null | null | null | a user attribute that matches the contact_types argument
| codeqa | def get User Contact master contact types uid d master db users get User uid d add Callback extract Contact contact types uid return d
| null | null | null | null | Question:
What does a simple getter function return ?
Code:
def getUserContact(master, contact_types, uid):
d = master.db.users.getUser(uid)
d.addCallback(_extractContact, contact_types, uid)
return d
|
null | null | null | What matches the contact_types argument ?
| def getUserContact(master, contact_types, uid):
d = master.db.users.getUser(uid)
d.addCallback(_extractContact, contact_types, uid)
return d
| null | null | null | a user attribute
| codeqa | def get User Contact master contact types uid d master db users get User uid d add Callback extract Contact contact types uid return d
| null | null | null | null | Question:
What matches the contact_types argument ?
Code:
def getUserContact(master, contact_types, uid):
d = master.db.users.getUser(uid)
d.addCallback(_extractContact, contact_types, uid)
return d
|
null | null | null | What does a user attribute match ?
| def getUserContact(master, contact_types, uid):
d = master.db.users.getUser(uid)
d.addCallback(_extractContact, contact_types, uid)
return d
| null | null | null | the contact_types argument
| codeqa | def get User Contact master contact types uid d master db users get User uid d add Callback extract Contact contact types uid return d
| null | null | null | null | Question:
What does a user attribute match ?
Code:
def getUserContact(master, contact_types, uid):
d = master.db.users.getUser(uid)
d.addCallback(_extractContact, contact_types, uid)
return d
|
null | null | null | What does the code reduce by padding ?
| def extra_padding_y(original_size, padding):
return _resize(original_size, 1, padding=padding)
| null | null | null | the height of original_size
| codeqa | def extra padding y original size padding return resize original size 1 padding padding
| null | null | null | null | Question:
What does the code reduce by padding ?
Code:
def extra_padding_y(original_size, padding):
return _resize(original_size, 1, padding=padding)
|
null | null | null | How does the code reduce the height of original_size ?
| def extra_padding_y(original_size, padding):
return _resize(original_size, 1, padding=padding)
| null | null | null | by padding
| codeqa | def extra padding y original size padding return resize original size 1 padding padding
| null | null | null | null | Question:
How does the code reduce the height of original_size ?
Code:
def extra_padding_y(original_size, padding):
return _resize(original_size, 1, padding=padding)
|
null | null | null | In which direction do that x work ?
| def reshape_t(x, shape):
if (shape != ()):
return x.reshape(shape)
else:
return x[0]
| null | null | null | around fact
| codeqa | def reshape t x shape if shape return x reshape shape else return x[ 0 ]
| null | null | null | null | Question:
In which direction do that x work ?
Code:
def reshape_t(x, shape):
if (shape != ()):
return x.reshape(shape)
else:
return x[0]
|
null | null | null | How did paths separate ?
| def expand_dictionary(record, separator='.'):
result = {}
for (key, value) in record.items():
current = result
path = key.split(separator)
for part in path[:(-1)]:
if (part not in current):
current[part] = {}
current = current[part]
current[path[(-1)]] = value
return result
| null | null | null | by separator
| codeqa | def expand dictionary record separator ' ' result {}for key value in record items current resultpath key split separator for part in path[ -1 ] if part not in current current[part] {}current current[part]current[path[ -1 ]] valuereturn result
| null | null | null | null | Question:
How did paths separate ?
Code:
def expand_dictionary(record, separator='.'):
result = {}
for (key, value) in record.items():
current = result
path = key.split(separator)
for part in path[:(-1)]:
if (part not in current):
current[part] = {}
current = current[part]
current[path[(-1)]] = value
return result
|
null | null | null | What does the code return ?
| def get_managed_object_name(mo_ref):
props = get_properties_of_managed_object(mo_ref, ['name'])
return props.get('name')
| null | null | null | the name of a managed object
| codeqa | def get managed object name mo ref props get properties of managed object mo ref ['name'] return props get 'name'
| null | null | null | null | Question:
What does the code return ?
Code:
def get_managed_object_name(mo_ref):
props = get_properties_of_managed_object(mo_ref, ['name'])
return props.get('name')
|
null | null | null | What does the code update ?
| def update_credit_request_status(request_uuid, provider_id, status):
if (status not in [CreditRequest.REQUEST_STATUS_APPROVED, CreditRequest.REQUEST_STATUS_REJECTED]):
raise InvalidCreditStatus
try:
request = CreditRequest.objects.get(uuid=request_uuid, provider__provider_id=provider_id)
old_status = request.status
request.status = status
request.save()
log.info(u'Updated request with UUID "%s" from status "%s" to "%s" for provider with ID "%s".', request_uuid, old_status, status, provider_id)
except CreditRequest.DoesNotExist:
msg = u'Credit provider with ID "{provider_id}" attempted to update request with UUID "{request_uuid}", but no request with this UUID is associated with the provider.'.format(provider_id=provider_id, request_uuid=request_uuid)
log.warning(msg)
raise CreditRequestNotFound(msg)
| null | null | null | the status of a credit request
| codeqa | def update credit request status request uuid provider id status if status not in [ Credit Request REQUEST STATUS APPROVED Credit Request REQUEST STATUS REJECTED] raise Invalid Credit Statustry request Credit Request objects get uuid request uuid provider provider id provider id old status request statusrequest status statusrequest save log info u' Updatedrequestwith UUID"%s"fromstatus"%s"to"%s"forproviderwith ID"%s" ' request uuid old status status provider id except Credit Request Does Not Exist msg u' Creditproviderwith ID"{provider id}"attemptedtoupdaterequestwith UUID"{request uuid}" butnorequestwiththis UUI Disassociatedwiththeprovider ' format provider id provider id request uuid request uuid log warning msg raise Credit Request Not Found msg
| null | null | null | null | Question:
What does the code update ?
Code:
def update_credit_request_status(request_uuid, provider_id, status):
if (status not in [CreditRequest.REQUEST_STATUS_APPROVED, CreditRequest.REQUEST_STATUS_REJECTED]):
raise InvalidCreditStatus
try:
request = CreditRequest.objects.get(uuid=request_uuid, provider__provider_id=provider_id)
old_status = request.status
request.status = status
request.save()
log.info(u'Updated request with UUID "%s" from status "%s" to "%s" for provider with ID "%s".', request_uuid, old_status, status, provider_id)
except CreditRequest.DoesNotExist:
msg = u'Credit provider with ID "{provider_id}" attempted to update request with UUID "{request_uuid}", but no request with this UUID is associated with the provider.'.format(provider_id=provider_id, request_uuid=request_uuid)
log.warning(msg)
raise CreditRequestNotFound(msg)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.