labNo float64 1 10 ⌀ | taskNo float64 0 4 ⌀ | questioner stringclasses 2
values | question stringlengths 9 201 | code stringlengths 18 30.3k | startLine float64 0 192 ⌀ | endLine float64 0 196 ⌀ | questionType stringclasses 4
values | answer stringlengths 2 905 | src stringclasses 3
values | code_processed stringlengths 12 28.3k ⌀ | id stringlengths 2 5 ⌀ | raw_code stringlengths 20 30.3k ⌀ | raw_comment stringlengths 10 242 ⌀ | comment stringlengths 9 207 ⌀ | q_code stringlengths 66 30.3k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
null | null | null | What does this function do? | def __converting_factory(specimen_cls, original_factory):
instrumented_cls = __canned_instrumentation[specimen_cls]
def wrapper():
collection = original_factory()
return instrumented_cls(collection)
wrapper.__name__ = ('%sWrapper' % original_factory.__name__)
wrapper.__doc__ = original_factory.__doc__
return w... | null | null | null | Return a wrapper that converts a "canned" collection like
set, dict, list into the Instrumented* version. | pcsd | def converting factory specimen cls original factory instrumented cls = canned instrumentation[specimen cls] def wrapper collection = original factory return instrumented cls collection wrapper name = '%s Wrapper' % original factory name wrapper doc = original factory doc return wrapper | 12008 | def __converting_factory(specimen_cls, original_factory):
instrumented_cls = __canned_instrumentation[specimen_cls]
def wrapper():
collection = original_factory()
return instrumented_cls(collection)
wrapper.__name__ = ('%sWrapper' % original_factory.__name__)
wrapper.__doc__ = original_factory.__doc__
return w... | Return a wrapper that converts a "canned" collection like
set, dict, list into the Instrumented* version. | return a wrapper that converts a " canned " collection like set , dict , list into the instrumented * version . | Question:
What does this function do?
Code:
def __converting_factory(specimen_cls, original_factory):
instrumented_cls = __canned_instrumentation[specimen_cls]
def wrapper():
collection = original_factory()
return instrumented_cls(collection)
wrapper.__name__ = ('%sWrapper' % original_factory.__name__)
wrapp... |
null | null | null | What does this function do? | def make_flask_stack(conf, **app_conf):
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
debug = asbool(app_conf.get('debug', app_conf.get('DEBUG', False)))
testing = asbool(app_conf.get('testing', app_conf.get('TESTING', False)))
app = flask_app = CKANFlask(__name__)
app.debug =... | null | null | null | This has to pass the flask app through all the same middleware that
Pylons used | pcsd | def make flask stack conf **app conf root = os path dirname os path dirname os path dirname os path abspath file debug = asbool app conf get 'debug' app conf get 'DEBUG' False testing = asbool app conf get 'testing' app conf get 'TESTING' False app = flask app = CKAN Flask name app debug = debug app testing = testing a... | 12012 | def make_flask_stack(conf, **app_conf):
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
debug = asbool(app_conf.get('debug', app_conf.get('DEBUG', False)))
testing = asbool(app_conf.get('testing', app_conf.get('TESTING', False)))
app = flask_app = CKANFlask(__name__)
app.debug =... | This has to pass the flask app through all the same middleware that
Pylons used | this has to pass the flask app through all the same middleware that | Question:
What does this function do?
Code:
def make_flask_stack(conf, **app_conf):
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
debug = asbool(app_conf.get('debug', app_conf.get('DEBUG', False)))
testing = asbool(app_conf.get('testing', app_conf.get('TESTING', False)))
app... |
null | null | null | What does this function do? | def get_course_and_check_access(course_key, user, depth=0):
if (not has_studio_read_access(user, course_key)):
raise PermissionDenied()
course_module = modulestore().get_course(course_key, depth=depth)
return course_module
| null | null | null | Internal method used to calculate and return the locator and course module
for the view functions in this file. | pcsd | def get course and check access course key user depth=0 if not has studio read access user course key raise Permission Denied course module = modulestore get course course key depth=depth return course module | 12017 | def get_course_and_check_access(course_key, user, depth=0):
if (not has_studio_read_access(user, course_key)):
raise PermissionDenied()
course_module = modulestore().get_course(course_key, depth=depth)
return course_module
| Internal method used to calculate and return the locator and course module
for the view functions in this file. | internal method used to calculate and return the locator and course module for the view functions in this file . | Question:
What does this function do?
Code:
def get_course_and_check_access(course_key, user, depth=0):
if (not has_studio_read_access(user, course_key)):
raise PermissionDenied()
course_module = modulestore().get_course(course_key, depth=depth)
return course_module
|
null | null | null | What does this function do? | def paginate_data(request, data_list, data_type='cur', per_page=25, page=1):
if (not data_list):
paged_data = []
page_urls = {}
else:
paginator = Paginator(data_list, per_page)
try:
paged_data = paginator.page(page)
listed_pages = pages_to_show(paginator, page)
except PageNotAnInteger:
paged_data =... | null | null | null | Create pagination for list | pcsd | def paginate data request data list data type='cur' per page=25 page=1 if not data list paged data = [] page urls = {} else paginator = Paginator data list per page try paged data = paginator page page listed pages = pages to show paginator page except Page Not An Integer paged data = paginator page 1 listed pages = pa... | 12019 | def paginate_data(request, data_list, data_type='cur', per_page=25, page=1):
if (not data_list):
paged_data = []
page_urls = {}
else:
paginator = Paginator(data_list, per_page)
try:
paged_data = paginator.page(page)
listed_pages = pages_to_show(paginator, page)
except PageNotAnInteger:
paged_data =... | Create pagination for list | create pagination for list | Question:
What does this function do?
Code:
def paginate_data(request, data_list, data_type='cur', per_page=25, page=1):
if (not data_list):
paged_data = []
page_urls = {}
else:
paginator = Paginator(data_list, per_page)
try:
paged_data = paginator.page(page)
listed_pages = pages_to_show(paginator, p... |
null | null | null | What does this function do? | def create_resource(options):
deserializer = wsgi.JSONRequestDeserializer()
serializer = serializers.JSONResponseSerializer()
return wsgi.Resource(ActionController(options), deserializer, serializer)
| null | null | null | Actions action factory method. | pcsd | def create resource options deserializer = wsgi JSON Request Deserializer serializer = serializers JSON Response Serializer return wsgi Resource Action Controller options deserializer serializer | 12023 | def create_resource(options):
deserializer = wsgi.JSONRequestDeserializer()
serializer = serializers.JSONResponseSerializer()
return wsgi.Resource(ActionController(options), deserializer, serializer)
| Actions action factory method. | actions action factory method . | Question:
What does this function do?
Code:
def create_resource(options):
deserializer = wsgi.JSONRequestDeserializer()
serializer = serializers.JSONResponseSerializer()
return wsgi.Resource(ActionController(options), deserializer, serializer)
|
null | null | null | What does this function do? | def _package(package, subdirs=None):
dirs = package.split(u'.')
app_dir = os.path.join(u'share', u'git-cola', u'lib', *dirs)
if subdirs:
dirs = (list(subdirs) + dirs)
src_dir = os.path.join(*dirs)
return (app_dir, glob(os.path.join(src_dir, u'*.py')))
| null | null | null | Collect python files for a given python "package" name | pcsd | def package package subdirs=None dirs = package split u' ' app dir = os path join u'share' u'git-cola' u'lib' *dirs if subdirs dirs = list subdirs + dirs src dir = os path join *dirs return app dir glob os path join src dir u'* py' | 12024 | def _package(package, subdirs=None):
dirs = package.split(u'.')
app_dir = os.path.join(u'share', u'git-cola', u'lib', *dirs)
if subdirs:
dirs = (list(subdirs) + dirs)
src_dir = os.path.join(*dirs)
return (app_dir, glob(os.path.join(src_dir, u'*.py')))
| Collect python files for a given python "package" name | collect python files for a given python " package " name | Question:
What does this function do?
Code:
def _package(package, subdirs=None):
dirs = package.split(u'.')
app_dir = os.path.join(u'share', u'git-cola', u'lib', *dirs)
if subdirs:
dirs = (list(subdirs) + dirs)
src_dir = os.path.join(*dirs)
return (app_dir, glob(os.path.join(src_dir, u'*.py')))
|
null | null | null | What does this function do? | def assert_identical(a, b):
assert_equal(a, b)
if (type(b) is str):
assert_equal(type(a), type(b))
else:
assert_equal(np.asarray(a).dtype.type, np.asarray(b).dtype.type)
| null | null | null | Assert whether value AND type are the same | pcsd | def assert identical a b assert equal a b if type b is str assert equal type a type b else assert equal np asarray a dtype type np asarray b dtype type | 12033 | def assert_identical(a, b):
assert_equal(a, b)
if (type(b) is str):
assert_equal(type(a), type(b))
else:
assert_equal(np.asarray(a).dtype.type, np.asarray(b).dtype.type)
| Assert whether value AND type are the same | assert whether value and type are the same | Question:
What does this function do?
Code:
def assert_identical(a, b):
assert_equal(a, b)
if (type(b) is str):
assert_equal(type(a), type(b))
else:
assert_equal(np.asarray(a).dtype.type, np.asarray(b).dtype.type)
|
null | null | null | What does this function do? | def info(package, conn=None):
if (conn is None):
conn = init()
fields = ('package', 'version', 'release', 'installed', 'os', 'os_family', 'dependencies', 'os_dependencies', 'os_family_dependencies', 'summary', 'description')
data = conn.execute('SELECT {0} FROM packages WHERE package=?'.format(','.join(fields)), (... | null | null | null | List info for a package | pcsd | def info package conn=None if conn is None conn = init fields = 'package' 'version' 'release' 'installed' 'os' 'os family' 'dependencies' 'os dependencies' 'os family dependencies' 'summary' 'description' data = conn execute 'SELECT {0} FROM packages WHERE package=?' format ' ' join fields package row = data fetchone i... | 12034 | def info(package, conn=None):
if (conn is None):
conn = init()
fields = ('package', 'version', 'release', 'installed', 'os', 'os_family', 'dependencies', 'os_dependencies', 'os_family_dependencies', 'summary', 'description')
data = conn.execute('SELECT {0} FROM packages WHERE package=?'.format(','.join(fields)), (... | List info for a package | list info for a package | Question:
What does this function do?
Code:
def info(package, conn=None):
if (conn is None):
conn = init()
fields = ('package', 'version', 'release', 'installed', 'os', 'os_family', 'dependencies', 'os_dependencies', 'os_family_dependencies', 'summary', 'description')
data = conn.execute('SELECT {0} FROM packag... |
null | null | null | What does this function do? | def dispatch(c, id, methodname, args=(), kwds={}):
c.send((id, methodname, args, kwds))
(kind, result) = c.recv()
if (kind == '#RETURN'):
return result
raise convert_to_error(kind, result)
| null | null | null | Send a message to manager using connection `c` and return response | pcsd | def dispatch c id methodname args= kwds={} c send id methodname args kwds kind result = c recv if kind == '#RETURN' return result raise convert to error kind result | 12036 | def dispatch(c, id, methodname, args=(), kwds={}):
c.send((id, methodname, args, kwds))
(kind, result) = c.recv()
if (kind == '#RETURN'):
return result
raise convert_to_error(kind, result)
| Send a message to manager using connection `c` and return response | send a message to manager using connection c and return response | Question:
What does this function do?
Code:
def dispatch(c, id, methodname, args=(), kwds={}):
c.send((id, methodname, args, kwds))
(kind, result) = c.recv()
if (kind == '#RETURN'):
return result
raise convert_to_error(kind, result)
|
null | null | null | What does this function do? | def check_ignore_error(ignore_error, stderr):
if ((not ignore_error) or (not stderr)):
return False
if (not isinstance(ignore_error, six.string_types)):
ignore_error = '|'.join(ignore_error)
if re.search(ignore_error, stderr):
return True
return False
| null | null | null | Return True if ignore_error is in stderr, False otherwise. | pcsd | def check ignore error ignore error stderr if not ignore error or not stderr return False if not isinstance ignore error six string types ignore error = '|' join ignore error if re search ignore error stderr return True return False | 12037 | def check_ignore_error(ignore_error, stderr):
if ((not ignore_error) or (not stderr)):
return False
if (not isinstance(ignore_error, six.string_types)):
ignore_error = '|'.join(ignore_error)
if re.search(ignore_error, stderr):
return True
return False
| Return True if ignore_error is in stderr, False otherwise. | return true if ignore _ error is in stderr , false otherwise . | Question:
What does this function do?
Code:
def check_ignore_error(ignore_error, stderr):
if ((not ignore_error) or (not stderr)):
return False
if (not isinstance(ignore_error, six.string_types)):
ignore_error = '|'.join(ignore_error)
if re.search(ignore_error, stderr):
return True
return False
|
null | null | null | What does this function do? | def get_fallback_languages(language, site_id=None):
try:
language = get_language_object(language, site_id)
except LanguageError:
language = get_languages(site_id)[0]
return language.get('fallbacks', [])
| null | null | null | returns a list of fallback languages for the given language | pcsd | def get fallback languages language site id=None try language = get language object language site id except Language Error language = get languages site id [0] return language get 'fallbacks' [] | 12045 | def get_fallback_languages(language, site_id=None):
try:
language = get_language_object(language, site_id)
except LanguageError:
language = get_languages(site_id)[0]
return language.get('fallbacks', [])
| returns a list of fallback languages for the given language | returns a list of fallback languages for the given language | Question:
What does this function do?
Code:
def get_fallback_languages(language, site_id=None):
try:
language = get_language_object(language, site_id)
except LanguageError:
language = get_languages(site_id)[0]
return language.get('fallbacks', [])
|
null | null | null | What does this function do? | @FileSystem.in_directory(current_directory, 'django', 'grocery')
def test_django_admin_media_serving_on_django_125():
os.environ['PYTHONPATH'] = ('%s:%s' % (FileSystem.join(lib_directory, 'Django-1.2.5'), OLD_PYTHONPATH))
(status, out) = commands.getstatusoutput('python manage.py harvest --verbosity=2 ./features/')
... | null | null | null | lettuce should serve admin static files properly on Django 1.2.5 | pcsd | @File System in directory current directory 'django' 'grocery' def test django admin media serving on django 125 os environ['PYTHONPATH'] = '%s %s' % File System join lib directory 'Django-1 2 5' OLD PYTHONPATH status out = commands getstatusoutput 'python manage py harvest --verbosity=2 /features/' assert equals statu... | 12047 | @FileSystem.in_directory(current_directory, 'django', 'grocery')
def test_django_admin_media_serving_on_django_125():
os.environ['PYTHONPATH'] = ('%s:%s' % (FileSystem.join(lib_directory, 'Django-1.2.5'), OLD_PYTHONPATH))
(status, out) = commands.getstatusoutput('python manage.py harvest --verbosity=2 ./features/')
... | lettuce should serve admin static files properly on Django 1.2.5 | lettuce should serve admin static files properly on django 1 . 2 . 5 | Question:
What does this function do?
Code:
@FileSystem.in_directory(current_directory, 'django', 'grocery')
def test_django_admin_media_serving_on_django_125():
os.environ['PYTHONPATH'] = ('%s:%s' % (FileSystem.join(lib_directory, 'Django-1.2.5'), OLD_PYTHONPATH))
(status, out) = commands.getstatusoutput('python ... |
null | null | null | What does this function do? | def generate_fake_facility_groups(names=('Class 4E', 'Class 5B'), facilities=None):
if (not facilities):
facilities = generate_fake_facilities()
facility_groups = []
for facility in facilities:
for name in names:
found_facility_groups = FacilityGroup.objects.filter(facility=facility, name=name)
if found_fa... | null | null | null | Add the given fake facility groups to the given fake facilities | pcsd | def generate fake facility groups names= 'Class 4E' 'Class 5B' facilities=None if not facilities facilities = generate fake facilities facility groups = [] for facility in facilities for name in names found facility groups = Facility Group objects filter facility=facility name=name if found facility groups facility gro... | 12051 | def generate_fake_facility_groups(names=('Class 4E', 'Class 5B'), facilities=None):
if (not facilities):
facilities = generate_fake_facilities()
facility_groups = []
for facility in facilities:
for name in names:
found_facility_groups = FacilityGroup.objects.filter(facility=facility, name=name)
if found_fa... | Add the given fake facility groups to the given fake facilities | add the given fake facility groups to the given fake facilities | Question:
What does this function do?
Code:
def generate_fake_facility_groups(names=('Class 4E', 'Class 5B'), facilities=None):
if (not facilities):
facilities = generate_fake_facilities()
facility_groups = []
for facility in facilities:
for name in names:
found_facility_groups = FacilityGroup.objects.filt... |
null | null | null | What does this function do? | def getNewRepository():
return SmoothRepository()
| null | null | null | Get new repository. | pcsd | def get New Repository return Smooth Repository | 12053 | def getNewRepository():
return SmoothRepository()
| Get new repository. | get new repository . | Question:
What does this function do?
Code:
def getNewRepository():
return SmoothRepository()
|
null | null | null | What does this function do? | def addSphere(elementNode, faces, radius, vertexes):
bottom = (- radius.z)
sides = evaluate.getSidesMinimumThreeBasedOnPrecision(elementNode, max(radius.x, radius.y, radius.z))
sphereSlices = max((sides / 2), 2)
equator = euclidean.getComplexPolygonByComplexRadius(complex(radius.x, radius.y), sides)
polygons = [tr... | null | null | null | Add sphere by radius. | pcsd | def add Sphere element Node faces radius vertexes bottom = - radius z sides = evaluate get Sides Minimum Three Based On Precision element Node max radius x radius y radius z sphere Slices = max sides / 2 2 equator = euclidean get Complex Polygon By Complex Radius complex radius x radius y sides polygons = [triangle mes... | 12071 | def addSphere(elementNode, faces, radius, vertexes):
bottom = (- radius.z)
sides = evaluate.getSidesMinimumThreeBasedOnPrecision(elementNode, max(radius.x, radius.y, radius.z))
sphereSlices = max((sides / 2), 2)
equator = euclidean.getComplexPolygonByComplexRadius(complex(radius.x, radius.y), sides)
polygons = [tr... | Add sphere by radius. | add sphere by radius . | Question:
What does this function do?
Code:
def addSphere(elementNode, faces, radius, vertexes):
bottom = (- radius.z)
sides = evaluate.getSidesMinimumThreeBasedOnPrecision(elementNode, max(radius.x, radius.y, radius.z))
sphereSlices = max((sides / 2), 2)
equator = euclidean.getComplexPolygonByComplexRadius(comp... |
null | null | null | What does this function do? | def parseArgs():
global LogToConsole, NoKVM, Branch, Zip, TIMEOUT, Forward, Chown
parser = argparse.ArgumentParser(description='Mininet VM build script', epilog='')
parser.add_argument('-v', '--verbose', action='store_true', help='send VM output to console rather than log file')
parser.add_argument('-d', '--depend'... | null | null | null | Parse command line arguments and run | pcsd | def parse Args global Log To Console No KVM Branch Zip TIMEOUT Forward Chown parser = argparse Argument Parser description='Mininet VM build script' epilog='' parser add argument '-v' '--verbose' action='store true' help='send VM output to console rather than log file' parser add argument '-d' '--depend' action='store ... | 12078 | def parseArgs():
global LogToConsole, NoKVM, Branch, Zip, TIMEOUT, Forward, Chown
parser = argparse.ArgumentParser(description='Mininet VM build script', epilog='')
parser.add_argument('-v', '--verbose', action='store_true', help='send VM output to console rather than log file')
parser.add_argument('-d', '--depend'... | Parse command line arguments and run | parse command line arguments and run | Question:
What does this function do?
Code:
def parseArgs():
global LogToConsole, NoKVM, Branch, Zip, TIMEOUT, Forward, Chown
parser = argparse.ArgumentParser(description='Mininet VM build script', epilog='')
parser.add_argument('-v', '--verbose', action='store_true', help='send VM output to console rather than l... |
null | null | null | What does this function do? | def getDoubledRoundZ(overhangingSegment, segmentRoundZ):
endpoint = overhangingSegment[0]
roundZ = (endpoint.point - endpoint.otherEndpoint.point)
roundZ *= segmentRoundZ
if (abs(roundZ) == 0.0):
return complex()
if (roundZ.real < 0.0):
roundZ *= (-1.0)
roundZLength = abs(roundZ)
return ((roundZ * roundZ) / ... | null | null | null | Get doubled plane angle around z of the overhanging segment. | pcsd | def get Doubled Round Z overhanging Segment segment Round Z endpoint = overhanging Segment[0] round Z = endpoint point - endpoint other Endpoint point round Z *= segment Round Z if abs round Z == 0 0 return complex if round Z real < 0 0 round Z *= -1 0 round Z Length = abs round Z return round Z * round Z / round Z Len... | 12092 | def getDoubledRoundZ(overhangingSegment, segmentRoundZ):
endpoint = overhangingSegment[0]
roundZ = (endpoint.point - endpoint.otherEndpoint.point)
roundZ *= segmentRoundZ
if (abs(roundZ) == 0.0):
return complex()
if (roundZ.real < 0.0):
roundZ *= (-1.0)
roundZLength = abs(roundZ)
return ((roundZ * roundZ) / ... | Get doubled plane angle around z of the overhanging segment. | get doubled plane angle around z of the overhanging segment . | Question:
What does this function do?
Code:
def getDoubledRoundZ(overhangingSegment, segmentRoundZ):
endpoint = overhangingSegment[0]
roundZ = (endpoint.point - endpoint.otherEndpoint.point)
roundZ *= segmentRoundZ
if (abs(roundZ) == 0.0):
return complex()
if (roundZ.real < 0.0):
roundZ *= (-1.0)
roundZLen... |
null | null | null | What does this function do? | def removeIdentifiersFromDictionary(dictionary):
euclidean.removeElementsFromDictionary(dictionary, ['id', 'name', 'tags'])
return dictionary
| null | null | null | Remove the identifier elements from a dictionary. | pcsd | def remove Identifiers From Dictionary dictionary euclidean remove Elements From Dictionary dictionary ['id' 'name' 'tags'] return dictionary | 12095 | def removeIdentifiersFromDictionary(dictionary):
euclidean.removeElementsFromDictionary(dictionary, ['id', 'name', 'tags'])
return dictionary
| Remove the identifier elements from a dictionary. | remove the identifier elements from a dictionary . | Question:
What does this function do?
Code:
def removeIdentifiersFromDictionary(dictionary):
euclidean.removeElementsFromDictionary(dictionary, ['id', 'name', 'tags'])
return dictionary
|
null | null | null | What does this function do? | def mask_password(cmd):
if ((len(cmd) > 3) and (cmd[0] == 'raidcom') and (cmd[1] == '-login')):
tmp = list(cmd)
tmp[3] = strutils.mask_dict_password({'password': ''}).get('password')
else:
tmp = cmd
return ' '.join([six.text_type(c) for c in tmp])
| null | null | null | Return a string in which the password is masked. | pcsd | def mask password cmd if len cmd > 3 and cmd[0] == 'raidcom' and cmd[1] == '-login' tmp = list cmd tmp[3] = strutils mask dict password {'password' ''} get 'password' else tmp = cmd return ' ' join [six text type c for c in tmp] | 12097 | def mask_password(cmd):
if ((len(cmd) > 3) and (cmd[0] == 'raidcom') and (cmd[1] == '-login')):
tmp = list(cmd)
tmp[3] = strutils.mask_dict_password({'password': ''}).get('password')
else:
tmp = cmd
return ' '.join([six.text_type(c) for c in tmp])
| Return a string in which the password is masked. | return a string in which the password is masked . | Question:
What does this function do?
Code:
def mask_password(cmd):
if ((len(cmd) > 3) and (cmd[0] == 'raidcom') and (cmd[1] == '-login')):
tmp = list(cmd)
tmp[3] = strutils.mask_dict_password({'password': ''}).get('password')
else:
tmp = cmd
return ' '.join([six.text_type(c) for c in tmp])
|
null | null | null | What does this function do? | def _get_classifier(lang):
cls = (((lang == 'Perl') and PerlClassifier) or UDLClassifier)
return cls()
| null | null | null | Factory method for choosing the style classifier. | pcsd | def get classifier lang cls = lang == 'Perl' and Perl Classifier or UDL Classifier return cls | 12103 | def _get_classifier(lang):
cls = (((lang == 'Perl') and PerlClassifier) or UDLClassifier)
return cls()
| Factory method for choosing the style classifier. | factory method for choosing the style classifier . | Question:
What does this function do?
Code:
def _get_classifier(lang):
cls = (((lang == 'Perl') and PerlClassifier) or UDLClassifier)
return cls()
|
null | null | null | What does this function do? | def build_encoder(tparams, options):
embedding = tensor.tensor3('embedding', dtype='float32')
x_mask = tensor.matrix('x_mask', dtype='float32')
proj = get_layer(options['encoder'])[1](tparams, embedding, options, prefix='encoder', mask=x_mask)
ctx = proj[0][(-1)]
return (embedding, x_mask, ctx)
| null | null | null | build an encoder, given pre-computed word embeddings | pcsd | def build encoder tparams options embedding = tensor tensor3 'embedding' dtype='float32' x mask = tensor matrix 'x mask' dtype='float32' proj = get layer options['encoder'] [1] tparams embedding options prefix='encoder' mask=x mask ctx = proj[0][ -1 ] return embedding x mask ctx | 12104 | def build_encoder(tparams, options):
embedding = tensor.tensor3('embedding', dtype='float32')
x_mask = tensor.matrix('x_mask', dtype='float32')
proj = get_layer(options['encoder'])[1](tparams, embedding, options, prefix='encoder', mask=x_mask)
ctx = proj[0][(-1)]
return (embedding, x_mask, ctx)
| build an encoder, given pre-computed word embeddings | build an encoder , given pre - computed word embeddings | Question:
What does this function do?
Code:
def build_encoder(tparams, options):
embedding = tensor.tensor3('embedding', dtype='float32')
x_mask = tensor.matrix('x_mask', dtype='float32')
proj = get_layer(options['encoder'])[1](tparams, embedding, options, prefix='encoder', mask=x_mask)
ctx = proj[0][(-1)]
retu... |
null | null | null | What does this function do? | def get_ca_certs_path():
CA_CERTS = ['/opt/datadog-agent/embedded/ssl/certs/cacert.pem', os.path.join(os.path.dirname(tornado.__file__), 'ca-certificates.crt'), '/etc/ssl/certs/ca-certificates.crt']
for f in CA_CERTS:
if os.path.exists(f):
return f
return None
| null | null | null | Get a path to the trusted certificates of the system | pcsd | def get ca certs path CA CERTS = ['/opt/datadog-agent/embedded/ssl/certs/cacert pem' os path join os path dirname tornado file 'ca-certificates crt' '/etc/ssl/certs/ca-certificates crt'] for f in CA CERTS if os path exists f return f return None | 12108 | def get_ca_certs_path():
CA_CERTS = ['/opt/datadog-agent/embedded/ssl/certs/cacert.pem', os.path.join(os.path.dirname(tornado.__file__), 'ca-certificates.crt'), '/etc/ssl/certs/ca-certificates.crt']
for f in CA_CERTS:
if os.path.exists(f):
return f
return None
| Get a path to the trusted certificates of the system | get a path to the trusted certificates of the system | Question:
What does this function do?
Code:
def get_ca_certs_path():
CA_CERTS = ['/opt/datadog-agent/embedded/ssl/certs/cacert.pem', os.path.join(os.path.dirname(tornado.__file__), 'ca-certificates.crt'), '/etc/ssl/certs/ca-certificates.crt']
for f in CA_CERTS:
if os.path.exists(f):
return f
return None
|
null | null | null | What does this function do? | def get_repository_type_from_tool_shed(app, tool_shed_url, name, owner):
tool_shed_url = common_util.get_tool_shed_url_from_tool_shed_registry(app, tool_shed_url)
params = dict(name=name, owner=owner)
pathspec = ['repository', 'get_repository_type']
repository_type = util.url_get(tool_shed_url, password_mgr=app.too... | null | null | null | Send a request to the tool shed to retrieve the type for a repository defined by the
combination of a name and owner. | pcsd | def get repository type from tool shed app tool shed url name owner tool shed url = common util get tool shed url from tool shed registry app tool shed url params = dict name=name owner=owner pathspec = ['repository' 'get repository type'] repository type = util url get tool shed url password mgr=app tool shed registry... | 12111 | def get_repository_type_from_tool_shed(app, tool_shed_url, name, owner):
tool_shed_url = common_util.get_tool_shed_url_from_tool_shed_registry(app, tool_shed_url)
params = dict(name=name, owner=owner)
pathspec = ['repository', 'get_repository_type']
repository_type = util.url_get(tool_shed_url, password_mgr=app.too... | Send a request to the tool shed to retrieve the type for a repository defined by the
combination of a name and owner. | send a request to the tool shed to retrieve the type for a repository defined by the combination of a name and owner . | Question:
What does this function do?
Code:
def get_repository_type_from_tool_shed(app, tool_shed_url, name, owner):
tool_shed_url = common_util.get_tool_shed_url_from_tool_shed_registry(app, tool_shed_url)
params = dict(name=name, owner=owner)
pathspec = ['repository', 'get_repository_type']
repository_type = u... |
null | null | null | What does this function do? | def getDebugging():
return Deferred.debug
| null | null | null | Determine whether L{Deferred} debugging is enabled. | pcsd | def get Debugging return Deferred debug | 12125 | def getDebugging():
return Deferred.debug
| Determine whether L{Deferred} debugging is enabled. | determine whether l { deferred } debugging is enabled . | Question:
What does this function do?
Code:
def getDebugging():
return Deferred.debug
|
null | null | null | What does this function do? | def parse_gml_lines(lines, label, destringizer):
def tokenize():
patterns = ['[A-Za-z][0-9A-Za-z_]*\\b', '[+-]?(?:[0-9]*\\.[0-9]+|[0-9]+\\.[0-9]*)(?:[Ee][+-]?[0-9]+)?', '[+-]?[0-9]+', '".*?"', '\\[', '\\]', '#.*$|\\s+']
tokens = re.compile('|'.join(((('(' + pattern) + ')') for pattern in patterns)))
lineno = 0
... | null | null | null | Parse GML into a graph. | pcsd | def parse gml lines lines label destringizer def tokenize patterns = ['[A-Za-z][0-9A-Za-z ]*\\b' '[+-]? ? [0-9]*\\ [0-9]+|[0-9]+\\ [0-9]* ? [Ee][+-]?[0-9]+ ?' '[+-]?[0-9]+' '" *?"' '\\[' '\\]' '# *$|\\s+'] tokens = re compile '|' join ' ' + pattern + ' ' for pattern in patterns lineno = 0 for line in lines length = len... | 12126 | def parse_gml_lines(lines, label, destringizer):
def tokenize():
patterns = ['[A-Za-z][0-9A-Za-z_]*\\b', '[+-]?(?:[0-9]*\\.[0-9]+|[0-9]+\\.[0-9]*)(?:[Ee][+-]?[0-9]+)?', '[+-]?[0-9]+', '".*?"', '\\[', '\\]', '#.*$|\\s+']
tokens = re.compile('|'.join(((('(' + pattern) + ')') for pattern in patterns)))
lineno = 0
... | Parse GML into a graph. | parse gml into a graph . | Question:
What does this function do?
Code:
def parse_gml_lines(lines, label, destringizer):
def tokenize():
patterns = ['[A-Za-z][0-9A-Za-z_]*\\b', '[+-]?(?:[0-9]*\\.[0-9]+|[0-9]+\\.[0-9]*)(?:[Ee][+-]?[0-9]+)?', '[+-]?[0-9]+', '".*?"', '\\[', '\\]', '#.*$|\\s+']
tokens = re.compile('|'.join(((('(' + pattern) +... |
null | null | null | What does this function do? | def build_request_with_data(url, data, api_key, method):
http_redirect_with_data_handler = HTTPRedirectWithDataHandler(method=method)
opener = urllib2.build_opener(http_redirect_with_data_handler)
urllib2.install_opener(opener)
url = make_url(url, api_key=api_key, args=None)
request = urllib2.Request(url, headers=... | null | null | null | Build a request with the received method. | pcsd | def build request with data url data api key method http redirect with data handler = HTTP Redirect With Data Handler method=method opener = urllib2 build opener http redirect with data handler urllib2 install opener opener url = make url url api key=api key args=None request = urllib2 Request url headers={'Content-Typ... | 12131 | def build_request_with_data(url, data, api_key, method):
http_redirect_with_data_handler = HTTPRedirectWithDataHandler(method=method)
opener = urllib2.build_opener(http_redirect_with_data_handler)
urllib2.install_opener(opener)
url = make_url(url, api_key=api_key, args=None)
request = urllib2.Request(url, headers=... | Build a request with the received method. | build a request with the received method . | Question:
What does this function do?
Code:
def build_request_with_data(url, data, api_key, method):
http_redirect_with_data_handler = HTTPRedirectWithDataHandler(method=method)
opener = urllib2.build_opener(http_redirect_with_data_handler)
urllib2.install_opener(opener)
url = make_url(url, api_key=api_key, args... |
null | null | null | What does this function do? | @app.route('/register', methods=['GET', 'POST'])
def register():
if g.user:
return redirect(url_for('timeline'))
error = None
if (request.method == 'POST'):
if (not request.form['username']):
error = 'You have to enter a username'
elif ((not request.form['email']) or ('@' not in request.form['email'])):
... | null | null | null | Registers the user. | pcsd | @app route '/register' methods=['GET' 'POST'] def register if g user return redirect url for 'timeline' error = None if request method == 'POST' if not request form['username'] error = 'You have to enter a username' elif not request form['email'] or '@' not in request form['email'] error = 'You have to enter a valid em... | 12132 | @app.route('/register', methods=['GET', 'POST'])
def register():
if g.user:
return redirect(url_for('timeline'))
error = None
if (request.method == 'POST'):
if (not request.form['username']):
error = 'You have to enter a username'
elif ((not request.form['email']) or ('@' not in request.form['email'])):
... | Registers the user. | registers the user . | Question:
What does this function do?
Code:
@app.route('/register', methods=['GET', 'POST'])
def register():
if g.user:
return redirect(url_for('timeline'))
error = None
if (request.method == 'POST'):
if (not request.form['username']):
error = 'You have to enter a username'
elif ((not request.form['email... |
null | null | null | What does this function do? | def cleanPolygon(elem, options):
global numPointsRemovedFromPolygon
pts = parseListOfPoints(elem.getAttribute('points'))
N = (len(pts) / 2)
if (N >= 2):
(startx, starty) = pts[:2]
(endx, endy) = pts[(-2):]
if ((startx == endx) and (starty == endy)):
del pts[(-2):]
numPointsRemovedFromPolygon += 1
elem.... | null | null | null | Remove unnecessary closing point of polygon points attribute | pcsd | def clean Polygon elem options global num Points Removed From Polygon pts = parse List Of Points elem get Attribute 'points' N = len pts / 2 if N >= 2 startx starty = pts[ 2] endx endy = pts[ -2 ] if startx == endx and starty == endy del pts[ -2 ] num Points Removed From Polygon += 1 elem set Attribute 'points' scour C... | 12144 | def cleanPolygon(elem, options):
global numPointsRemovedFromPolygon
pts = parseListOfPoints(elem.getAttribute('points'))
N = (len(pts) / 2)
if (N >= 2):
(startx, starty) = pts[:2]
(endx, endy) = pts[(-2):]
if ((startx == endx) and (starty == endy)):
del pts[(-2):]
numPointsRemovedFromPolygon += 1
elem.... | Remove unnecessary closing point of polygon points attribute | remove unnecessary closing point of polygon points attribute | Question:
What does this function do?
Code:
def cleanPolygon(elem, options):
global numPointsRemovedFromPolygon
pts = parseListOfPoints(elem.getAttribute('points'))
N = (len(pts) / 2)
if (N >= 2):
(startx, starty) = pts[:2]
(endx, endy) = pts[(-2):]
if ((startx == endx) and (starty == endy)):
del pts[(-... |
null | null | null | What does this function do? | def rws(t):
for c in [' DCTB ', '\n', ' ']:
t = t.replace(c, '')
return t
| null | null | null | Remove white spaces, tabs, and new lines from a string | pcsd | def rws t for c in [' DCTB ' ' ' ' '] t = t replace c '' return t | 12150 | def rws(t):
for c in [' DCTB ', '\n', ' ']:
t = t.replace(c, '')
return t
| Remove white spaces, tabs, and new lines from a string | remove white spaces , tabs , and new lines from a string | Question:
What does this function do?
Code:
def rws(t):
for c in [' DCTB ', '\n', ' ']:
t = t.replace(c, '')
return t
|
null | null | null | What does this function do? | @register.inclusion_tag('social/_activity_item.html')
def activity_item(action, **kwargs):
actor = action.actor
activity_class = 'activity'
verb = action.verb
username = actor.username
target = action.target
object_type = None
object = action.action_object
raw_action = get_data(action, 'raw_action')
object_nam... | null | null | null | Provides a location to manipulate an action in preparation for display. | pcsd | @register inclusion tag 'social/ activity item html' def activity item action **kwargs actor = action actor activity class = 'activity' verb = action verb username = actor username target = action target object type = None object = action action object raw action = get data action 'raw action' object name = get data ac... | 12155 | @register.inclusion_tag('social/_activity_item.html')
def activity_item(action, **kwargs):
actor = action.actor
activity_class = 'activity'
verb = action.verb
username = actor.username
target = action.target
object_type = None
object = action.action_object
raw_action = get_data(action, 'raw_action')
object_nam... | Provides a location to manipulate an action in preparation for display. | provides a location to manipulate an action in preparation for display . | Question:
What does this function do?
Code:
@register.inclusion_tag('social/_activity_item.html')
def activity_item(action, **kwargs):
actor = action.actor
activity_class = 'activity'
verb = action.verb
username = actor.username
target = action.target
object_type = None
object = action.action_object
raw_acti... |
null | null | null | What does this function do? | @gen.coroutine
def SavePhotos(client, obj_store, user_id, device_id, request):
request['user_id'] = user_id
(yield Activity.VerifyActivityId(client, user_id, device_id, request['activity']['activity_id']))
vp_ids = request.get('viewpoint_ids', [])
ep_dicts = request.get('episodes', [])
num_photos = 0
for ep_dict ... | null | null | null | Saves photos from existing episodes to new episodes in the current user\'s default
viewpoint. This is used to implement the "save photos to library" functionality. | pcsd | @gen coroutine def Save Photos client obj store user id device id request request['user id'] = user id yield Activity Verify Activity Id client user id device id request['activity']['activity id'] vp ids = request get 'viewpoint ids' [] ep dicts = request get 'episodes' [] num photos = 0 for ep dict in ep dicts yield E... | 12158 | @gen.coroutine
def SavePhotos(client, obj_store, user_id, device_id, request):
request['user_id'] = user_id
(yield Activity.VerifyActivityId(client, user_id, device_id, request['activity']['activity_id']))
vp_ids = request.get('viewpoint_ids', [])
ep_dicts = request.get('episodes', [])
num_photos = 0
for ep_dict ... | Saves photos from existing episodes to new episodes in the current user\'s default
viewpoint. This is used to implement the "save photos to library" functionality. | saves photos from existing episodes to new episodes in the current users default viewpoint . | Question:
What does this function do?
Code:
@gen.coroutine
def SavePhotos(client, obj_store, user_id, device_id, request):
request['user_id'] = user_id
(yield Activity.VerifyActivityId(client, user_id, device_id, request['activity']['activity_id']))
vp_ids = request.get('viewpoint_ids', [])
ep_dicts = request.ge... |
null | null | null | What does this function do? | def get_active_web_certificate(course, is_preview_mode=None):
certificates = getattr(course, 'certificates', '{}')
configurations = certificates.get('certificates', [])
for config in configurations:
if (config.get('is_active') or is_preview_mode):
return config
return None
| null | null | null | Retrieves the active web certificate configuration for the specified course | pcsd | def get active web certificate course is preview mode=None certificates = getattr course 'certificates' '{}' configurations = certificates get 'certificates' [] for config in configurations if config get 'is active' or is preview mode return config return None | 12159 | def get_active_web_certificate(course, is_preview_mode=None):
certificates = getattr(course, 'certificates', '{}')
configurations = certificates.get('certificates', [])
for config in configurations:
if (config.get('is_active') or is_preview_mode):
return config
return None
| Retrieves the active web certificate configuration for the specified course | retrieves the active web certificate configuration for the specified course | Question:
What does this function do?
Code:
def get_active_web_certificate(course, is_preview_mode=None):
certificates = getattr(course, 'certificates', '{}')
configurations = certificates.get('certificates', [])
for config in configurations:
if (config.get('is_active') or is_preview_mode):
return config
re... |
null | null | null | What does this function do? | def axis_reverse(a, axis=(-1)):
return axis_slice(a, step=(-1), axis=axis)
| null | null | null | Reverse the 1-d slices of `a` along axis `axis`. | pcsd | def axis reverse a axis= -1 return axis slice a step= -1 axis=axis | 12161 | def axis_reverse(a, axis=(-1)):
return axis_slice(a, step=(-1), axis=axis)
| Reverse the 1-d slices of `a` along axis `axis`. | reverse the 1 - d slices of a along axis axis . | Question:
What does this function do?
Code:
def axis_reverse(a, axis=(-1)):
return axis_slice(a, step=(-1), axis=axis)
|
null | null | null | What does this function do? | def db_sync(version=None):
return IMPL.db_sync(version=version)
| null | null | null | Migrate the database to `version` or the most recent version. | pcsd | def db sync version=None return IMPL db sync version=version | 12176 | def db_sync(version=None):
return IMPL.db_sync(version=version)
| Migrate the database to `version` or the most recent version. | migrate the database to version or the most recent version . | Question:
What does this function do?
Code:
def db_sync(version=None):
return IMPL.db_sync(version=version)
|
null | null | null | What does this function do? | def year_to_days(builder, year_val):
ret = cgutils.alloca_once(builder, TIMEDELTA64)
days = scale_by_constant(builder, year_val, 365)
with builder.if_else(cgutils.is_neg_int(builder, year_val)) as (if_neg, if_pos):
with if_pos:
from_1968 = add_constant(builder, year_val, 1)
p_days = builder.add(days, unscale... | null | null | null | Given a year *year_val* (offset to 1970), return the number of days
since the 1970 epoch. | pcsd | def year to days builder year val ret = cgutils alloca once builder TIMEDELTA64 days = scale by constant builder year val 365 with builder if else cgutils is neg int builder year val as if neg if pos with if pos from 1968 = add constant builder year val 1 p days = builder add days unscale by constant builder from 1968 ... | 12180 | def year_to_days(builder, year_val):
ret = cgutils.alloca_once(builder, TIMEDELTA64)
days = scale_by_constant(builder, year_val, 365)
with builder.if_else(cgutils.is_neg_int(builder, year_val)) as (if_neg, if_pos):
with if_pos:
from_1968 = add_constant(builder, year_val, 1)
p_days = builder.add(days, unscale... | Given a year *year_val* (offset to 1970), return the number of days
since the 1970 epoch. | given a year * year _ val * , return the number of days since the 1970 epoch . | Question:
What does this function do?
Code:
def year_to_days(builder, year_val):
ret = cgutils.alloca_once(builder, TIMEDELTA64)
days = scale_by_constant(builder, year_val, 365)
with builder.if_else(cgutils.is_neg_int(builder, year_val)) as (if_neg, if_pos):
with if_pos:
from_1968 = add_constant(builder, yea... |
null | null | null | What does this function do? | def getPointsFromSegmentTable(segmentTable):
points = []
endpoints = euclidean.getEndpointsFromSegmentTable(segmentTable)
for endpoint in endpoints:
points.append(endpoint.point)
return points
| null | null | null | Get the points from the segment table. | pcsd | def get Points From Segment Table segment Table points = [] endpoints = euclidean get Endpoints From Segment Table segment Table for endpoint in endpoints points append endpoint point return points | 12186 | def getPointsFromSegmentTable(segmentTable):
points = []
endpoints = euclidean.getEndpointsFromSegmentTable(segmentTable)
for endpoint in endpoints:
points.append(endpoint.point)
return points
| Get the points from the segment table. | get the points from the segment table . | Question:
What does this function do?
Code:
def getPointsFromSegmentTable(segmentTable):
points = []
endpoints = euclidean.getEndpointsFromSegmentTable(segmentTable)
for endpoint in endpoints:
points.append(endpoint.point)
return points
|
null | null | null | What does this function do? | def dict_to_xml(tag, d):
elem = Element(tag)
for (key, val) in d.items():
child = Element(key)
child.text = str(val)
elem.append(child)
return elem
| null | null | null | Turn a simple dict of key/value pairs into XML | pcsd | def dict to xml tag d elem = Element tag for key val in d items child = Element key child text = str val elem append child return elem | 12192 | def dict_to_xml(tag, d):
elem = Element(tag)
for (key, val) in d.items():
child = Element(key)
child.text = str(val)
elem.append(child)
return elem
| Turn a simple dict of key/value pairs into XML | turn a simple dict of key / value pairs into xml | Question:
What does this function do?
Code:
def dict_to_xml(tag, d):
elem = Element(tag)
for (key, val) in d.items():
child = Element(key)
child.text = str(val)
elem.append(child)
return elem
|
null | null | null | What does this function do? | @register.filter
def can_write(obj, user):
return obj.can_write(user)
| null | null | null | Takes article or related to article model.
Check if user can write article. | pcsd | @register filter def can write obj user return obj can write user | 12196 | @register.filter
def can_write(obj, user):
return obj.can_write(user)
| Takes article or related to article model.
Check if user can write article. | takes article or related to article model . | Question:
What does this function do?
Code:
@register.filter
def can_write(obj, user):
return obj.can_write(user)
|
null | null | null | What does this function do? | @handle_response_format
@treeio_login_required
@_process_mass_form
def folder_view(request, folder_id, response_format='html'):
folder = get_object_or_404(Folder, pk=folder_id)
if (not request.user.profile.has_permission(folder)):
return user_denied(request, message="You don't have access to this Folder")
query = ... | null | null | null | Single folder view page | pcsd | @handle response format @treeio login required @ process mass form def folder view request folder id response format='html' folder = get object or 404 Folder pk=folder id if not request user profile has permission folder return user denied request message="You don't have access to this Folder" query = Q object type='tr... | 12200 | @handle_response_format
@treeio_login_required
@_process_mass_form
def folder_view(request, folder_id, response_format='html'):
folder = get_object_or_404(Folder, pk=folder_id)
if (not request.user.profile.has_permission(folder)):
return user_denied(request, message="You don't have access to this Folder")
query = ... | Single folder view page | single folder view page | Question:
What does this function do?
Code:
@handle_response_format
@treeio_login_required
@_process_mass_form
def folder_view(request, folder_id, response_format='html'):
folder = get_object_or_404(Folder, pk=folder_id)
if (not request.user.profile.has_permission(folder)):
return user_denied(request, message="Y... |
null | null | null | What does this function do? | def organisation():
if settings.get_project_multiple_organisations():
s3db.configure('project_organisation', deletable=False, editable=False, insertable=False)
return s3_rest_controller()
else:
tabs = [(T('Basic Details'), None), (T('Projects'), 'project'), (T('Contacts'), 'human_resource')]
rheader = (lambda... | null | null | null | RESTful CRUD controller | pcsd | def organisation if settings get project multiple organisations s3db configure 'project organisation' deletable=False editable=False insertable=False return s3 rest controller else tabs = [ T 'Basic Details' None T 'Projects' 'project' T 'Contacts' 'human resource' ] rheader = lambda r s3db org rheader r tabs return s3... | 12205 | def organisation():
if settings.get_project_multiple_organisations():
s3db.configure('project_organisation', deletable=False, editable=False, insertable=False)
return s3_rest_controller()
else:
tabs = [(T('Basic Details'), None), (T('Projects'), 'project'), (T('Contacts'), 'human_resource')]
rheader = (lambda... | RESTful CRUD controller | restful crud controller | Question:
What does this function do?
Code:
def organisation():
if settings.get_project_multiple_organisations():
s3db.configure('project_organisation', deletable=False, editable=False, insertable=False)
return s3_rest_controller()
else:
tabs = [(T('Basic Details'), None), (T('Projects'), 'project'), (T('Con... |
null | null | null | What does this function do? | def _brick_get_connector_properties(multipath=False, enforce_multipath=False):
return DEFAULT_CONNECTOR
| null | null | null | Return a predefined connector object. | pcsd | def brick get connector properties multipath=False enforce multipath=False return DEFAULT CONNECTOR | 12207 | def _brick_get_connector_properties(multipath=False, enforce_multipath=False):
return DEFAULT_CONNECTOR
| Return a predefined connector object. | return a predefined connector object . | Question:
What does this function do?
Code:
def _brick_get_connector_properties(multipath=False, enforce_multipath=False):
return DEFAULT_CONNECTOR
|
null | null | null | What does this function do? | def _ipv4_to_bits(ipaddr):
return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')])
| null | null | null | Accepts an IPv4 dotted quad and returns a string representing its binary
counterpart | pcsd | def ipv4 to bits ipaddr return '' join [bin int x [2 ] rjust 8 '0' for x in ipaddr split ' ' ] | 12210 | def _ipv4_to_bits(ipaddr):
return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')])
| Accepts an IPv4 dotted quad and returns a string representing its binary
counterpart | accepts an ipv4 dotted quad and returns a string representing its binary counterpart | Question:
What does this function do?
Code:
def _ipv4_to_bits(ipaddr):
return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')])
|
null | null | null | What does this function do? | def get_generator_names_descriptions():
descs = []
for language in registered_languages:
for generator in language.html_generators:
description = getattr(generator, 'description', None)
if (description is None):
description = generator.name
descs.append((generator.name, description))
return descs
| null | null | null | Return a tuple of the name and description | pcsd | def get generator names descriptions descs = [] for language in registered languages for generator in language html generators description = getattr generator 'description' None if description is None description = generator name descs append generator name description return descs | 12212 | def get_generator_names_descriptions():
descs = []
for language in registered_languages:
for generator in language.html_generators:
description = getattr(generator, 'description', None)
if (description is None):
description = generator.name
descs.append((generator.name, description))
return descs
| Return a tuple of the name and description | return a tuple of the name and description | Question:
What does this function do?
Code:
def get_generator_names_descriptions():
descs = []
for language in registered_languages:
for generator in language.html_generators:
description = getattr(generator, 'description', None)
if (description is None):
description = generator.name
descs.append((g... |
null | null | null | What does this function do? | @pytest.fixture('module', APPS)
def app(request):
_app = APPS[request.param]
_app.name = request.param
try:
_app.live(kill_port=True)
except Exception as e:
pytest.exit(e.message)
request.addfinalizer((lambda : _app.die()))
return _app
| null | null | null | Starts and stops the server for each app in APPS | pcsd | @pytest fixture 'module' APPS def app request app = APPS[request param] app name = request param try app live kill port=True except Exception as e pytest exit e message request addfinalizer lambda app die return app | 12219 | @pytest.fixture('module', APPS)
def app(request):
_app = APPS[request.param]
_app.name = request.param
try:
_app.live(kill_port=True)
except Exception as e:
pytest.exit(e.message)
request.addfinalizer((lambda : _app.die()))
return _app
| Starts and stops the server for each app in APPS | starts and stops the server for each app in apps | Question:
What does this function do?
Code:
@pytest.fixture('module', APPS)
def app(request):
_app = APPS[request.param]
_app.name = request.param
try:
_app.live(kill_port=True)
except Exception as e:
pytest.exit(e.message)
request.addfinalizer((lambda : _app.die()))
return _app
|
null | null | null | What does this function do? | def remove_file(filename):
if os.path.exists(filename):
os.remove(filename)
| null | null | null | Remove a file if it exists | pcsd | def remove file filename if os path exists filename os remove filename | 12229 | def remove_file(filename):
if os.path.exists(filename):
os.remove(filename)
| Remove a file if it exists | remove a file if it exists | Question:
What does this function do?
Code:
def remove_file(filename):
if os.path.exists(filename):
os.remove(filename)
|
null | null | null | What does this function do? | def _hasSubstring(key, text):
escapedKey = re.escape(key)
return bool(re.search((('\\W' + escapedKey) + '\\W'), text))
| null | null | null | I return True if key is part of text. | pcsd | def has Substring key text escaped Key = re escape key return bool re search '\\W' + escaped Key + '\\W' text | 12230 | def _hasSubstring(key, text):
escapedKey = re.escape(key)
return bool(re.search((('\\W' + escapedKey) + '\\W'), text))
| I return True if key is part of text. | i return true if key is part of text . | Question:
What does this function do?
Code:
def _hasSubstring(key, text):
escapedKey = re.escape(key)
return bool(re.search((('\\W' + escapedKey) + '\\W'), text))
|
null | null | null | What does this function do? | def main():
fn_root = FLAGS.fn_root
img_fn_list = os.listdir(fn_root)
img_fn_list = [img_fn for img_fn in img_fn_list if img_fn.endswith('.webp')]
num_examples = len(img_fn_list)
n_examples_per_file = 10000
for (example_idx, img_fn) in enumerate(img_fn_list):
if ((example_idx % n_examples_per_file) == 0):
fi... | null | null | null | Main converter function. | pcsd | def main fn root = FLAGS fn root img fn list = os listdir fn root img fn list = [img fn for img fn in img fn list if img fn endswith ' webp' ] num examples = len img fn list n examples per file = 10000 for example idx img fn in enumerate img fn list if example idx % n examples per file == 0 file out = '%s %05d tfrecord... | 12233 | def main():
fn_root = FLAGS.fn_root
img_fn_list = os.listdir(fn_root)
img_fn_list = [img_fn for img_fn in img_fn_list if img_fn.endswith('.webp')]
num_examples = len(img_fn_list)
n_examples_per_file = 10000
for (example_idx, img_fn) in enumerate(img_fn_list):
if ((example_idx % n_examples_per_file) == 0):
fi... | Main converter function. | main converter function . | Question:
What does this function do?
Code:
def main():
fn_root = FLAGS.fn_root
img_fn_list = os.listdir(fn_root)
img_fn_list = [img_fn for img_fn in img_fn_list if img_fn.endswith('.webp')]
num_examples = len(img_fn_list)
n_examples_per_file = 10000
for (example_idx, img_fn) in enumerate(img_fn_list):
if ((... |
null | null | null | What does this function do? | def isunauthenticated(fnc):
return getattr(fnc, 'unauthenticated', False)
| null | null | null | Checks to see if the function is marked as not requiring authentication
with the @unauthenticated decorator. Returns True if decorator is
set to True, False otherwise. | pcsd | def isunauthenticated fnc return getattr fnc 'unauthenticated' False | 12234 | def isunauthenticated(fnc):
return getattr(fnc, 'unauthenticated', False)
| Checks to see if the function is marked as not requiring authentication
with the @unauthenticated decorator. Returns True if decorator is
set to True, False otherwise. | checks to see if the function is marked as not requiring authentication with the @ unauthenticated decorator . | Question:
What does this function do?
Code:
def isunauthenticated(fnc):
return getattr(fnc, 'unauthenticated', False)
|
null | null | null | What does this function do? | @slow_test
@testing.requires_testing_data
@requires_mne
def test_dipole_fitting():
amp = 1e-08
tempdir = _TempDir()
rng = np.random.RandomState(0)
fname_dtemp = op.join(tempdir, 'test.dip')
fname_sim = op.join(tempdir, 'test-ave.fif')
fwd = convert_forward_solution(read_forward_solution(fname_fwd), surf_ori=False... | null | null | null | Test dipole fitting. | pcsd | @slow test @testing requires testing data @requires mne def test dipole fitting amp = 1e-08 tempdir = Temp Dir rng = np random Random State 0 fname dtemp = op join tempdir 'test dip' fname sim = op join tempdir 'test-ave fif' fwd = convert forward solution read forward solution fname fwd surf ori=False force fixed=True... | 12235 | @slow_test
@testing.requires_testing_data
@requires_mne
def test_dipole_fitting():
amp = 1e-08
tempdir = _TempDir()
rng = np.random.RandomState(0)
fname_dtemp = op.join(tempdir, 'test.dip')
fname_sim = op.join(tempdir, 'test-ave.fif')
fwd = convert_forward_solution(read_forward_solution(fname_fwd), surf_ori=False... | Test dipole fitting. | test dipole fitting . | Question:
What does this function do?
Code:
@slow_test
@testing.requires_testing_data
@requires_mne
def test_dipole_fitting():
amp = 1e-08
tempdir = _TempDir()
rng = np.random.RandomState(0)
fname_dtemp = op.join(tempdir, 'test.dip')
fname_sim = op.join(tempdir, 'test-ave.fif')
fwd = convert_forward_solution(r... |
null | null | null | What does this function do? | def convert_db_torrent_to_json(torrent, include_rel_score=False):
torrent_name = torrent[2]
if ((torrent_name is None) or (len(torrent_name.strip()) == 0)):
torrent_name = 'Unnamed torrent'
res_json = {'id': torrent[0], 'infohash': torrent[1].encode('hex'), 'name': torrent_name, 'size': torrent[3], 'category': tor... | null | null | null | This method converts a torrent in the database to a JSON dictionary. | pcsd | def convert db torrent to json torrent include rel score=False torrent name = torrent[2] if torrent name is None or len torrent name strip == 0 torrent name = 'Unnamed torrent' res json = {'id' torrent[0] 'infohash' torrent[1] encode 'hex' 'name' torrent name 'size' torrent[3] 'category' torrent[4] 'num seeders' torren... | 12239 | def convert_db_torrent_to_json(torrent, include_rel_score=False):
torrent_name = torrent[2]
if ((torrent_name is None) or (len(torrent_name.strip()) == 0)):
torrent_name = 'Unnamed torrent'
res_json = {'id': torrent[0], 'infohash': torrent[1].encode('hex'), 'name': torrent_name, 'size': torrent[3], 'category': tor... | This method converts a torrent in the database to a JSON dictionary. | this method converts a torrent in the database to a json dictionary . | Question:
What does this function do?
Code:
def convert_db_torrent_to_json(torrent, include_rel_score=False):
torrent_name = torrent[2]
if ((torrent_name is None) or (len(torrent_name.strip()) == 0)):
torrent_name = 'Unnamed torrent'
res_json = {'id': torrent[0], 'infohash': torrent[1].encode('hex'), 'name': to... |
null | null | null | What does this function do? | def get_port_from_device(device):
LOG.debug(_('get_port_from_device() called'))
session = db.get_session()
sg_binding_port = sg_db.SecurityGroupPortBinding.port_id
query = session.query(models_v2.Port, sg_db.SecurityGroupPortBinding.security_group_id)
query = query.outerjoin(sg_db.SecurityGroupPortBinding, (models... | null | null | null | Get port from database | pcsd | def get port from device device LOG debug 'get port from device called' session = db get session sg binding port = sg db Security Group Port Binding port id query = session query models v2 Port sg db Security Group Port Binding security group id query = query outerjoin sg db Security Group Port Binding models v2 Port i... | 12245 | def get_port_from_device(device):
LOG.debug(_('get_port_from_device() called'))
session = db.get_session()
sg_binding_port = sg_db.SecurityGroupPortBinding.port_id
query = session.query(models_v2.Port, sg_db.SecurityGroupPortBinding.security_group_id)
query = query.outerjoin(sg_db.SecurityGroupPortBinding, (models... | Get port from database | get port from database | Question:
What does this function do?
Code:
def get_port_from_device(device):
LOG.debug(_('get_port_from_device() called'))
session = db.get_session()
sg_binding_port = sg_db.SecurityGroupPortBinding.port_id
query = session.query(models_v2.Port, sg_db.SecurityGroupPortBinding.security_group_id)
query = query.ou... |
null | null | null | What does this function do? | def get_git_version():
version = get_cmd_output('git --version').strip().split()[2]
version = '.'.join(version.split('.')[0:2])
return float(version)
| null | null | null | returns git version from `git --version`
extracts version number from string `get version 1.9.1` etc | pcsd | def get git version version = get cmd output 'git --version' strip split [2] version = ' ' join version split ' ' [0 2] return float version | 12252 | def get_git_version():
version = get_cmd_output('git --version').strip().split()[2]
version = '.'.join(version.split('.')[0:2])
return float(version)
| returns git version from `git --version`
extracts version number from string `get version 1.9.1` etc | returns git version from git - - version extracts version number from string get version 1 . 9 . 1 etc | Question:
What does this function do?
Code:
def get_git_version():
version = get_cmd_output('git --version').strip().split()[2]
version = '.'.join(version.split('.')[0:2])
return float(version)
|
null | null | null | What does this function do? | def call_fp_intrinsic(builder, name, args):
mod = builder.module
intr = lc.Function.intrinsic(mod, name, [a.type for a in args])
return builder.call(intr, args)
| null | null | null | Call a LLVM intrinsic floating-point operation. | pcsd | def call fp intrinsic builder name args mod = builder module intr = lc Function intrinsic mod name [a type for a in args] return builder call intr args | 12256 | def call_fp_intrinsic(builder, name, args):
mod = builder.module
intr = lc.Function.intrinsic(mod, name, [a.type for a in args])
return builder.call(intr, args)
| Call a LLVM intrinsic floating-point operation. | call a llvm intrinsic floating - point operation . | Question:
What does this function do?
Code:
def call_fp_intrinsic(builder, name, args):
mod = builder.module
intr = lc.Function.intrinsic(mod, name, [a.type for a in args])
return builder.call(intr, args)
|
null | null | null | What does this function do? | def interactive():
print 'Compute digits of pi with SymPy\n'
base = input('Which base? (2-36, 10 for decimal) \n> ')
digits = input('How many digits? (enter a big number, say, 10000)\n> ')
tofile = raw_input('Output to file? (enter a filename, or just press enter\nto print directly to the screen) \n> ')
if tofile:... | null | null | null | Simple function to interact with user | pcsd | def interactive print 'Compute digits of pi with Sym Py ' base = input 'Which base? 2-36 10 for decimal > ' digits = input 'How many digits? enter a big number say 10000 > ' tofile = raw input 'Output to file? enter a filename or just press enter to print directly to the screen > ' if tofile tofile = open tofile 'w' ca... | 12268 | def interactive():
print 'Compute digits of pi with SymPy\n'
base = input('Which base? (2-36, 10 for decimal) \n> ')
digits = input('How many digits? (enter a big number, say, 10000)\n> ')
tofile = raw_input('Output to file? (enter a filename, or just press enter\nto print directly to the screen) \n> ')
if tofile:... | Simple function to interact with user | simple function to interact with user | Question:
What does this function do?
Code:
def interactive():
print 'Compute digits of pi with SymPy\n'
base = input('Which base? (2-36, 10 for decimal) \n> ')
digits = input('How many digits? (enter a big number, say, 10000)\n> ')
tofile = raw_input('Output to file? (enter a filename, or just press enter\nto p... |
null | null | null | What does this function do? | def action_peek_xml(body):
dom = xmlutil.safe_minidom_parse_string(body)
action_node = dom.childNodes[0]
return action_node.tagName
| null | null | null | Determine action to invoke. | pcsd | def action peek xml body dom = xmlutil safe minidom parse string body action node = dom child Nodes[0] return action node tag Name | 12278 | def action_peek_xml(body):
dom = xmlutil.safe_minidom_parse_string(body)
action_node = dom.childNodes[0]
return action_node.tagName
| Determine action to invoke. | determine action to invoke . | Question:
What does this function do?
Code:
def action_peek_xml(body):
dom = xmlutil.safe_minidom_parse_string(body)
action_node = dom.childNodes[0]
return action_node.tagName
|
null | null | null | What does this function do? | def query_db(query, args=(), one=False):
cur = sqldb.execute(query, args)
rv = cur.fetchall()
return ((rv[0] if rv else None) if one else rv)
| null | null | null | Queries the database and returns a list of dictionaries. | pcsd | def query db query args= one=False cur = sqldb execute query args rv = cur fetchall return rv[0] if rv else None if one else rv | 12283 | def query_db(query, args=(), one=False):
cur = sqldb.execute(query, args)
rv = cur.fetchall()
return ((rv[0] if rv else None) if one else rv)
| Queries the database and returns a list of dictionaries. | queries the database and returns a list of dictionaries . | Question:
What does this function do?
Code:
def query_db(query, args=(), one=False):
cur = sqldb.execute(query, args)
rv = cur.fetchall()
return ((rv[0] if rv else None) if one else rv)
|
null | null | null | What does this function do? | def user_home(request):
return shortcuts.redirect(horizon.get_user_home(request.user))
| null | null | null | Reversible named view to direct a user to the appropriate homepage. | pcsd | def user home request return shortcuts redirect horizon get user home request user | 12286 | def user_home(request):
return shortcuts.redirect(horizon.get_user_home(request.user))
| Reversible named view to direct a user to the appropriate homepage. | reversible named view to direct a user to the appropriate homepage . | Question:
What does this function do?
Code:
def user_home(request):
return shortcuts.redirect(horizon.get_user_home(request.user))
|
null | null | null | What does this function do? | def get_ssh_certificate_tokens(module, ssh_cert_path):
(rc, stdout, stderr) = module.run_command(['openssl', 'x509', '-in', ssh_cert_path, '-fingerprint', '-noout'])
if (rc != 0):
module.fail_json(msg=('failed to generate the key fingerprint, error was: %s' % stderr))
fingerprint = stdout.strip()[17:].replace(':',... | null | null | null | Returns the sha1 fingerprint and a base64-encoded PKCS12 version of the certificate. | pcsd | def get ssh certificate tokens module ssh cert path rc stdout stderr = module run command ['openssl' 'x509' '-in' ssh cert path '-fingerprint' '-noout'] if rc != 0 module fail json msg= 'failed to generate the key fingerprint error was %s' % stderr fingerprint = stdout strip [17 ] replace ' ' '' rc stdout stderr = modu... | 12291 | def get_ssh_certificate_tokens(module, ssh_cert_path):
(rc, stdout, stderr) = module.run_command(['openssl', 'x509', '-in', ssh_cert_path, '-fingerprint', '-noout'])
if (rc != 0):
module.fail_json(msg=('failed to generate the key fingerprint, error was: %s' % stderr))
fingerprint = stdout.strip()[17:].replace(':',... | Returns the sha1 fingerprint and a base64-encoded PKCS12 version of the certificate. | returns the sha1 fingerprint and a base64 - encoded pkcs12 version of the certificate . | Question:
What does this function do?
Code:
def get_ssh_certificate_tokens(module, ssh_cert_path):
(rc, stdout, stderr) = module.run_command(['openssl', 'x509', '-in', ssh_cert_path, '-fingerprint', '-noout'])
if (rc != 0):
module.fail_json(msg=('failed to generate the key fingerprint, error was: %s' % stderr))
... |
null | null | null | What does this function do? | def match_filter(filter_list, userargs):
found_filter = None
for f in filter_list:
if f.match(userargs):
if isinstance(f, filters.ExecCommandFilter):
leaf_filters = [fltr for fltr in filter_list if (not isinstance(fltr, filters.ExecCommandFilter))]
args = f.exec_args(userargs)
if ((not args) or (not ... | null | null | null | Checks user command and arguments through command filters and
returns the first matching filter, or None is none matched. | pcsd | def match filter filter list userargs found filter = None for f in filter list if f match userargs if isinstance f filters Exec Command Filter leaf filters = [fltr for fltr in filter list if not isinstance fltr filters Exec Command Filter ] args = f exec args userargs if not args or not match filter leaf filters args c... | 12296 | def match_filter(filter_list, userargs):
found_filter = None
for f in filter_list:
if f.match(userargs):
if isinstance(f, filters.ExecCommandFilter):
leaf_filters = [fltr for fltr in filter_list if (not isinstance(fltr, filters.ExecCommandFilter))]
args = f.exec_args(userargs)
if ((not args) or (not ... | Checks user command and arguments through command filters and
returns the first matching filter, or None is none matched. | checks user command and arguments through command filters and returns the first matching filter , or none is none matched . | Question:
What does this function do?
Code:
def match_filter(filter_list, userargs):
found_filter = None
for f in filter_list:
if f.match(userargs):
if isinstance(f, filters.ExecCommandFilter):
leaf_filters = [fltr for fltr in filter_list if (not isinstance(fltr, filters.ExecCommandFilter))]
args = f.... |
null | null | null | What does this function do? | def simpleOpenIDTransformer(endpoint):
if ('http://openid.net/signon/1.0' not in endpoint.type_uris):
return None
delegates = list(endpoint.service_element.findall('{http://openid.net/xmlns/1.0}Delegate'))
assert (len(delegates) == 1)
delegate = delegates[0].text
return (endpoint.uri, delegate)
| null | null | null | Function to extract information from an OpenID service element | pcsd | def simple Open ID Transformer endpoint if 'http //openid net/signon/1 0' not in endpoint type uris return None delegates = list endpoint service element findall '{http //openid net/xmlns/1 0}Delegate' assert len delegates == 1 delegate = delegates[0] text return endpoint uri delegate | 12308 | def simpleOpenIDTransformer(endpoint):
if ('http://openid.net/signon/1.0' not in endpoint.type_uris):
return None
delegates = list(endpoint.service_element.findall('{http://openid.net/xmlns/1.0}Delegate'))
assert (len(delegates) == 1)
delegate = delegates[0].text
return (endpoint.uri, delegate)
| Function to extract information from an OpenID service element | function to extract information from an openid service element | Question:
What does this function do?
Code:
def simpleOpenIDTransformer(endpoint):
if ('http://openid.net/signon/1.0' not in endpoint.type_uris):
return None
delegates = list(endpoint.service_element.findall('{http://openid.net/xmlns/1.0}Delegate'))
assert (len(delegates) == 1)
delegate = delegates[0].text
re... |
null | null | null | What does this function do? | def _weight_func(dist):
with np.errstate(divide='ignore'):
retval = (1.0 / dist)
return (retval ** 2)
| null | null | null | Weight function to replace lambda d: d ** -2.
The lambda function is not valid because:
if d==0 then 0^-2 is not valid. | pcsd | def weight func dist with np errstate divide='ignore' retval = 1 0 / dist return retval ** 2 | 12316 | def _weight_func(dist):
with np.errstate(divide='ignore'):
retval = (1.0 / dist)
return (retval ** 2)
| Weight function to replace lambda d: d ** -2.
The lambda function is not valid because:
if d==0 then 0^-2 is not valid. | weight function to replace lambda d : d * * - 2 . | Question:
What does this function do?
Code:
def _weight_func(dist):
with np.errstate(divide='ignore'):
retval = (1.0 / dist)
return (retval ** 2)
|
null | null | null | What does this function do? | def assert_ok(response, msg_prefix=u''):
return assert_code(response, 200, msg_prefix=msg_prefix)
| null | null | null | Assert the response was returned with status 200 (OK). | pcsd | def assert ok response msg prefix=u'' return assert code response 200 msg prefix=msg prefix | 12322 | def assert_ok(response, msg_prefix=u''):
return assert_code(response, 200, msg_prefix=msg_prefix)
| Assert the response was returned with status 200 (OK). | assert the response was returned with status 200 . | Question:
What does this function do?
Code:
def assert_ok(response, msg_prefix=u''):
return assert_code(response, 200, msg_prefix=msg_prefix)
|
null | null | null | What does this function do? | @pytest.mark.django_db
def test_apiview_search(rf):
view = UserAPIView.as_view()
UserFactory.create(username='foo', full_name='Foo Bar')
UserFactory.create(username='foobar', full_name='Foo Bar')
UserFactory.create(username='foobarbaz', full_name='Foo Bar')
request = create_api_request(rf, url='/?q=bar')
response... | null | null | null | Tests filtering through a search query. | pcsd | @pytest mark django db def test apiview search rf view = User API View as view User Factory create username='foo' full name='Foo Bar' User Factory create username='foobar' full name='Foo Bar' User Factory create username='foobarbaz' full name='Foo Bar' request = create api request rf url='/?q=bar' response = view reque... | 12327 | @pytest.mark.django_db
def test_apiview_search(rf):
view = UserAPIView.as_view()
UserFactory.create(username='foo', full_name='Foo Bar')
UserFactory.create(username='foobar', full_name='Foo Bar')
UserFactory.create(username='foobarbaz', full_name='Foo Bar')
request = create_api_request(rf, url='/?q=bar')
response... | Tests filtering through a search query. | tests filtering through a search query . | Question:
What does this function do?
Code:
@pytest.mark.django_db
def test_apiview_search(rf):
view = UserAPIView.as_view()
UserFactory.create(username='foo', full_name='Foo Bar')
UserFactory.create(username='foobar', full_name='Foo Bar')
UserFactory.create(username='foobarbaz', full_name='Foo Bar')
request = ... |
null | null | null | What does this function do? | @utils.arg('server', metavar='<server>', help=_('Name or ID of server.'))
def do_reset_network(cs, args):
_find_server(cs, args.server).reset_network()
| null | null | null | Reset network of a server. | pcsd | @utils arg 'server' metavar='<server>' help= 'Name or ID of server ' def do reset network cs args find server cs args server reset network | 12333 | @utils.arg('server', metavar='<server>', help=_('Name or ID of server.'))
def do_reset_network(cs, args):
_find_server(cs, args.server).reset_network()
| Reset network of a server. | reset network of a server . | Question:
What does this function do?
Code:
@utils.arg('server', metavar='<server>', help=_('Name or ID of server.'))
def do_reset_network(cs, args):
_find_server(cs, args.server).reset_network()
|
null | null | null | What does this function do? | def simple_keyword():
print 'You have used the simplest keyword.'
| null | null | null | Log a message | pcsd | def simple keyword print 'You have used the simplest keyword ' | 12342 | def simple_keyword():
print 'You have used the simplest keyword.'
| Log a message | log a message | Question:
What does this function do?
Code:
def simple_keyword():
print 'You have used the simplest keyword.'
|
null | null | null | What does this function do? | def haystack_get_app_modules():
return [i.module for i in apps.get_app_configs()]
| null | null | null | Return the Python module for each installed app | pcsd | def haystack get app modules return [i module for i in apps get app configs ] | 12344 | def haystack_get_app_modules():
return [i.module for i in apps.get_app_configs()]
| Return the Python module for each installed app | return the python module for each installed app | Question:
What does this function do?
Code:
def haystack_get_app_modules():
return [i.module for i in apps.get_app_configs()]
|
null | null | null | What does this function do? | def PrintPosition(pos, with_returns=False):
print ' Position :', pos.position_title
print ' Ticker ID :', pos.ticker_id
print ' Symbol :', pos.symbol
print ' Last updated :', pos.updated.text
d = pos.position_data
print ' Shares :', d.shares
if with_returns:
print ' Ga... | null | null | null | Print single position. | pcsd | def Print Position pos with returns=False print ' Position ' pos position title print ' Ticker ID ' pos ticker id print ' Symbol ' pos symbol print ' Last updated ' pos updated text d = pos position data print ' Shares ' d shares if with returns print ' Gain % ' d gain percentage Pr Rtn ' Returns ' d print ' Cost basis... | 12350 | def PrintPosition(pos, with_returns=False):
print ' Position :', pos.position_title
print ' Ticker ID :', pos.ticker_id
print ' Symbol :', pos.symbol
print ' Last updated :', pos.updated.text
d = pos.position_data
print ' Shares :', d.shares
if with_returns:
print ' Ga... | Print single position. | print single position . | Question:
What does this function do?
Code:
def PrintPosition(pos, with_returns=False):
print ' Position :', pos.position_title
print ' Ticker ID :', pos.ticker_id
print ' Symbol :', pos.symbol
print ' Last updated :', pos.updated.text
d = pos.position_data
print ' Shares ... |
null | null | null | What does this function do? | def twitter():
s3db.configure('msg_twitter', editable=False, insertable=False, list_fields=['id', 'date', 'from_address', 'to_address', 'body'])
return s3_rest_controller()
| null | null | null | Twitter RESTful Controller
@ToDo: Action Button to update async | pcsd | def twitter s3db configure 'msg twitter' editable=False insertable=False list fields=['id' 'date' 'from address' 'to address' 'body'] return s3 rest controller | 12360 | def twitter():
s3db.configure('msg_twitter', editable=False, insertable=False, list_fields=['id', 'date', 'from_address', 'to_address', 'body'])
return s3_rest_controller()
| Twitter RESTful Controller
@ToDo: Action Button to update async | twitter restful controller | Question:
What does this function do?
Code:
def twitter():
s3db.configure('msg_twitter', editable=False, insertable=False, list_fields=['id', 'date', 'from_address', 'to_address', 'body'])
return s3_rest_controller()
|
null | null | null | What does this function do? | def download_plugin(file_):
global PLUGIN_EXTENSION
plugins_installed_before = set(__get_all_plugin_descriptors())
fileName = os.path.join(resources.PLUGINS, os.path.basename(file_))
content = urlopen(file_)
f = open(fileName, u'wb')
f.write(content.read())
f.close()
zipFile = zipfile.ZipFile(fileName, u'r')
z... | null | null | null | Download a plugin specified by file_ | pcsd | def download plugin file global PLUGIN EXTENSION plugins installed before = set get all plugin descriptors file Name = os path join resources PLUGINS os path basename file content = urlopen file f = open file Name u'wb' f write content read f close zip File = zipfile Zip File file Name u'r' zip File extractall resource... | 12364 | def download_plugin(file_):
global PLUGIN_EXTENSION
plugins_installed_before = set(__get_all_plugin_descriptors())
fileName = os.path.join(resources.PLUGINS, os.path.basename(file_))
content = urlopen(file_)
f = open(fileName, u'wb')
f.write(content.read())
f.close()
zipFile = zipfile.ZipFile(fileName, u'r')
z... | Download a plugin specified by file_ | download a plugin specified by file _ | Question:
What does this function do?
Code:
def download_plugin(file_):
global PLUGIN_EXTENSION
plugins_installed_before = set(__get_all_plugin_descriptors())
fileName = os.path.join(resources.PLUGINS, os.path.basename(file_))
content = urlopen(file_)
f = open(fileName, u'wb')
f.write(content.read())
f.close(... |
null | null | null | What does this function do? | def vote(r, **attr):
problem = r.record
duser = s3db.delphi_DelphiUser(problem.group_id)
rheader = problem_rheader(r)
stable = s3db.delphi_solution
query = (stable.problem_id == problem.id)
rows = db(query).select(stable.id, stable.name)
options = Storage()
for row in rows:
options[row.id] = row.name
if duse... | null | null | null | Custom Method to allow Voting on Solutions to a Problem | pcsd | def vote r **attr problem = r record duser = s3db delphi Delphi User problem group id rheader = problem rheader r stable = s3db delphi solution query = stable problem id == problem id rows = db query select stable id stable name options = Storage for row in rows options[row id] = row name if duser user id vtable = s3db... | 12374 | def vote(r, **attr):
problem = r.record
duser = s3db.delphi_DelphiUser(problem.group_id)
rheader = problem_rheader(r)
stable = s3db.delphi_solution
query = (stable.problem_id == problem.id)
rows = db(query).select(stable.id, stable.name)
options = Storage()
for row in rows:
options[row.id] = row.name
if duse... | Custom Method to allow Voting on Solutions to a Problem | custom method to allow voting on solutions to a problem | Question:
What does this function do?
Code:
def vote(r, **attr):
problem = r.record
duser = s3db.delphi_DelphiUser(problem.group_id)
rheader = problem_rheader(r)
stable = s3db.delphi_solution
query = (stable.problem_id == problem.id)
rows = db(query).select(stable.id, stable.name)
options = Storage()
for row... |
null | null | null | What does this function do? | @get('/scan/<taskid>/log')
def scan_log(taskid):
json_log_messages = list()
if (taskid not in DataStore.tasks):
logger.warning(('[%s] Invalid task ID provided to scan_log()' % taskid))
return jsonize({'success': False, 'message': 'Invalid task ID'})
for (time_, level, message) in DataStore.current_db.execute('SE... | null | null | null | Retrieve the log messages | pcsd | @get '/scan/<taskid>/log' def scan log taskid json log messages = list if taskid not in Data Store tasks logger warning '[%s] Invalid task ID provided to scan log ' % taskid return jsonize {'success' False 'message' 'Invalid task ID'} for time level message in Data Store current db execute 'SELECT time level message FR... | 12375 | @get('/scan/<taskid>/log')
def scan_log(taskid):
json_log_messages = list()
if (taskid not in DataStore.tasks):
logger.warning(('[%s] Invalid task ID provided to scan_log()' % taskid))
return jsonize({'success': False, 'message': 'Invalid task ID'})
for (time_, level, message) in DataStore.current_db.execute('SE... | Retrieve the log messages | retrieve the log messages | Question:
What does this function do?
Code:
@get('/scan/<taskid>/log')
def scan_log(taskid):
json_log_messages = list()
if (taskid not in DataStore.tasks):
logger.warning(('[%s] Invalid task ID provided to scan_log()' % taskid))
return jsonize({'success': False, 'message': 'Invalid task ID'})
for (time_, leve... |
null | null | null | What does this function do? | def _diff(old_pipeline_definition, new_pipeline_definition):
old_pipeline_definition.pop('ResponseMetadata', None)
new_pipeline_definition.pop('ResponseMetadata', None)
diff = difflib.unified_diff(json.dumps(old_pipeline_definition, indent=4).splitlines(1), json.dumps(new_pipeline_definition, indent=4).splitlines(1)... | null | null | null | Return string diff of pipeline definitions. | pcsd | def diff old pipeline definition new pipeline definition old pipeline definition pop 'Response Metadata' None new pipeline definition pop 'Response Metadata' None diff = difflib unified diff json dumps old pipeline definition indent=4 splitlines 1 json dumps new pipeline definition indent=4 splitlines 1 return '' join ... | 12376 | def _diff(old_pipeline_definition, new_pipeline_definition):
old_pipeline_definition.pop('ResponseMetadata', None)
new_pipeline_definition.pop('ResponseMetadata', None)
diff = difflib.unified_diff(json.dumps(old_pipeline_definition, indent=4).splitlines(1), json.dumps(new_pipeline_definition, indent=4).splitlines(1)... | Return string diff of pipeline definitions. | return string diff of pipeline definitions . | Question:
What does this function do?
Code:
def _diff(old_pipeline_definition, new_pipeline_definition):
old_pipeline_definition.pop('ResponseMetadata', None)
new_pipeline_definition.pop('ResponseMetadata', None)
diff = difflib.unified_diff(json.dumps(old_pipeline_definition, indent=4).splitlines(1), json.dumps(n... |
null | null | null | What does this function do? | def create_logger(path=None, format_=None, name=None):
global logger
logger = getLogger((name or DEFAULT_LOGGER_NAME))
logger.propagate = False
if (not logger.handlers):
formatter = Formatter(fmt=(format_ or DEFAULT_FORMAT))
if path:
handler = FileHandler(path)
else:
handler = StreamHandler()
handler.... | null | null | null | Create a default logger | pcsd | def create logger path=None format =None name=None global logger logger = get Logger name or DEFAULT LOGGER NAME logger propagate = False if not logger handlers formatter = Formatter fmt= format or DEFAULT FORMAT if path handler = File Handler path else handler = Stream Handler handler set Formatter formatter logger ad... | 12381 | def create_logger(path=None, format_=None, name=None):
global logger
logger = getLogger((name or DEFAULT_LOGGER_NAME))
logger.propagate = False
if (not logger.handlers):
formatter = Formatter(fmt=(format_ or DEFAULT_FORMAT))
if path:
handler = FileHandler(path)
else:
handler = StreamHandler()
handler.... | Create a default logger | create a default logger | Question:
What does this function do?
Code:
def create_logger(path=None, format_=None, name=None):
global logger
logger = getLogger((name or DEFAULT_LOGGER_NAME))
logger.propagate = False
if (not logger.handlers):
formatter = Formatter(fmt=(format_ or DEFAULT_FORMAT))
if path:
handler = FileHandler(path)
... |
null | null | null | What does this function do? | def init_params(options):
params = OrderedDict()
params['Wemb'] = norm_weight(options['n_words_src'], options['dim_word'])
params = get_layer(options['encoder'])[0](options, params, prefix='encoder', nin=options['dim_word'], dim=options['dim'])
return params
| null | null | null | initialize all parameters needed for the encoder | pcsd | def init params options params = Ordered Dict params['Wemb'] = norm weight options['n words src'] options['dim word'] params = get layer options['encoder'] [0] options params prefix='encoder' nin=options['dim word'] dim=options['dim'] return params | 12384 | def init_params(options):
params = OrderedDict()
params['Wemb'] = norm_weight(options['n_words_src'], options['dim_word'])
params = get_layer(options['encoder'])[0](options, params, prefix='encoder', nin=options['dim_word'], dim=options['dim'])
return params
| initialize all parameters needed for the encoder | initialize all parameters needed for the encoder | Question:
What does this function do?
Code:
def init_params(options):
params = OrderedDict()
params['Wemb'] = norm_weight(options['n_words_src'], options['dim_word'])
params = get_layer(options['encoder'])[0](options, params, prefix='encoder', nin=options['dim_word'], dim=options['dim'])
return params
|
null | null | null | What does this function do? | def get_parsed(text):
return str(TemplateParser(text))
| null | null | null | Returns the indented python code of text. Useful for unit testing. | pcsd | def get parsed text return str Template Parser text | 12386 | def get_parsed(text):
return str(TemplateParser(text))
| Returns the indented python code of text. Useful for unit testing. | returns the indented python code of text . | Question:
What does this function do?
Code:
def get_parsed(text):
return str(TemplateParser(text))
|
null | null | null | What does this function do? | def load_all(stream, Loader=Loader):
loader = Loader(stream)
while loader.check_data():
(yield loader.get_data())
| null | null | null | Parse all YAML documents in a stream
and produce corresponding Python objects. | pcsd | def load all stream Loader=Loader loader = Loader stream while loader check data yield loader get data | 12387 | def load_all(stream, Loader=Loader):
loader = Loader(stream)
while loader.check_data():
(yield loader.get_data())
| Parse all YAML documents in a stream
and produce corresponding Python objects. | parse all yaml documents in a stream and produce corresponding python objects . | Question:
What does this function do?
Code:
def load_all(stream, Loader=Loader):
loader = Loader(stream)
while loader.check_data():
(yield loader.get_data())
|
null | null | null | What does this function do? | @testing.requires_testing_data
@requires_mne
def test_average_forward_solution():
temp_dir = _TempDir()
fwd = read_forward_solution(fname_meeg)
assert_raises(TypeError, average_forward_solutions, 1)
assert_raises(ValueError, average_forward_solutions, [])
assert_raises(ValueError, average_forward_solutions, [fwd, ... | null | null | null | Test averaging forward solutions | pcsd | @testing requires testing data @requires mne def test average forward solution temp dir = Temp Dir fwd = read forward solution fname meeg assert raises Type Error average forward solutions 1 assert raises Value Error average forward solutions [] assert raises Value Error average forward solutions [fwd fwd] [ -1 0] asse... | 12394 | @testing.requires_testing_data
@requires_mne
def test_average_forward_solution():
temp_dir = _TempDir()
fwd = read_forward_solution(fname_meeg)
assert_raises(TypeError, average_forward_solutions, 1)
assert_raises(ValueError, average_forward_solutions, [])
assert_raises(ValueError, average_forward_solutions, [fwd, ... | Test averaging forward solutions | test averaging forward solutions | Question:
What does this function do?
Code:
@testing.requires_testing_data
@requires_mne
def test_average_forward_solution():
temp_dir = _TempDir()
fwd = read_forward_solution(fname_meeg)
assert_raises(TypeError, average_forward_solutions, 1)
assert_raises(ValueError, average_forward_solutions, [])
assert_raise... |
null | null | null | What does this function do? | @cmd
def coverage():
install()
sh(('%s -m coverage run %s' % (PYTHON, TSCRIPT)))
sh(('%s -m coverage report' % PYTHON))
sh(('%s -m coverage html' % PYTHON))
sh(('%s -m webbrowser -t htmlcov/index.html' % PYTHON))
| null | null | null | Run coverage tests. | pcsd | @cmd def coverage install sh '%s -m coverage run %s' % PYTHON TSCRIPT sh '%s -m coverage report' % PYTHON sh '%s -m coverage html' % PYTHON sh '%s -m webbrowser -t htmlcov/index html' % PYTHON | 12395 | @cmd
def coverage():
install()
sh(('%s -m coverage run %s' % (PYTHON, TSCRIPT)))
sh(('%s -m coverage report' % PYTHON))
sh(('%s -m coverage html' % PYTHON))
sh(('%s -m webbrowser -t htmlcov/index.html' % PYTHON))
| Run coverage tests. | run coverage tests . | Question:
What does this function do?
Code:
@cmd
def coverage():
install()
sh(('%s -m coverage run %s' % (PYTHON, TSCRIPT)))
sh(('%s -m coverage report' % PYTHON))
sh(('%s -m coverage html' % PYTHON))
sh(('%s -m webbrowser -t htmlcov/index.html' % PYTHON))
|
null | null | null | What does this function do? | def assertDimensions(self, x, y, w, h, win=None):
if (win is None):
win = self.c.window
info = win.info()
assert (info['x'] == x), info
assert (info['y'] == y), info
assert (info['width'] == w), info
assert (info['height'] == h), info
| null | null | null | Asserts dimensions of window | pcsd | def assert Dimensions self x y w h win=None if win is None win = self c window info = win info assert info['x'] == x info assert info['y'] == y info assert info['width'] == w info assert info['height'] == h info | 12401 | def assertDimensions(self, x, y, w, h, win=None):
if (win is None):
win = self.c.window
info = win.info()
assert (info['x'] == x), info
assert (info['y'] == y), info
assert (info['width'] == w), info
assert (info['height'] == h), info
| Asserts dimensions of window | asserts dimensions of window | Question:
What does this function do?
Code:
def assertDimensions(self, x, y, w, h, win=None):
if (win is None):
win = self.c.window
info = win.info()
assert (info['x'] == x), info
assert (info['y'] == y), info
assert (info['width'] == w), info
assert (info['height'] == h), info
|
null | null | null | What does this function do? | def incr_ratelimit(user, domain='all'):
(list_key, set_key, _) = redis_key(user, domain)
now = time.time()
if (len(rules) == 0):
return
with client.pipeline() as pipe:
count = 0
while True:
try:
pipe.watch(list_key)
last_val = pipe.lindex(list_key, (max_api_calls(user) - 1))
pipe.multi()
pi... | null | null | null | Increases the rate-limit for the specified user | pcsd | def incr ratelimit user domain='all' list key set key = redis key user domain now = time time if len rules == 0 return with client pipeline as pipe count = 0 while True try pipe watch list key last val = pipe lindex list key max api calls user - 1 pipe multi pipe lpush list key now pipe ltrim list key 0 max api calls u... | 12404 | def incr_ratelimit(user, domain='all'):
(list_key, set_key, _) = redis_key(user, domain)
now = time.time()
if (len(rules) == 0):
return
with client.pipeline() as pipe:
count = 0
while True:
try:
pipe.watch(list_key)
last_val = pipe.lindex(list_key, (max_api_calls(user) - 1))
pipe.multi()
pi... | Increases the rate-limit for the specified user | increases the rate - limit for the specified user | Question:
What does this function do?
Code:
def incr_ratelimit(user, domain='all'):
(list_key, set_key, _) = redis_key(user, domain)
now = time.time()
if (len(rules) == 0):
return
with client.pipeline() as pipe:
count = 0
while True:
try:
pipe.watch(list_key)
last_val = pipe.lindex(list_key, (ma... |
null | null | null | What does this function do? | def get_common_complete_suffix(document, completions):
def doesnt_change_before_cursor(completion):
end = completion.text[:(- completion.start_position)]
return document.text_before_cursor.endswith(end)
completions2 = [c for c in completions if doesnt_change_before_cursor(c)]
if (len(completions2) != len(complet... | null | null | null | Return the common prefix for all completions. | pcsd | def get common complete suffix document completions def doesnt change before cursor completion end = completion text[ - completion start position ] return document text before cursor endswith end completions2 = [c for c in completions if doesnt change before cursor c ] if len completions2 != len completions return u'' ... | 12411 | def get_common_complete_suffix(document, completions):
def doesnt_change_before_cursor(completion):
end = completion.text[:(- completion.start_position)]
return document.text_before_cursor.endswith(end)
completions2 = [c for c in completions if doesnt_change_before_cursor(c)]
if (len(completions2) != len(complet... | Return the common prefix for all completions. | return the common prefix for all completions . | Question:
What does this function do?
Code:
def get_common_complete_suffix(document, completions):
def doesnt_change_before_cursor(completion):
end = completion.text[:(- completion.start_position)]
return document.text_before_cursor.endswith(end)
completions2 = [c for c in completions if doesnt_change_before_c... |
null | null | null | What does this function do? | def sanitize_win_path_string(winpath):
intab = '<>:|?*'
outtab = ('_' * len(intab))
trantab = (''.maketrans(intab, outtab) if six.PY3 else string.maketrans(intab, outtab))
if isinstance(winpath, str):
winpath = winpath.translate(trantab)
elif isinstance(winpath, six.text_type):
winpath = winpath.translate(dict... | null | null | null | Remove illegal path characters for windows | pcsd | def sanitize win path string winpath intab = '<> |?*' outtab = ' ' * len intab trantab = '' maketrans intab outtab if six PY3 else string maketrans intab outtab if isinstance winpath str winpath = winpath translate trantab elif isinstance winpath six text type winpath = winpath translate dict ord c u' ' for c in intab ... | 12415 | def sanitize_win_path_string(winpath):
intab = '<>:|?*'
outtab = ('_' * len(intab))
trantab = (''.maketrans(intab, outtab) if six.PY3 else string.maketrans(intab, outtab))
if isinstance(winpath, str):
winpath = winpath.translate(trantab)
elif isinstance(winpath, six.text_type):
winpath = winpath.translate(dict... | Remove illegal path characters for windows | remove illegal path characters for windows | Question:
What does this function do?
Code:
def sanitize_win_path_string(winpath):
intab = '<>:|?*'
outtab = ('_' * len(intab))
trantab = (''.maketrans(intab, outtab) if six.PY3 else string.maketrans(intab, outtab))
if isinstance(winpath, str):
winpath = winpath.translate(trantab)
elif isinstance(winpath, six... |
null | null | null | What does this function do? | def addNegativesPositives(derivation, negatives, paths, positives):
portionDirections = getSpacedPortionDirections(derivation.interpolationDictionary)
for path in paths:
endMultiplier = None
if (not euclidean.getIsWiddershinsByVector3(path)):
endMultiplier = 1.000001
loopLists = getLoopListsByPath(derivation... | null | null | null | Add pillars output to negatives and positives. | pcsd | def add Negatives Positives derivation negatives paths positives portion Directions = get Spaced Portion Directions derivation interpolation Dictionary for path in paths end Multiplier = None if not euclidean get Is Widdershins By Vector3 path end Multiplier = 1 000001 loop Lists = get Loop Lists By Path derivation end... | 12424 | def addNegativesPositives(derivation, negatives, paths, positives):
portionDirections = getSpacedPortionDirections(derivation.interpolationDictionary)
for path in paths:
endMultiplier = None
if (not euclidean.getIsWiddershinsByVector3(path)):
endMultiplier = 1.000001
loopLists = getLoopListsByPath(derivation... | Add pillars output to negatives and positives. | add pillars output to negatives and positives . | Question:
What does this function do?
Code:
def addNegativesPositives(derivation, negatives, paths, positives):
portionDirections = getSpacedPortionDirections(derivation.interpolationDictionary)
for path in paths:
endMultiplier = None
if (not euclidean.getIsWiddershinsByVector3(path)):
endMultiplier = 1.000... |
null | null | null | What does this function do? | def computeNearestNeighbor(username, users):
distances = []
for user in users:
if (user != username):
distance = manhattan(users[user], users[username])
distances.append((distance, user))
distances.sort()
return distances
| null | null | null | creates a sorted list of users based on their distance to username | pcsd | def compute Nearest Neighbor username users distances = [] for user in users if user != username distance = manhattan users[user] users[username] distances append distance user distances sort return distances | 12436 | def computeNearestNeighbor(username, users):
distances = []
for user in users:
if (user != username):
distance = manhattan(users[user], users[username])
distances.append((distance, user))
distances.sort()
return distances
| creates a sorted list of users based on their distance to username | creates a sorted list of users based on their distance to username | Question:
What does this function do?
Code:
def computeNearestNeighbor(username, users):
distances = []
for user in users:
if (user != username):
distance = manhattan(users[user], users[username])
distances.append((distance, user))
distances.sort()
return distances
|
null | null | null | What does this function do? | def cell_create(context, values):
return IMPL.cell_create(context, values)
| null | null | null | Create a new child Cell entry. | pcsd | def cell create context values return IMPL cell create context values | 12445 | def cell_create(context, values):
return IMPL.cell_create(context, values)
| Create a new child Cell entry. | create a new child cell entry . | Question:
What does this function do?
Code:
def cell_create(context, values):
return IMPL.cell_create(context, values)
|
null | null | null | What does this function do? | def open_stream(stream):
global stream_fd
try:
stream_fd = stream.open()
except StreamError as err:
raise StreamError('Could not open stream: {0}'.format(err))
try:
console.logger.debug('Pre-buffering 8192 bytes')
prebuffer = stream_fd.read(8192)
except IOError as err:
raise StreamError('Failed to read d... | null | null | null | Opens a stream and reads 8192 bytes from it.
This is useful to check if a stream actually has data
before opening the output. | pcsd | def open stream stream global stream fd try stream fd = stream open except Stream Error as err raise Stream Error 'Could not open stream {0}' format err try console logger debug 'Pre-buffering 8192 bytes' prebuffer = stream fd read 8192 except IO Error as err raise Stream Error 'Failed to read data from stream {0}' for... | 12449 | def open_stream(stream):
global stream_fd
try:
stream_fd = stream.open()
except StreamError as err:
raise StreamError('Could not open stream: {0}'.format(err))
try:
console.logger.debug('Pre-buffering 8192 bytes')
prebuffer = stream_fd.read(8192)
except IOError as err:
raise StreamError('Failed to read d... | Opens a stream and reads 8192 bytes from it.
This is useful to check if a stream actually has data
before opening the output. | opens a stream and reads 8192 bytes from it . | Question:
What does this function do?
Code:
def open_stream(stream):
global stream_fd
try:
stream_fd = stream.open()
except StreamError as err:
raise StreamError('Could not open stream: {0}'.format(err))
try:
console.logger.debug('Pre-buffering 8192 bytes')
prebuffer = stream_fd.read(8192)
except IOErro... |
null | null | null | What does this function do? | def isValidUSState(field_data, all_data):
states = ['AA', 'AE', 'AK', 'AL', 'AP', 'AR', 'AS', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'FM', 'GA', 'GU', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MH', 'MI', 'MN', 'MO', 'MP', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NV', 'NY', 'OH', 'OK... | null | null | null | Checks that the given string is a valid two-letter U.S. state abbreviation | pcsd | def is Valid US State field data all data states = ['AA' 'AE' 'AK' 'AL' 'AP' 'AR' 'AS' 'AZ' 'CA' 'CO' 'CT' 'DC' 'DE' 'FL' 'FM' 'GA' 'GU' 'HI' 'IA' 'ID' 'IL' 'IN' 'KS' 'KY' 'LA' 'MA' 'MD' 'ME' 'MH' 'MI' 'MN' 'MO' 'MP' 'MS' 'MT' 'NC' 'ND' 'NE' 'NH' 'NJ' 'NM' 'NV' 'NY' 'OH' 'OK' 'OR' 'PA' 'PR' 'PW' 'RI' 'SC' 'SD' 'TN' 'TX... | 12450 | def isValidUSState(field_data, all_data):
states = ['AA', 'AE', 'AK', 'AL', 'AP', 'AR', 'AS', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'FM', 'GA', 'GU', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MH', 'MI', 'MN', 'MO', 'MP', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NV', 'NY', 'OH', 'OK... | Checks that the given string is a valid two-letter U.S. state abbreviation | checks that the given string is a valid two - letter u . s . | Question:
What does this function do?
Code:
def isValidUSState(field_data, all_data):
states = ['AA', 'AE', 'AK', 'AL', 'AP', 'AR', 'AS', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'FM', 'GA', 'GU', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MH', 'MI', 'MN', 'MO', 'MP', 'MS', 'MT', 'NC', 'ND'... |
null | null | null | What does this function do? | def _update_access_token(user, graph):
profile = try_get_profile(user)
model_or_profile = get_instance_for_attribute(user, profile, 'access_token')
if model_or_profile:
new_token = (graph.access_token != model_or_profile.access_token)
token_message = ('a new' if new_token else 'the same')
logger.info('found %s... | null | null | null | Conditionally updates the access token in the database | pcsd | def update access token user graph profile = try get profile user model or profile = get instance for attribute user profile 'access token' if model or profile new token = graph access token != model or profile access token token message = 'a new' if new token else 'the same' logger info 'found %s token %s' token messa... | 12461 | def _update_access_token(user, graph):
profile = try_get_profile(user)
model_or_profile = get_instance_for_attribute(user, profile, 'access_token')
if model_or_profile:
new_token = (graph.access_token != model_or_profile.access_token)
token_message = ('a new' if new_token else 'the same')
logger.info('found %s... | Conditionally updates the access token in the database | conditionally updates the access token in the database | Question:
What does this function do?
Code:
def _update_access_token(user, graph):
profile = try_get_profile(user)
model_or_profile = get_instance_for_attribute(user, profile, 'access_token')
if model_or_profile:
new_token = (graph.access_token != model_or_profile.access_token)
token_message = ('a new' if new... |
null | null | null | What does this function do? | def p_command_read_bad(p):
p[0] = 'MALFORMED VARIABLE LIST IN READ'
| null | null | null | command : READ error | pcsd | def p command read bad p p[0] = 'MALFORMED VARIABLE LIST IN READ' | 12466 | def p_command_read_bad(p):
p[0] = 'MALFORMED VARIABLE LIST IN READ'
| command : READ error | command : read error | Question:
What does this function do?
Code:
def p_command_read_bad(p):
p[0] = 'MALFORMED VARIABLE LIST IN READ'
|
null | null | null | What does this function do? | @contextmanager
def __environ(values, remove=[]):
new_keys = (set(environ.keys()) - set(values.keys()))
old_environ = environ.copy()
try:
environ.update(values)
for to_remove in remove:
try:
del environ[remove]
except KeyError:
pass
(yield)
finally:
environ.update(old_environ)
for key in new... | null | null | null | Modify the environment for a test, adding/updating values in dict `values` and
removing any environment variables mentioned in list `remove`. | pcsd | @contextmanager def environ values remove=[] new keys = set environ keys - set values keys old environ = environ copy try environ update values for to remove in remove try del environ[remove] except Key Error pass yield finally environ update old environ for key in new keys del environ[key] | 12468 | @contextmanager
def __environ(values, remove=[]):
new_keys = (set(environ.keys()) - set(values.keys()))
old_environ = environ.copy()
try:
environ.update(values)
for to_remove in remove:
try:
del environ[remove]
except KeyError:
pass
(yield)
finally:
environ.update(old_environ)
for key in new... | Modify the environment for a test, adding/updating values in dict `values` and
removing any environment variables mentioned in list `remove`. | modify the environment for a test , adding / updating values in dict values and removing any environment variables mentioned in list remove . | Question:
What does this function do?
Code:
@contextmanager
def __environ(values, remove=[]):
new_keys = (set(environ.keys()) - set(values.keys()))
old_environ = environ.copy()
try:
environ.update(values)
for to_remove in remove:
try:
del environ[remove]
except KeyError:
pass
(yield)
finally:... |
null | null | null | What does this function do? | def SaveTemporaryFile(fp):
loc = data_store.DB.Location()
if (not os.path.exists(loc)):
return False
if (not os.path.isdir(loc)):
return False
filecopy_len_str = fp.read(sutils.SIZE_PACKER.size)
filecopy_len = sutils.SIZE_PACKER.unpack(filecopy_len_str)[0]
filecopy = rdf_data_server.DataServerFileCopy(fp.read... | null | null | null | Store incoming database file in a temporary directory. | pcsd | def Save Temporary File fp loc = data store DB Location if not os path exists loc return False if not os path isdir loc return False filecopy len str = fp read sutils SIZE PACKER size filecopy len = sutils SIZE PACKER unpack filecopy len str [0] filecopy = rdf data server Data Server File Copy fp read filecopy len rebd... | 12478 | def SaveTemporaryFile(fp):
loc = data_store.DB.Location()
if (not os.path.exists(loc)):
return False
if (not os.path.isdir(loc)):
return False
filecopy_len_str = fp.read(sutils.SIZE_PACKER.size)
filecopy_len = sutils.SIZE_PACKER.unpack(filecopy_len_str)[0]
filecopy = rdf_data_server.DataServerFileCopy(fp.read... | Store incoming database file in a temporary directory. | store incoming database file in a temporary directory . | Question:
What does this function do?
Code:
def SaveTemporaryFile(fp):
loc = data_store.DB.Location()
if (not os.path.exists(loc)):
return False
if (not os.path.isdir(loc)):
return False
filecopy_len_str = fp.read(sutils.SIZE_PACKER.size)
filecopy_len = sutils.SIZE_PACKER.unpack(filecopy_len_str)[0]
fileco... |
null | null | null | What does this function do? | def intercept_renderer(path, context):
response = render_to_response(path, context)
response.mako_context = context
response.mako_template = path
return response
| null | null | null | Intercept calls to `render_to_response` and attach the context dict to the
response for examination in unit tests. | pcsd | def intercept renderer path context response = render to response path context response mako context = context response mako template = path return response | 12480 | def intercept_renderer(path, context):
response = render_to_response(path, context)
response.mako_context = context
response.mako_template = path
return response
| Intercept calls to `render_to_response` and attach the context dict to the
response for examination in unit tests. | intercept calls to render _ to _ response and attach the context dict to the response for examination in unit tests . | Question:
What does this function do?
Code:
def intercept_renderer(path, context):
response = render_to_response(path, context)
response.mako_context = context
response.mako_template = path
return response
|
null | null | null | What does this function do? | def get_metrics():
global METRICS, LAST_METRICS
if ((time.time() - METRICS['time']) > METRICS_CACHE_TTL):
io = os.popen(PARAMS['stats_command'])
metrics_str = ''.join(io.readlines()).strip()
metrics_str = re.sub('\\w+\\((.*)\\)', '\\1', metrics_str)
try:
metrics = flatten(json.loads(metrics_str))
except ... | null | null | null | Return all metrics | pcsd | def get metrics global METRICS LAST METRICS if time time - METRICS['time'] > METRICS CACHE TTL io = os popen PARAMS['stats command'] metrics str = '' join io readlines strip metrics str = re sub '\\w+\\ * \\ ' '\\1' metrics str try metrics = flatten json loads metrics str except Value Error metrics = {} LAST METRICS = ... | 12482 | def get_metrics():
global METRICS, LAST_METRICS
if ((time.time() - METRICS['time']) > METRICS_CACHE_TTL):
io = os.popen(PARAMS['stats_command'])
metrics_str = ''.join(io.readlines()).strip()
metrics_str = re.sub('\\w+\\((.*)\\)', '\\1', metrics_str)
try:
metrics = flatten(json.loads(metrics_str))
except ... | Return all metrics | return all metrics | Question:
What does this function do?
Code:
def get_metrics():
global METRICS, LAST_METRICS
if ((time.time() - METRICS['time']) > METRICS_CACHE_TTL):
io = os.popen(PARAMS['stats_command'])
metrics_str = ''.join(io.readlines()).strip()
metrics_str = re.sub('\\w+\\((.*)\\)', '\\1', metrics_str)
try:
metri... |
null | null | null | What does this function do? | def name_to_cat(fname, cat=None):
if ((cat is None) and fname.startswith('{{')):
n = fname.find('}}')
if (n > 2):
cat = fname[2:n].strip()
fname = fname[(n + 2):].strip()
logging.debug('Job %s has category %s', fname, cat)
return (fname, cat)
| null | null | null | Retrieve category from file name, but only if "cat" is None. | pcsd | def name to cat fname cat=None if cat is None and fname startswith '{{' n = fname find '}}' if n > 2 cat = fname[2 n] strip fname = fname[ n + 2 ] strip logging debug 'Job %s has category %s' fname cat return fname cat | 12485 | def name_to_cat(fname, cat=None):
if ((cat is None) and fname.startswith('{{')):
n = fname.find('}}')
if (n > 2):
cat = fname[2:n].strip()
fname = fname[(n + 2):].strip()
logging.debug('Job %s has category %s', fname, cat)
return (fname, cat)
| Retrieve category from file name, but only if "cat" is None. | retrieve category from file name , but only if " cat " is none . | Question:
What does this function do?
Code:
def name_to_cat(fname, cat=None):
if ((cat is None) and fname.startswith('{{')):
n = fname.find('}}')
if (n > 2):
cat = fname[2:n].strip()
fname = fname[(n + 2):].strip()
logging.debug('Job %s has category %s', fname, cat)
return (fname, cat)
|
null | null | null | What does this function do? | @manager.option(u'-v', u'--verbose', action=u'store_true', help=u'Show extra information')
def version(verbose):
s = u'\n-----------------------\nSuperset {version}\n-----------------------'.format(version=config.get(u'VERSION_STRING'))
print(s)
if verbose:
print((u'[DB] : ' + u'{}'.format(db.engine)))
| null | null | null | Prints the current version number | pcsd | @manager option u'-v' u'--verbose' action=u'store true' help=u'Show extra information' def version verbose s = u' ----------------------- Superset {version} -----------------------' format version=config get u'VERSION STRING' print s if verbose print u'[DB] ' + u'{}' format db engine | 12486 | @manager.option(u'-v', u'--verbose', action=u'store_true', help=u'Show extra information')
def version(verbose):
s = u'\n-----------------------\nSuperset {version}\n-----------------------'.format(version=config.get(u'VERSION_STRING'))
print(s)
if verbose:
print((u'[DB] : ' + u'{}'.format(db.engine)))
| Prints the current version number | prints the current version number | Question:
What does this function do?
Code:
@manager.option(u'-v', u'--verbose', action=u'store_true', help=u'Show extra information')
def version(verbose):
s = u'\n-----------------------\nSuperset {version}\n-----------------------'.format(version=config.get(u'VERSION_STRING'))
print(s)
if verbose:
print((u'[... |
null | null | null | What does this function do? | def get_account_by_id(account_id):
account = Account.query.filter((Account.id == account_id)).first()
manager_class = account_registry.get(account.account_type.name)
account = manager_class()._load(account)
db.session.expunge(account)
return account
| null | null | null | Retrieves an account plus any additional custom fields | pcsd | def get account by id account id account = Account query filter Account id == account id first manager class = account registry get account account type name account = manager class load account db session expunge account return account | 12501 | def get_account_by_id(account_id):
account = Account.query.filter((Account.id == account_id)).first()
manager_class = account_registry.get(account.account_type.name)
account = manager_class()._load(account)
db.session.expunge(account)
return account
| Retrieves an account plus any additional custom fields | retrieves an account plus any additional custom fields | Question:
What does this function do?
Code:
def get_account_by_id(account_id):
account = Account.query.filter((Account.id == account_id)).first()
manager_class = account_registry.get(account.account_type.name)
account = manager_class()._load(account)
db.session.expunge(account)
return account
|
null | null | null | What does this function do? | def find_version(*file_path):
version_file = read(*file_path)
version_match = re.search(VERSION_RE, version_file, re.MULTILINE)
if version_match:
return version_match.group(1)
raise RuntimeError('Unable to find version string.')
| null | null | null | Returns the version number appearing in the file in the given file
path.
Each positional argument indicates a member of the path. | pcsd | def find version *file path version file = read *file path version match = re search VERSION RE version file re MULTILINE if version match return version match group 1 raise Runtime Error 'Unable to find version string ' | 12503 | def find_version(*file_path):
version_file = read(*file_path)
version_match = re.search(VERSION_RE, version_file, re.MULTILINE)
if version_match:
return version_match.group(1)
raise RuntimeError('Unable to find version string.')
| Returns the version number appearing in the file in the given file
path.
Each positional argument indicates a member of the path. | returns the version number appearing in the file in the given file path . | Question:
What does this function do?
Code:
def find_version(*file_path):
version_file = read(*file_path)
version_match = re.search(VERSION_RE, version_file, re.MULTILINE)
if version_match:
return version_match.group(1)
raise RuntimeError('Unable to find version string.')
|
null | null | null | What does this function do? | def _cross_val(data, est, cv, n_jobs):
try:
from sklearn.model_selection import cross_val_score
except ImportError:
from sklearn.cross_validation import cross_val_score
return np.mean(cross_val_score(est, data, cv=cv, n_jobs=n_jobs, scoring=_gaussian_loglik_scorer))
| null | null | null | Helper to compute cross validation. | pcsd | def cross val data est cv n jobs try from sklearn model selection import cross val score except Import Error from sklearn cross validation import cross val score return np mean cross val score est data cv=cv n jobs=n jobs scoring= gaussian loglik scorer | 12520 | def _cross_val(data, est, cv, n_jobs):
try:
from sklearn.model_selection import cross_val_score
except ImportError:
from sklearn.cross_validation import cross_val_score
return np.mean(cross_val_score(est, data, cv=cv, n_jobs=n_jobs, scoring=_gaussian_loglik_scorer))
| Helper to compute cross validation. | helper to compute cross validation . | Question:
What does this function do?
Code:
def _cross_val(data, est, cv, n_jobs):
try:
from sklearn.model_selection import cross_val_score
except ImportError:
from sklearn.cross_validation import cross_val_score
return np.mean(cross_val_score(est, data, cv=cv, n_jobs=n_jobs, scoring=_gaussian_loglik_scorer))... |
null | null | null | What does this function do? | def get_cookie_header(jar, request):
r = MockRequest(request)
jar.add_cookie_header(r)
return r.get_new_headers().get('Cookie')
| null | null | null | Produce an appropriate Cookie header string to be sent with `request`, or None. | pcsd | def get cookie header jar request r = Mock Request request jar add cookie header r return r get new headers get 'Cookie' | 12523 | def get_cookie_header(jar, request):
r = MockRequest(request)
jar.add_cookie_header(r)
return r.get_new_headers().get('Cookie')
| Produce an appropriate Cookie header string to be sent with `request`, or None. | produce an appropriate cookie header string to be sent with request , or none . | Question:
What does this function do?
Code:
def get_cookie_header(jar, request):
r = MockRequest(request)
jar.add_cookie_header(r)
return r.get_new_headers().get('Cookie')
|
null | null | null | What does this function do? | def make_link(path):
tryFile = path.replace('\\', '/')
if (os.path.isabs(tryFile) and os.path.isfile(tryFile)):
(folder, filename) = os.path.split(tryFile)
(base, ext) = os.path.splitext(filename)
app = get_app()
editable = {'controllers': '.py', 'models': '.py', 'views': '.html'}
for key in editable.keys()... | null | null | null | Create a link from a path | pcsd | def make link path try File = path replace '\\' '/' if os path isabs try File and os path isfile try File folder filename = os path split try File base ext = os path splitext filename app = get app editable = {'controllers' ' py' 'models' ' py' 'views' ' html'} for key in editable keys check extension = folder endswith... | 12530 | def make_link(path):
tryFile = path.replace('\\', '/')
if (os.path.isabs(tryFile) and os.path.isfile(tryFile)):
(folder, filename) = os.path.split(tryFile)
(base, ext) = os.path.splitext(filename)
app = get_app()
editable = {'controllers': '.py', 'models': '.py', 'views': '.html'}
for key in editable.keys()... | Create a link from a path | create a link from a path | Question:
What does this function do?
Code:
def make_link(path):
tryFile = path.replace('\\', '/')
if (os.path.isabs(tryFile) and os.path.isfile(tryFile)):
(folder, filename) = os.path.split(tryFile)
(base, ext) = os.path.splitext(filename)
app = get_app()
editable = {'controllers': '.py', 'models': '.py',... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.