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 group(): s3db.configure('pr_group', linkto=(lambda record_id: URL(c='hrm', f='group', args=[record_id]))) return s3_rest_controller(rheader=s3db.org_rheader)
null
null
null
RESTful CRUD controller
pcsd
def group s3db configure 'pr group' linkto= lambda record id URL c='hrm' f='group' args=[record id] return s3 rest controller rheader=s3db org rheader
9821
def group(): s3db.configure('pr_group', linkto=(lambda record_id: URL(c='hrm', f='group', args=[record_id]))) return s3_rest_controller(rheader=s3db.org_rheader)
RESTful CRUD controller
restful crud controller
Question: What does this function do? Code: def group(): s3db.configure('pr_group', linkto=(lambda record_id: URL(c='hrm', f='group', args=[record_id]))) return s3_rest_controller(rheader=s3db.org_rheader)
null
null
null
What does this function do?
def make_resource(): return {'url': 'http://www.example.com', 'description': 'example resource description', 'format': 'txt', 'name': 'example resource'}
null
null
null
Return a test resource in dictionary form.
pcsd
def make resource return {'url' 'http //www example com' 'description' 'example resource description' 'format' 'txt' 'name' 'example resource'}
9829
def make_resource(): return {'url': 'http://www.example.com', 'description': 'example resource description', 'format': 'txt', 'name': 'example resource'}
Return a test resource in dictionary form.
return a test resource in dictionary form .
Question: What does this function do? Code: def make_resource(): return {'url': 'http://www.example.com', 'description': 'example resource description', 'format': 'txt', 'name': 'example resource'}
null
null
null
What does this function do?
def print_bucket_acl_for_user(bucket_name, user_email): storage_client = storage.Client() bucket = storage_client.bucket(bucket_name) bucket.acl.reload() roles = bucket.acl.user(user_email).get_roles() print roles
null
null
null
Prints out a bucket\'s access control list for a given user.
pcsd
def print bucket acl for user bucket name user email storage client = storage Client bucket = storage client bucket bucket name bucket acl reload roles = bucket acl user user email get roles print roles
9833
def print_bucket_acl_for_user(bucket_name, user_email): storage_client = storage.Client() bucket = storage_client.bucket(bucket_name) bucket.acl.reload() roles = bucket.acl.user(user_email).get_roles() print roles
Prints out a bucket\'s access control list for a given user.
prints out a buckets access control list for a given user .
Question: What does this function do? Code: def print_bucket_acl_for_user(bucket_name, user_email): storage_client = storage.Client() bucket = storage_client.bucket(bucket_name) bucket.acl.reload() roles = bucket.acl.user(user_email).get_roles() print roles
null
null
null
What does this function do?
def maybe_unroll_group(g): try: size = len(g.tasks) except TypeError: try: size = g.tasks.__length_hint__() except (AttributeError, TypeError): return g else: return (list(g.tasks)[0] if (size == 1) else g) else: return (g.tasks[0] if (size == 1) else g)
null
null
null
Unroll group with only one member.
pcsd
def maybe unroll group g try size = len g tasks except Type Error try size = g tasks length hint except Attribute Error Type Error return g else return list g tasks [0] if size == 1 else g else return g tasks[0] if size == 1 else g
9834
def maybe_unroll_group(g): try: size = len(g.tasks) except TypeError: try: size = g.tasks.__length_hint__() except (AttributeError, TypeError): return g else: return (list(g.tasks)[0] if (size == 1) else g) else: return (g.tasks[0] if (size == 1) else g)
Unroll group with only one member.
unroll group with only one member .
Question: What does this function do? Code: def maybe_unroll_group(g): try: size = len(g.tasks) except TypeError: try: size = g.tasks.__length_hint__() except (AttributeError, TypeError): return g else: return (list(g.tasks)[0] if (size == 1) else g) else: return (g.tasks[0] if (size == 1) else...
null
null
null
What does this function do?
def definite_article(word, gender=MALE): if ((PLURAL in gender) and (MALE in gender) and (is_vowel(word[:1]) or zs(word))): return 'gli' if ((PLURAL not in gender) and word and is_vowel(word[:1])): return "l'" if ((PLURAL not in gender) and (MALE in gender) and zs(word)): return 'lo' if (MALE in gender): re...
null
null
null
Returns the definite article for a given word.
pcsd
def definite article word gender=MALE if PLURAL in gender and MALE in gender and is vowel word[ 1] or zs word return 'gli' if PLURAL not in gender and word and is vowel word[ 1] return "l'" if PLURAL not in gender and MALE in gender and zs word return 'lo' if MALE in gender return PLURAL in gender and 'i' or 'il' if FE...
9849
def definite_article(word, gender=MALE): if ((PLURAL in gender) and (MALE in gender) and (is_vowel(word[:1]) or zs(word))): return 'gli' if ((PLURAL not in gender) and word and is_vowel(word[:1])): return "l'" if ((PLURAL not in gender) and (MALE in gender) and zs(word)): return 'lo' if (MALE in gender): re...
Returns the definite article for a given word.
returns the definite article for a given word .
Question: What does this function do? Code: def definite_article(word, gender=MALE): if ((PLURAL in gender) and (MALE in gender) and (is_vowel(word[:1]) or zs(word))): return 'gli' if ((PLURAL not in gender) and word and is_vowel(word[:1])): return "l'" if ((PLURAL not in gender) and (MALE in gender) and zs(w...
null
null
null
What does this function do?
def logout(client): client.click(jquery='("#hue-logout a")[0]')
null
null
null
logs the user out of desktop
pcsd
def logout client client click jquery=' "#hue-logout a" [0]'
9867
def logout(client): client.click(jquery='("#hue-logout a")[0]')
logs the user out of desktop
logs the user out of desktop
Question: What does this function do? Code: def logout(client): client.click(jquery='("#hue-logout a")[0]')
null
null
null
What does this function do?
def safename(filename): try: if re_url_scheme.match(filename): if isinstance(filename, str): filename = filename.decode('utf-8') filename = filename.encode('idna') else: filename = filename.encode('idna') except UnicodeError: pass if isinstance(filename, unicode): filename = filename.encode('...
null
null
null
Return a filename suitable for the cache. Strips dangerous and common characters to create a filename we can use to store the cache in.
pcsd
def safename filename try if re url scheme match filename if isinstance filename str filename = filename decode 'utf-8' filename = filename encode 'idna' else filename = filename encode 'idna' except Unicode Error pass if isinstance filename unicode filename = filename encode 'utf-8' filemd5 = md5 filename hexdigest fi...
9883
def safename(filename): try: if re_url_scheme.match(filename): if isinstance(filename, str): filename = filename.decode('utf-8') filename = filename.encode('idna') else: filename = filename.encode('idna') except UnicodeError: pass if isinstance(filename, unicode): filename = filename.encode('...
Return a filename suitable for the cache. Strips dangerous and common characters to create a filename we can use to store the cache in.
return a filename suitable for the cache .
Question: What does this function do? Code: def safename(filename): try: if re_url_scheme.match(filename): if isinstance(filename, str): filename = filename.decode('utf-8') filename = filename.encode('idna') else: filename = filename.encode('idna') except UnicodeError: pass if isinstance(fil...
null
null
null
What does this function do?
def dset_sheet(dataset, ws): _package = dataset._package(dicts=False) for (i, sep) in enumerate(dataset._separators): _offset = i _package.insert((sep[0] + _offset), (sep[1],)) for (i, row) in enumerate(_package): for (j, col) in enumerate(row): if ((i == 0) and dataset.headers): ws.write(i, j, col, bol...
null
null
null
Completes given worksheet from given Dataset.
pcsd
def dset sheet dataset ws package = dataset package dicts=False for i sep in enumerate dataset separators offset = i package insert sep[0] + offset sep[1] for i row in enumerate package for j col in enumerate row if i == 0 and dataset headers ws write i j col bold ws panes frozen = True ws horz split pos = 1 elif len r...
9884
def dset_sheet(dataset, ws): _package = dataset._package(dicts=False) for (i, sep) in enumerate(dataset._separators): _offset = i _package.insert((sep[0] + _offset), (sep[1],)) for (i, row) in enumerate(_package): for (j, col) in enumerate(row): if ((i == 0) and dataset.headers): ws.write(i, j, col, bol...
Completes given worksheet from given Dataset.
completes given worksheet from given dataset .
Question: What does this function do? Code: def dset_sheet(dataset, ws): _package = dataset._package(dicts=False) for (i, sep) in enumerate(dataset._separators): _offset = i _package.insert((sep[0] + _offset), (sep[1],)) for (i, row) in enumerate(_package): for (j, col) in enumerate(row): if ((i == 0) an...
null
null
null
What does this function do?
def _preview(layer): layername = layer.name() (lat, lon) = (layer.preview_lat, layer.preview_lon) zoom = layer.preview_zoom ext = layer.preview_ext return ('<!DOCTYPE html>\n<html>\n<head>\n <title>TileStache Preview: %(layername)s</title>\n <script src="http://cdn.rawgit.com/stamen/modestmaps-js/v1.0.0-beta...
null
null
null
Get an HTML response for a given named layer.
pcsd
def preview layer layername = layer name lat lon = layer preview lat layer preview lon zoom = layer preview zoom ext = layer preview ext return '<!DOCTYPE html> <html> <head> <title>Tile Stache Preview % layername s</title> <script src="http //cdn rawgit com/stamen/modestmaps-js/v1 0 0-beta1/modestmaps min js" type="te...
9891
def _preview(layer): layername = layer.name() (lat, lon) = (layer.preview_lat, layer.preview_lon) zoom = layer.preview_zoom ext = layer.preview_ext return ('<!DOCTYPE html>\n<html>\n<head>\n <title>TileStache Preview: %(layername)s</title>\n <script src="http://cdn.rawgit.com/stamen/modestmaps-js/v1.0.0-beta...
Get an HTML response for a given named layer.
get an html response for a given named layer .
Question: What does this function do? Code: def _preview(layer): layername = layer.name() (lat, lon) = (layer.preview_lat, layer.preview_lon) zoom = layer.preview_zoom ext = layer.preview_ext return ('<!DOCTYPE html>\n<html>\n<head>\n <title>TileStache Preview: %(layername)s</title>\n <script src="http://...
null
null
null
What does this function do?
@pytest.mark.nondestructive def test_there_are_ten_most_popular_extensions(base_url, selenium): page = Home(selenium, base_url).open() assert (len(page.most_popular.extensions) == 10)
null
null
null
Ten most popular add-ons are listed
pcsd
@pytest mark nondestructive def test there are ten most popular extensions base url selenium page = Home selenium base url open assert len page most popular extensions == 10
9900
@pytest.mark.nondestructive def test_there_are_ten_most_popular_extensions(base_url, selenium): page = Home(selenium, base_url).open() assert (len(page.most_popular.extensions) == 10)
Ten most popular add-ons are listed
ten most popular add - ons are listed
Question: What does this function do? Code: @pytest.mark.nondestructive def test_there_are_ten_most_popular_extensions(base_url, selenium): page = Home(selenium, base_url).open() assert (len(page.most_popular.extensions) == 10)
null
null
null
What does this function do?
def add_callers(target, source): new_callers = {} for (func, caller) in target.iteritems(): new_callers[func] = caller for (func, caller) in source.iteritems(): if (func in new_callers): new_callers[func] = tuple([(i[0] + i[1]) for i in zip(caller, new_callers[func])]) else: new_callers[func] = caller r...
null
null
null
Combine two caller lists in a single list.
pcsd
def add callers target source new callers = {} for func caller in target iteritems new callers[func] = caller for func caller in source iteritems if func in new callers new callers[func] = tuple [ i[0] + i[1] for i in zip caller new callers[func] ] else new callers[func] = caller return new callers
9901
def add_callers(target, source): new_callers = {} for (func, caller) in target.iteritems(): new_callers[func] = caller for (func, caller) in source.iteritems(): if (func in new_callers): new_callers[func] = tuple([(i[0] + i[1]) for i in zip(caller, new_callers[func])]) else: new_callers[func] = caller r...
Combine two caller lists in a single list.
combine two caller lists in a single list .
Question: What does this function do? Code: def add_callers(target, source): new_callers = {} for (func, caller) in target.iteritems(): new_callers[func] = caller for (func, caller) in source.iteritems(): if (func in new_callers): new_callers[func] = tuple([(i[0] + i[1]) for i in zip(caller, new_callers[fu...
null
null
null
What does this function do?
def getPointsFromLoop(loop, radius, thresholdRatio=0.9): if (radius == 0.0): print 'Warning, radius is 0 in getPointsFromLoop in intercircle.' print loop return loop radius = abs(radius) points = [] for pointIndex in xrange(len(loop)): pointBegin = loop[pointIndex] pointEnd = loop[((pointIndex + 1) % len(...
null
null
null
Get the points from every point on a loop and between points.
pcsd
def get Points From Loop loop radius threshold Ratio=0 9 if radius == 0 0 print 'Warning radius is 0 in get Points From Loop in intercircle ' print loop return loop radius = abs radius points = [] for point Index in xrange len loop point Begin = loop[point Index] point End = loop[ point Index + 1 % len loop ] points ap...
9904
def getPointsFromLoop(loop, radius, thresholdRatio=0.9): if (radius == 0.0): print 'Warning, radius is 0 in getPointsFromLoop in intercircle.' print loop return loop radius = abs(radius) points = [] for pointIndex in xrange(len(loop)): pointBegin = loop[pointIndex] pointEnd = loop[((pointIndex + 1) % len(...
Get the points from every point on a loop and between points.
get the points from every point on a loop and between points .
Question: What does this function do? Code: def getPointsFromLoop(loop, radius, thresholdRatio=0.9): if (radius == 0.0): print 'Warning, radius is 0 in getPointsFromLoop in intercircle.' print loop return loop radius = abs(radius) points = [] for pointIndex in xrange(len(loop)): pointBegin = loop[pointIn...
null
null
null
What does this function do?
@register.inclusion_tag('horizon/_nav_list.html', takes_context=True) def horizon_main_nav(context): if ('request' not in context): return {} current_dashboard = context['request'].horizon.get('dashboard', None) dashboards = [] for dash in Horizon.get_dashboards(): if (callable(dash.nav) and dash.nav(context)):...
null
null
null
Generates top-level dashboard navigation entries.
pcsd
@register inclusion tag 'horizon/ nav list html' takes context=True def horizon main nav context if 'request' not in context return {} current dashboard = context['request'] horizon get 'dashboard' None dashboards = [] for dash in Horizon get dashboards if callable dash nav and dash nav context dashboards append dash e...
9910
@register.inclusion_tag('horizon/_nav_list.html', takes_context=True) def horizon_main_nav(context): if ('request' not in context): return {} current_dashboard = context['request'].horizon.get('dashboard', None) dashboards = [] for dash in Horizon.get_dashboards(): if (callable(dash.nav) and dash.nav(context)):...
Generates top-level dashboard navigation entries.
generates top - level dashboard navigation entries .
Question: What does this function do? Code: @register.inclusion_tag('horizon/_nav_list.html', takes_context=True) def horizon_main_nav(context): if ('request' not in context): return {} current_dashboard = context['request'].horizon.get('dashboard', None) dashboards = [] for dash in Horizon.get_dashboards(): ...
null
null
null
What does this function do?
def xsrf_required(method): def xsrf_required_decorator(self): expected_token = get_xsrf_token() actual_token = self.request.get('xsrf_token') if (actual_token != expected_token): self.response.set_status(403, 'Invalid XSRF token') self.response.out.write((('<h1>Invalid XSRF token</h1>\n' + '<p>Please reloa...
null
null
null
Decorator to protect post() handlers against XSRF attacks.
pcsd
def xsrf required method def xsrf required decorator self expected token = get xsrf token actual token = self request get 'xsrf token' if actual token != expected token self response set status 403 'Invalid XSRF token' self response out write '<h1>Invalid XSRF token</h1> ' + '<p>Please reload the form page</n> ' + ' ' ...
9921
def xsrf_required(method): def xsrf_required_decorator(self): expected_token = get_xsrf_token() actual_token = self.request.get('xsrf_token') if (actual_token != expected_token): self.response.set_status(403, 'Invalid XSRF token') self.response.out.write((('<h1>Invalid XSRF token</h1>\n' + '<p>Please reloa...
Decorator to protect post() handlers against XSRF attacks.
decorator to protect post ( ) handlers against xsrf attacks .
Question: What does this function do? Code: def xsrf_required(method): def xsrf_required_decorator(self): expected_token = get_xsrf_token() actual_token = self.request.get('xsrf_token') if (actual_token != expected_token): self.response.set_status(403, 'Invalid XSRF token') self.response.out.write((('<h...
null
null
null
What does this function do?
def get_path_collection_extents(*args): from transforms import Bbox if (len(args[1]) == 0): raise ValueError('No paths provided') return Bbox.from_extents(*_get_path_collection_extents(*args))
null
null
null
Given a sequence of :class:`Path` objects, returns the bounding box that encapsulates all of them.
pcsd
def get path collection extents *args from transforms import Bbox if len args[1] == 0 raise Value Error 'No paths provided' return Bbox from extents * get path collection extents *args
9922
def get_path_collection_extents(*args): from transforms import Bbox if (len(args[1]) == 0): raise ValueError('No paths provided') return Bbox.from_extents(*_get_path_collection_extents(*args))
Given a sequence of :class:`Path` objects, returns the bounding box that encapsulates all of them.
given a sequence of : class : path objects , returns the bounding box that encapsulates all of them .
Question: What does this function do? Code: def get_path_collection_extents(*args): from transforms import Bbox if (len(args[1]) == 0): raise ValueError('No paths provided') return Bbox.from_extents(*_get_path_collection_extents(*args))
null
null
null
What does this function do?
def get_localizable_attributes(obj): locale = {} try: if obj.label: locale['label'] = obj.label except: pass try: if obj.description: locale['description'] = obj.description except: pass return locale
null
null
null
Returns a dictionary with localizable attributes of `obj`.
pcsd
def get localizable attributes obj locale = {} try if obj label locale['label'] = obj label except pass try if obj description locale['description'] = obj description except pass return locale
9928
def get_localizable_attributes(obj): locale = {} try: if obj.label: locale['label'] = obj.label except: pass try: if obj.description: locale['description'] = obj.description except: pass return locale
Returns a dictionary with localizable attributes of `obj`.
returns a dictionary with localizable attributes of obj .
Question: What does this function do? Code: def get_localizable_attributes(obj): locale = {} try: if obj.label: locale['label'] = obj.label except: pass try: if obj.description: locale['description'] = obj.description except: pass return locale
null
null
null
What does this function do?
def _vector_or_scalar(x, type='row'): if isinstance(x, (list, tuple)): x = np.array(x) if isinstance(x, np.ndarray): assert (x.ndim == 1) if (type == 'column'): x = x[:, None] return x
null
null
null
Convert an object to either a scalar or a row or column vector.
pcsd
def vector or scalar x type='row' if isinstance x list tuple x = np array x if isinstance x np ndarray assert x ndim == 1 if type == 'column' x = x[ None] return x
9932
def _vector_or_scalar(x, type='row'): if isinstance(x, (list, tuple)): x = np.array(x) if isinstance(x, np.ndarray): assert (x.ndim == 1) if (type == 'column'): x = x[:, None] return x
Convert an object to either a scalar or a row or column vector.
convert an object to either a scalar or a row or column vector .
Question: What does this function do? Code: def _vector_or_scalar(x, type='row'): if isinstance(x, (list, tuple)): x = np.array(x) if isinstance(x, np.ndarray): assert (x.ndim == 1) if (type == 'column'): x = x[:, None] return x
null
null
null
What does this function do?
def translate_longopt(opt): return opt.translate(longopt_xlate)
null
null
null
Convert a long option name to a valid Python identifier by changing "-" to "_".
pcsd
def translate longopt opt return opt translate longopt xlate
9940
def translate_longopt(opt): return opt.translate(longopt_xlate)
Convert a long option name to a valid Python identifier by changing "-" to "_".
convert a long option name to a valid python identifier by changing " - " to " _ " .
Question: What does this function do? Code: def translate_longopt(opt): return opt.translate(longopt_xlate)
null
null
null
What does this function do?
def get_repository_version(pear_output): lines = pear_output.split('\n') for line in lines: if ('Latest ' in line): return line.rsplit(None, 1)[(-1)].strip() return None
null
null
null
Take pear remote-info output and get the latest version
pcsd
def get repository version pear output lines = pear output split ' ' for line in lines if 'Latest ' in line return line rsplit None 1 [ -1 ] strip return None
9943
def get_repository_version(pear_output): lines = pear_output.split('\n') for line in lines: if ('Latest ' in line): return line.rsplit(None, 1)[(-1)].strip() return None
Take pear remote-info output and get the latest version
take pear remote - info output and get the latest version
Question: What does this function do? Code: def get_repository_version(pear_output): lines = pear_output.split('\n') for line in lines: if ('Latest ' in line): return line.rsplit(None, 1)[(-1)].strip() return None
null
null
null
What does this function do?
def stringToLong(s): result = 0L for byte in s: result = ((256 * result) + ord(byte)) return result
null
null
null
Convert digest to long
pcsd
def string To Long s result = 0L for byte in s result = 256 * result + ord byte return result
9948
def stringToLong(s): result = 0L for byte in s: result = ((256 * result) + ord(byte)) return result
Convert digest to long
convert digest to long
Question: What does this function do? Code: def stringToLong(s): result = 0L for byte in s: result = ((256 * result) + ord(byte)) return result
null
null
null
What does this function do?
def visit_snippet(self, node): lang = self.highlightlang linenos = (node.rawsource.count('\n') >= (self.highlightlinenothreshold - 1)) fname = node['filename'] highlight_args = node.get('highlight_args', {}) if ('language' in node): lang = node['language'] highlight_args['force'] = True if ('linenos' in node)...
null
null
null
HTML document generator visit handler
pcsd
def visit snippet self node lang = self highlightlang linenos = node rawsource count ' ' >= self highlightlinenothreshold - 1 fname = node['filename'] highlight args = node get 'highlight args' {} if 'language' in node lang = node['language'] highlight args['force'] = True if 'linenos' in node linenos = node['linenos']...
9955
def visit_snippet(self, node): lang = self.highlightlang linenos = (node.rawsource.count('\n') >= (self.highlightlinenothreshold - 1)) fname = node['filename'] highlight_args = node.get('highlight_args', {}) if ('language' in node): lang = node['language'] highlight_args['force'] = True if ('linenos' in node)...
HTML document generator visit handler
html document generator visit handler
Question: What does this function do? Code: def visit_snippet(self, node): lang = self.highlightlang linenos = (node.rawsource.count('\n') >= (self.highlightlinenothreshold - 1)) fname = node['filename'] highlight_args = node.get('highlight_args', {}) if ('language' in node): lang = node['language'] highlig...
null
null
null
What does this function do?
def muladd_with_overflow(builder, a, b, c): p = builder.smul_with_overflow(a, b) prod = builder.extract_value(p, 0) prod_ovf = builder.extract_value(p, 1) s = builder.sadd_with_overflow(prod, c) res = builder.extract_value(s, 0) ovf = builder.or_(prod_ovf, builder.extract_value(s, 1)) return (res, ovf)
null
null
null
Compute (a * b + c) and return a (result, overflow bit) pair. The operands must be signed integers.
pcsd
def muladd with overflow builder a b c p = builder smul with overflow a b prod = builder extract value p 0 prod ovf = builder extract value p 1 s = builder sadd with overflow prod c res = builder extract value s 0 ovf = builder or prod ovf builder extract value s 1 return res ovf
9967
def muladd_with_overflow(builder, a, b, c): p = builder.smul_with_overflow(a, b) prod = builder.extract_value(p, 0) prod_ovf = builder.extract_value(p, 1) s = builder.sadd_with_overflow(prod, c) res = builder.extract_value(s, 0) ovf = builder.or_(prod_ovf, builder.extract_value(s, 1)) return (res, ovf)
Compute (a * b + c) and return a (result, overflow bit) pair. The operands must be signed integers.
compute and return a pair .
Question: What does this function do? Code: def muladd_with_overflow(builder, a, b, c): p = builder.smul_with_overflow(a, b) prod = builder.extract_value(p, 0) prod_ovf = builder.extract_value(p, 1) s = builder.sadd_with_overflow(prod, c) res = builder.extract_value(s, 0) ovf = builder.or_(prod_ovf, builder.ex...
null
null
null
What does this function do?
def __virtual__(): if (salt.utils.is_windows() and _HAS_MODULE_DEPENDENCIES): return __virtualname__ return False
null
null
null
Only works on Windows systems.
pcsd
def virtual if salt utils is windows and HAS MODULE DEPENDENCIES return virtualname return False
9968
def __virtual__(): if (salt.utils.is_windows() and _HAS_MODULE_DEPENDENCIES): return __virtualname__ return False
Only works on Windows systems.
only works on windows systems .
Question: What does this function do? Code: def __virtual__(): if (salt.utils.is_windows() and _HAS_MODULE_DEPENDENCIES): return __virtualname__ return False
null
null
null
What does this function do?
@require_role('admin') def group_edit(request): (header_title, path1, path2) = (u'\u7f16\u8f91\u4e3b\u673a\u7ec4', u'\u8d44\u4ea7\u7ba1\u7406', u'\u7f16\u8f91\u4e3b\u673a\u7ec4') group_id = request.GET.get('id', '') group = get_object(AssetGroup, id=group_id) asset_all = Asset.objects.all() asset_select = Asset.ob...
null
null
null
Group edit view
pcsd
@require role 'admin' def group edit request header title path1 path2 = u'\u7f16\u8f91\u4e3b\u673a\u7ec4' u'\u8d44\u4ea7\u7ba1\u7406' u'\u7f16\u8f91\u4e3b\u673a\u7ec4' group id = request GET get 'id' '' group = get object Asset Group id=group id asset all = Asset objects all asset select = Asset objects filter group=gr...
9975
@require_role('admin') def group_edit(request): (header_title, path1, path2) = (u'\u7f16\u8f91\u4e3b\u673a\u7ec4', u'\u8d44\u4ea7\u7ba1\u7406', u'\u7f16\u8f91\u4e3b\u673a\u7ec4') group_id = request.GET.get('id', '') group = get_object(AssetGroup, id=group_id) asset_all = Asset.objects.all() asset_select = Asset.ob...
Group edit view
group edit view
Question: What does this function do? Code: @require_role('admin') def group_edit(request): (header_title, path1, path2) = (u'\u7f16\u8f91\u4e3b\u673a\u7ec4', u'\u8d44\u4ea7\u7ba1\u7406', u'\u7f16\u8f91\u4e3b\u673a\u7ec4') group_id = request.GET.get('id', '') group = get_object(AssetGroup, id=group_id) asset_all...
null
null
null
What does this function do?
def equal_any(*values): return IMPL.equal_any(*values)
null
null
null
Return an equality condition object suitable for use in a constraint. Equal_any conditions require that a model object\'s attribute equal any one of the given values.
pcsd
def equal any *values return IMPL equal any *values
9979
def equal_any(*values): return IMPL.equal_any(*values)
Return an equality condition object suitable for use in a constraint. Equal_any conditions require that a model object\'s attribute equal any one of the given values.
return an equality condition object suitable for use in a constraint .
Question: What does this function do? Code: def equal_any(*values): return IMPL.equal_any(*values)
null
null
null
What does this function do?
def massage_permissions(document): read_perms = document.list_permissions(perm='read') write_perms = document.list_permissions(perm='write') return {'perms': {'read': {'users': [{'id': perm_user.id, 'username': perm_user.username} for perm_user in read_perms.users.all()], 'groups': [{'id': perm_group.id, 'name': per...
null
null
null
Returns the permissions for a given document as a dictionary
pcsd
def massage permissions document read perms = document list permissions perm='read' write perms = document list permissions perm='write' return {'perms' {'read' {'users' [{'id' perm user id 'username' perm user username} for perm user in read perms users all ] 'groups' [{'id' perm group id 'name' perm group name} for p...
9984
def massage_permissions(document): read_perms = document.list_permissions(perm='read') write_perms = document.list_permissions(perm='write') return {'perms': {'read': {'users': [{'id': perm_user.id, 'username': perm_user.username} for perm_user in read_perms.users.all()], 'groups': [{'id': perm_group.id, 'name': per...
Returns the permissions for a given document as a dictionary
returns the permissions for a given document as a dictionary
Question: What does this function do? Code: def massage_permissions(document): read_perms = document.list_permissions(perm='read') write_perms = document.list_permissions(perm='write') return {'perms': {'read': {'users': [{'id': perm_user.id, 'username': perm_user.username} for perm_user in read_perms.users.all()...
null
null
null
What does this function do?
def _config_from_file(filename, config=None): if config: bravia_config = _config_from_file(filename) if (bravia_config is None): bravia_config = {} new_config = bravia_config.copy() new_config.update(config) try: with open(filename, 'w') as fdesc: fdesc.write(json.dumps(new_config)) except IOErro...
null
null
null
Create the configuration from a file.
pcsd
def config from file filename config=None if config bravia config = config from file filename if bravia config is None bravia config = {} new config = bravia config copy new config update config try with open filename 'w' as fdesc fdesc write json dumps new config except IO Error as error LOGGER error 'Saving config fi...
9987
def _config_from_file(filename, config=None): if config: bravia_config = _config_from_file(filename) if (bravia_config is None): bravia_config = {} new_config = bravia_config.copy() new_config.update(config) try: with open(filename, 'w') as fdesc: fdesc.write(json.dumps(new_config)) except IOErro...
Create the configuration from a file.
create the configuration from a file .
Question: What does this function do? Code: def _config_from_file(filename, config=None): if config: bravia_config = _config_from_file(filename) if (bravia_config is None): bravia_config = {} new_config = bravia_config.copy() new_config.update(config) try: with open(filename, 'w') as fdesc: fdes...
null
null
null
What does this function do?
def render_doc(thing, title='Python Library Documentation: %s', forceload=0): (object, name) = resolve(thing, forceload) desc = describe(object) module = inspect.getmodule(object) if (name and ('.' in name)): desc += (' in ' + name[:name.rfind('.')]) elif (module and (module is not object)): desc += (' in modu...
null
null
null
Render text documentation, given an object or a path to an object.
pcsd
def render doc thing title='Python Library Documentation %s' forceload=0 object name = resolve thing forceload desc = describe object module = inspect getmodule object if name and ' ' in name desc += ' in ' + name[ name rfind ' ' ] elif module and module is not object desc += ' in module ' + module name if type object ...
9996
def render_doc(thing, title='Python Library Documentation: %s', forceload=0): (object, name) = resolve(thing, forceload) desc = describe(object) module = inspect.getmodule(object) if (name and ('.' in name)): desc += (' in ' + name[:name.rfind('.')]) elif (module and (module is not object)): desc += (' in modu...
Render text documentation, given an object or a path to an object.
render text documentation , given an object or a path to an object .
Question: What does this function do? Code: def render_doc(thing, title='Python Library Documentation: %s', forceload=0): (object, name) = resolve(thing, forceload) desc = describe(object) module = inspect.getmodule(object) if (name and ('.' in name)): desc += (' in ' + name[:name.rfind('.')]) elif (module an...
null
null
null
What does this function do?
def get_text_box(text, fs): return (fs, text_len(len(text), fs))
null
null
null
Approximation of text bounds
pcsd
def get text box text fs return fs text len len text fs
9999
def get_text_box(text, fs): return (fs, text_len(len(text), fs))
Approximation of text bounds
approximation of text bounds
Question: What does this function do? Code: def get_text_box(text, fs): return (fs, text_len(len(text), fs))
null
null
null
What does this function do?
def compareFunctionName(first, second): first = getConvertedName(first) second = getConvertedName(second) if (first < second): return (-1) return (first < second)
null
null
null
Compare the function names.
pcsd
def compare Function Name first second first = get Converted Name first second = get Converted Name second if first < second return -1 return first < second
10008
def compareFunctionName(first, second): first = getConvertedName(first) second = getConvertedName(second) if (first < second): return (-1) return (first < second)
Compare the function names.
compare the function names .
Question: What does this function do? Code: def compareFunctionName(first, second): first = getConvertedName(first) second = getConvertedName(second) if (first < second): return (-1) return (first < second)
null
null
null
What does this function do?
def _get_default_context(request): types = Object.filter_by_request(request, ItemType.objects.filter(parent__isnull=True)) statuses = Object.filter_by_request(request, ItemStatus.objects) locations = Object.filter_by_request(request, Location.objects) massform = MassActionForm(request.user.profile) context = {'sta...
null
null
null
Returns default context for all views as dict()
pcsd
def get default context request types = Object filter by request request Item Type objects filter parent isnull=True statuses = Object filter by request request Item Status objects locations = Object filter by request request Location objects massform = Mass Action Form request user profile context = {'statuses' status...
10010
def _get_default_context(request): types = Object.filter_by_request(request, ItemType.objects.filter(parent__isnull=True)) statuses = Object.filter_by_request(request, ItemStatus.objects) locations = Object.filter_by_request(request, Location.objects) massform = MassActionForm(request.user.profile) context = {'sta...
Returns default context for all views as dict()
returns default context for all views as dict ( )
Question: What does this function do? Code: def _get_default_context(request): types = Object.filter_by_request(request, ItemType.objects.filter(parent__isnull=True)) statuses = Object.filter_by_request(request, ItemStatus.objects) locations = Object.filter_by_request(request, Location.objects) massform = MassAc...
null
null
null
What does this function do?
def generate_controllers(table, fieldname, ref): itext_list = [] controllers_list = [] field = table[fieldname] itext_list.append(TAG['text'](TAG['value'](field.label), _id=(ref + ':label'))) itext_list.append(TAG['text'](TAG['value'](field.comment), _id=(ref + ':hint'))) if hasattr(field.requires, 'option'): i...
null
null
null
Generates the controllers XML for the database table field. @todo: deprecate
pcsd
def generate controllers table fieldname ref itext list = [] controllers list = [] field = table[fieldname] itext list append TAG['text'] TAG['value'] field label id= ref + ' label' itext list append TAG['text'] TAG['value'] field comment id= ref + ' hint' if hasattr field requires 'option' items list = [] for option i...
10012
def generate_controllers(table, fieldname, ref): itext_list = [] controllers_list = [] field = table[fieldname] itext_list.append(TAG['text'](TAG['value'](field.label), _id=(ref + ':label'))) itext_list.append(TAG['text'](TAG['value'](field.comment), _id=(ref + ':hint'))) if hasattr(field.requires, 'option'): i...
Generates the controllers XML for the database table field. @todo: deprecate
generates the controllers xml for the database table field .
Question: What does this function do? Code: def generate_controllers(table, fieldname, ref): itext_list = [] controllers_list = [] field = table[fieldname] itext_list.append(TAG['text'](TAG['value'](field.label), _id=(ref + ':label'))) itext_list.append(TAG['text'](TAG['value'](field.comment), _id=(ref + ':hint...
null
null
null
What does this function do?
def inherit_nomination(sender, instance, **kw): if kw.get('raw'): return addon = instance.addon if ((instance.nomination is None) and (addon.status in amo.UNREVIEWED_ADDON_STATUSES) and (not instance.is_beta)): last_ver = Version.objects.filter(addon=addon).exclude(nomination=None).order_by('-nomination') if l...
null
null
null
For new versions pending review, ensure nomination date is inherited from last nominated version.
pcsd
def inherit nomination sender instance **kw if kw get 'raw' return addon = instance addon if instance nomination is None and addon status in amo UNREVIEWED ADDON STATUSES and not instance is beta last ver = Version objects filter addon=addon exclude nomination=None order by '-nomination' if last ver exists instance res...
10015
def inherit_nomination(sender, instance, **kw): if kw.get('raw'): return addon = instance.addon if ((instance.nomination is None) and (addon.status in amo.UNREVIEWED_ADDON_STATUSES) and (not instance.is_beta)): last_ver = Version.objects.filter(addon=addon).exclude(nomination=None).order_by('-nomination') if l...
For new versions pending review, ensure nomination date is inherited from last nominated version.
for new versions pending review , ensure nomination date is inherited from last nominated version .
Question: What does this function do? Code: def inherit_nomination(sender, instance, **kw): if kw.get('raw'): return addon = instance.addon if ((instance.nomination is None) and (addon.status in amo.UNREVIEWED_ADDON_STATUSES) and (not instance.is_beta)): last_ver = Version.objects.filter(addon=addon).exclude(...
null
null
null
What does this function do?
def update_last_login(sender, user, **kwargs): user.last_login = timezone.now() user.save(update_fields=['last_login'])
null
null
null
A signal receiver which updates the last_login date for the user logging in.
pcsd
def update last login sender user **kwargs user last login = timezone now user save update fields=['last login']
10018
def update_last_login(sender, user, **kwargs): user.last_login = timezone.now() user.save(update_fields=['last_login'])
A signal receiver which updates the last_login date for the user logging in.
a signal receiver which updates the last _ login date for the user logging in .
Question: What does this function do? Code: def update_last_login(sender, user, **kwargs): user.last_login = timezone.now() user.save(update_fields=['last_login'])
null
null
null
What does this function do?
def validate_path_exists(s): if (s is None): return None if os.path.exists(s): return s else: raise RuntimeError((u'"%s" should be a path but it does not exist' % s))
null
null
null
If s is a path, return s, else False
pcsd
def validate path exists s if s is None return None if os path exists s return s else raise Runtime Error u'"%s" should be a path but it does not exist' % s
10036
def validate_path_exists(s): if (s is None): return None if os.path.exists(s): return s else: raise RuntimeError((u'"%s" should be a path but it does not exist' % s))
If s is a path, return s, else False
if s is a path , return s , else false
Question: What does this function do? Code: def validate_path_exists(s): if (s is None): return None if os.path.exists(s): return s else: raise RuntimeError((u'"%s" should be a path but it does not exist' % s))
null
null
null
What does this function do?
def reducer(*tokens): def decorator(func): if (not hasattr(func, 'reducers')): func.reducers = [] func.reducers.append(list(tokens)) return func return decorator
null
null
null
Decorator for reduction methods. Arguments are a sequence of tokens, in order, which should trigger running this reduction method.
pcsd
def reducer *tokens def decorator func if not hasattr func 'reducers' func reducers = [] func reducers append list tokens return func return decorator
10043
def reducer(*tokens): def decorator(func): if (not hasattr(func, 'reducers')): func.reducers = [] func.reducers.append(list(tokens)) return func return decorator
Decorator for reduction methods. Arguments are a sequence of tokens, in order, which should trigger running this reduction method.
decorator for reduction methods .
Question: What does this function do? Code: def reducer(*tokens): def decorator(func): if (not hasattr(func, 'reducers')): func.reducers = [] func.reducers.append(list(tokens)) return func return decorator
null
null
null
What does this function do?
def filename(): if (not _state): raise RuntimeError('no active input()') return _state.filename()
null
null
null
Return the name of the file currently being read. Before the first line has been read, returns None.
pcsd
def filename if not state raise Runtime Error 'no active input ' return state filename
10046
def filename(): if (not _state): raise RuntimeError('no active input()') return _state.filename()
Return the name of the file currently being read. Before the first line has been read, returns None.
return the name of the file currently being read .
Question: What does this function do? Code: def filename(): if (not _state): raise RuntimeError('no active input()') return _state.filename()
null
null
null
What does this function do?
def init_list(doctype): doc = frappe.get_meta(doctype) make_boilerplate(u'controller_list.js', doc) make_boilerplate(u'controller_list.html', doc)
null
null
null
Make boilerplate list views.
pcsd
def init list doctype doc = frappe get meta doctype make boilerplate u'controller list js' doc make boilerplate u'controller list html' doc
10049
def init_list(doctype): doc = frappe.get_meta(doctype) make_boilerplate(u'controller_list.js', doc) make_boilerplate(u'controller_list.html', doc)
Make boilerplate list views.
make boilerplate list views .
Question: What does this function do? Code: def init_list(doctype): doc = frappe.get_meta(doctype) make_boilerplate(u'controller_list.js', doc) make_boilerplate(u'controller_list.html', doc)
null
null
null
What does this function do?
def file_props(root, path): abspath = os.path.join(root, path) try: st = os.lstat(abspath) except OSError as e: display.warning(('filetree: Error using stat() on path %s (%s)' % (abspath, e))) return None ret = dict(root=root, path=path) if stat.S_ISLNK(st.st_mode): ret['state'] = 'link' ret['src'] = os....
null
null
null
Returns dictionary with file properties, or return None on failure
pcsd
def file props root path abspath = os path join root path try st = os lstat abspath except OS Error as e display warning 'filetree Error using stat on path %s %s ' % abspath e return None ret = dict root=root path=path if stat S ISLNK st st mode ret['state'] = 'link' ret['src'] = os readlink abspath elif stat S ISDIR s...
10068
def file_props(root, path): abspath = os.path.join(root, path) try: st = os.lstat(abspath) except OSError as e: display.warning(('filetree: Error using stat() on path %s (%s)' % (abspath, e))) return None ret = dict(root=root, path=path) if stat.S_ISLNK(st.st_mode): ret['state'] = 'link' ret['src'] = os....
Returns dictionary with file properties, or return None on failure
returns dictionary with file properties , or return none on failure
Question: What does this function do? Code: def file_props(root, path): abspath = os.path.join(root, path) try: st = os.lstat(abspath) except OSError as e: display.warning(('filetree: Error using stat() on path %s (%s)' % (abspath, e))) return None ret = dict(root=root, path=path) if stat.S_ISLNK(st.st_mo...
null
null
null
What does this function do?
def get_path_names(): return _SCHEMES.options('posix_prefix')
null
null
null
Return a tuple containing the paths names.
pcsd
def get path names return SCHEMES options 'posix prefix'
10070
def get_path_names(): return _SCHEMES.options('posix_prefix')
Return a tuple containing the paths names.
return a tuple containing the paths names .
Question: What does this function do? Code: def get_path_names(): return _SCHEMES.options('posix_prefix')
null
null
null
What does this function do?
def resolve_email_domain(domain): request = DNS.Request() reply = request.req(name=sys.argv[1], qtype=DNS.Type.MX) if reply.answers: print ('The domain %r has explicit MX records!' % (domain,)) print 'Try the servers in this order:' datalist = [answer['data'] for answer in reply.answers] datalist.sort() fo...
null
null
null
Print mail server IP addresses for an email address @ `domain`.
pcsd
def resolve email domain domain request = DNS Request reply = request req name=sys argv[1] qtype=DNS Type MX if reply answers print 'The domain %r has explicit MX records!' % domain print 'Try the servers in this order ' datalist = [answer['data'] for answer in reply answers] datalist sort for data in datalist priority...
10073
def resolve_email_domain(domain): request = DNS.Request() reply = request.req(name=sys.argv[1], qtype=DNS.Type.MX) if reply.answers: print ('The domain %r has explicit MX records!' % (domain,)) print 'Try the servers in this order:' datalist = [answer['data'] for answer in reply.answers] datalist.sort() fo...
Print mail server IP addresses for an email address @ `domain`.
print mail server ip addresses for an email address @ domain .
Question: What does this function do? Code: def resolve_email_domain(domain): request = DNS.Request() reply = request.req(name=sys.argv[1], qtype=DNS.Type.MX) if reply.answers: print ('The domain %r has explicit MX records!' % (domain,)) print 'Try the servers in this order:' datalist = [answer['data'] for ...
null
null
null
What does this function do?
def parse_call_group(source, info, ch, pos): if (ch == 'R'): group = '0' else: group = (ch + source.get_while(DIGITS)) source.expect(')') return CallGroup(info, group, pos)
null
null
null
Parses a call to a group.
pcsd
def parse call group source info ch pos if ch == 'R' group = '0' else group = ch + source get while DIGITS source expect ' ' return Call Group info group pos
10075
def parse_call_group(source, info, ch, pos): if (ch == 'R'): group = '0' else: group = (ch + source.get_while(DIGITS)) source.expect(')') return CallGroup(info, group, pos)
Parses a call to a group.
parses a call to a group .
Question: What does this function do? Code: def parse_call_group(source, info, ch, pos): if (ch == 'R'): group = '0' else: group = (ch + source.get_while(DIGITS)) source.expect(')') return CallGroup(info, group, pos)
null
null
null
What does this function do?
def detect(fp, max_read=1024): if (not is_filelike(fp)): return None for Format in _registry.values(): if Format.detect(fp.read(max_read)): fp.seek(0) return Format fp.seek(0) return None
null
null
null
Attempt to detect a file\'s format, trying each of the supported formats. Return the format class that was detected. If no format is detected, return ``None``.
pcsd
def detect fp max read=1024 if not is filelike fp return None for Format in registry values if Format detect fp read max read fp seek 0 return Format fp seek 0 return None
10085
def detect(fp, max_read=1024): if (not is_filelike(fp)): return None for Format in _registry.values(): if Format.detect(fp.read(max_read)): fp.seek(0) return Format fp.seek(0) return None
Attempt to detect a file\'s format, trying each of the supported formats. Return the format class that was detected. If no format is detected, return ``None``.
attempt to detect a files format , trying each of the supported formats .
Question: What does this function do? Code: def detect(fp, max_read=1024): if (not is_filelike(fp)): return None for Format in _registry.values(): if Format.detect(fp.read(max_read)): fp.seek(0) return Format fp.seek(0) return None
null
null
null
What does this function do?
def user_media_path(what): default = os.path.join(settings.MEDIA_ROOT, what) key = '{0}_PATH'.format(what.upper()) return getattr(settings, key, default)
null
null
null
Make it possible to override storage paths in settings. By default, all storage paths are in the MEDIA_ROOT. This is backwards compatible.
pcsd
def user media path what default = os path join settings MEDIA ROOT what key = '{0} PATH' format what upper return getattr settings key default
10092
def user_media_path(what): default = os.path.join(settings.MEDIA_ROOT, what) key = '{0}_PATH'.format(what.upper()) return getattr(settings, key, default)
Make it possible to override storage paths in settings. By default, all storage paths are in the MEDIA_ROOT. This is backwards compatible.
make it possible to override storage paths in settings .
Question: What does this function do? Code: def user_media_path(what): default = os.path.join(settings.MEDIA_ROOT, what) key = '{0}_PATH'.format(what.upper()) return getattr(settings, key, default)
null
null
null
What does this function do?
@staff_member_required def admin_page_ordering(request): def get_id(s): s = s.split(u'_')[(-1)] return (int(s) if s.isdigit() else None) page = get_object_or_404(Page, id=get_id(request.POST[u'id'])) old_parent_id = page.parent_id new_parent_id = get_id(request.POST[u'parent_id']) new_parent = (Page.objects.ge...
null
null
null
Updates the ordering of pages via AJAX from within the admin.
pcsd
@staff member required def admin page ordering request def get id s s = s split u' ' [ -1 ] return int s if s isdigit else None page = get object or 404 Page id=get id request POST[u'id'] old parent id = page parent id new parent id = get id request POST[u'parent id'] new parent = Page objects get id=new parent id if n...
10102
@staff_member_required def admin_page_ordering(request): def get_id(s): s = s.split(u'_')[(-1)] return (int(s) if s.isdigit() else None) page = get_object_or_404(Page, id=get_id(request.POST[u'id'])) old_parent_id = page.parent_id new_parent_id = get_id(request.POST[u'parent_id']) new_parent = (Page.objects.ge...
Updates the ordering of pages via AJAX from within the admin.
updates the ordering of pages via ajax from within the admin .
Question: What does this function do? Code: @staff_member_required def admin_page_ordering(request): def get_id(s): s = s.split(u'_')[(-1)] return (int(s) if s.isdigit() else None) page = get_object_or_404(Page, id=get_id(request.POST[u'id'])) old_parent_id = page.parent_id new_parent_id = get_id(request.POS...
null
null
null
What does this function do?
def _convert_to_idn(url): parts = list(urlparse.urlsplit(url)) try: parts[1].encode('ascii') except UnicodeEncodeError: host = parts[1].rsplit(':', 1) newhost = [] port = u'' if (len(host) == 2): port = host.pop() for h in host[0].split('.'): newhost.append(h.encode('idna').decode('utf-8')) parts...
null
null
null
Convert a URL to IDN notation
pcsd
def convert to idn url parts = list urlparse urlsplit url try parts[1] encode 'ascii' except Unicode Encode Error host = parts[1] rsplit ' ' 1 newhost = [] port = u'' if len host == 2 port = host pop for h in host[0] split ' ' newhost append h encode 'idna' decode 'utf-8' parts[1] = ' ' join newhost if port parts[1] +=...
10111
def _convert_to_idn(url): parts = list(urlparse.urlsplit(url)) try: parts[1].encode('ascii') except UnicodeEncodeError: host = parts[1].rsplit(':', 1) newhost = [] port = u'' if (len(host) == 2): port = host.pop() for h in host[0].split('.'): newhost.append(h.encode('idna').decode('utf-8')) parts...
Convert a URL to IDN notation
convert a url to idn notation
Question: What does this function do? Code: def _convert_to_idn(url): parts = list(urlparse.urlsplit(url)) try: parts[1].encode('ascii') except UnicodeEncodeError: host = parts[1].rsplit(':', 1) newhost = [] port = u'' if (len(host) == 2): port = host.pop() for h in host[0].split('.'): newhost.a...
null
null
null
What does this function do?
def job_title(): mode = session.s3.hrm.mode def prep(r): if (mode is not None): auth.permission.fail() elif (r.representation == 'xls'): current.messages['NONE'] = '' table = s3db.hrm_job_title table.organisation_id.represent = s3db.org_OrganisationRepresent(acronym=False, parent=False) table.organ...
null
null
null
Job Titles Controller
pcsd
def job title mode = session s3 hrm mode def prep r if mode is not None auth permission fail elif r representation == 'xls' current messages['NONE'] = '' table = s3db hrm job title table organisation id represent = s3db org Organisation Represent acronym=False parent=False table organisation id label = None table type ...
10113
def job_title(): mode = session.s3.hrm.mode def prep(r): if (mode is not None): auth.permission.fail() elif (r.representation == 'xls'): current.messages['NONE'] = '' table = s3db.hrm_job_title table.organisation_id.represent = s3db.org_OrganisationRepresent(acronym=False, parent=False) table.organ...
Job Titles Controller
job titles controller
Question: What does this function do? Code: def job_title(): mode = session.s3.hrm.mode def prep(r): if (mode is not None): auth.permission.fail() elif (r.representation == 'xls'): current.messages['NONE'] = '' table = s3db.hrm_job_title table.organisation_id.represent = s3db.org_OrganisationRepres...
null
null
null
What does this function do?
def _termination_condition(t, k, g, n, s, alpha, delta): diff = (k - solow_steady_state(g, n, s, alpha, delta)) return diff
null
null
null
Terminate solver when we get close to steady state.
pcsd
def termination condition t k g n s alpha delta diff = k - solow steady state g n s alpha delta return diff
10120
def _termination_condition(t, k, g, n, s, alpha, delta): diff = (k - solow_steady_state(g, n, s, alpha, delta)) return diff
Terminate solver when we get close to steady state.
terminate solver when we get close to steady state .
Question: What does this function do? Code: def _termination_condition(t, k, g, n, s, alpha, delta): diff = (k - solow_steady_state(g, n, s, alpha, delta)) return diff
null
null
null
What does this function do?
def extract_module_locals(depth=0): f = sys._getframe((depth + 1)) global_ns = f.f_globals module = sys.modules[global_ns['__name__']] return (module, f.f_locals)
null
null
null
Returns (module, locals) of the function `depth` frames away from the caller
pcsd
def extract module locals depth=0 f = sys getframe depth + 1 global ns = f f globals module = sys modules[global ns[' name ']] return module f f locals
10127
def extract_module_locals(depth=0): f = sys._getframe((depth + 1)) global_ns = f.f_globals module = sys.modules[global_ns['__name__']] return (module, f.f_locals)
Returns (module, locals) of the function `depth` frames away from the caller
returns of the function depth frames away from the caller
Question: What does this function do? Code: def extract_module_locals(depth=0): f = sys._getframe((depth + 1)) global_ns = f.f_globals module = sys.modules[global_ns['__name__']] return (module, f.f_locals)
null
null
null
What does this function do?
@cli.command() def clone(): click.echo('Clone')
null
null
null
Clones a repository.
pcsd
@cli command def clone click echo 'Clone'
10130
@cli.command() def clone(): click.echo('Clone')
Clones a repository.
clones a repository .
Question: What does this function do? Code: @cli.command() def clone(): click.echo('Clone')
null
null
null
What does this function do?
def retrieve_flags(flag_dict, flag_filter): return [(f[0], f[1]) for f in list(flag_dict.items()) if (isinstance(f[0], (str, bytes)) and f[0].startswith(flag_filter))]
null
null
null
Read the flags from a dictionary and return them in a usable form. Will return a list of (flag, value) for all flags in "flag_dict" matching the filter "flag_filter".
pcsd
def retrieve flags flag dict flag filter return [ f[0] f[1] for f in list flag dict items if isinstance f[0] str bytes and f[0] startswith flag filter ]
10133
def retrieve_flags(flag_dict, flag_filter): return [(f[0], f[1]) for f in list(flag_dict.items()) if (isinstance(f[0], (str, bytes)) and f[0].startswith(flag_filter))]
Read the flags from a dictionary and return them in a usable form. Will return a list of (flag, value) for all flags in "flag_dict" matching the filter "flag_filter".
read the flags from a dictionary and return them in a usable form .
Question: What does this function do? Code: def retrieve_flags(flag_dict, flag_filter): return [(f[0], f[1]) for f in list(flag_dict.items()) if (isinstance(f[0], (str, bytes)) and f[0].startswith(flag_filter))]
null
null
null
What does this function do?
def staff(): return s3_rest_controller()
null
null
null
REST controller for budget_staff
pcsd
def staff return s3 rest controller
10142
def staff(): return s3_rest_controller()
REST controller for budget_staff
rest controller for budget _ staff
Question: What does this function do? Code: def staff(): return s3_rest_controller()
null
null
null
What does this function do?
def supports_caller(func): def wrap_stackframe(context, *args, **kwargs): context.caller_stack._push_frame() try: return func(context, *args, **kwargs) finally: context.caller_stack._pop_frame() return wrap_stackframe
null
null
null
Apply a caller_stack compatibility decorator to a plain Python function. See the example in :ref:`namespaces_python_modules`.
pcsd
def supports caller func def wrap stackframe context *args **kwargs context caller stack push frame try return func context *args **kwargs finally context caller stack pop frame return wrap stackframe
10143
def supports_caller(func): def wrap_stackframe(context, *args, **kwargs): context.caller_stack._push_frame() try: return func(context, *args, **kwargs) finally: context.caller_stack._pop_frame() return wrap_stackframe
Apply a caller_stack compatibility decorator to a plain Python function. See the example in :ref:`namespaces_python_modules`.
apply a caller _ stack compatibility decorator to a plain
Question: What does this function do? Code: def supports_caller(func): def wrap_stackframe(context, *args, **kwargs): context.caller_stack._push_frame() try: return func(context, *args, **kwargs) finally: context.caller_stack._pop_frame() return wrap_stackframe
null
null
null
What does this function do?
def mangle_signature(sig, max_chars=30): s = re.sub('^\\((.*)\\)$', '\\1', sig).strip() s = re.sub('\\\\\\\\', '', s) s = re.sub("\\\\'", '', s) s = re.sub("'[^']*'", '', s) args = [] opts = [] opt_re = re.compile('^(.*, |)([a-zA-Z0-9_*]+)=') while s: m = opt_re.search(s) if (not m): args = s.split(', ')...
null
null
null
Reformat a function signature to a more compact form.
pcsd
def mangle signature sig max chars=30 s = re sub '^\\ * \\ $' '\\1' sig strip s = re sub '\\\\\\\\' '' s s = re sub "\\\\'" '' s s = re sub "'[^']*'" '' s args = [] opts = [] opt re = re compile '^ * | [a-z A-Z0-9 *]+ =' while s m = opt re search s if not m args = s split ' ' break opts insert 0 m group 2 s = m group 1...
10147
def mangle_signature(sig, max_chars=30): s = re.sub('^\\((.*)\\)$', '\\1', sig).strip() s = re.sub('\\\\\\\\', '', s) s = re.sub("\\\\'", '', s) s = re.sub("'[^']*'", '', s) args = [] opts = [] opt_re = re.compile('^(.*, |)([a-zA-Z0-9_*]+)=') while s: m = opt_re.search(s) if (not m): args = s.split(', ')...
Reformat a function signature to a more compact form.
reformat a function signature to a more compact form .
Question: What does this function do? Code: def mangle_signature(sig, max_chars=30): s = re.sub('^\\((.*)\\)$', '\\1', sig).strip() s = re.sub('\\\\\\\\', '', s) s = re.sub("\\\\'", '', s) s = re.sub("'[^']*'", '', s) args = [] opts = [] opt_re = re.compile('^(.*, |)([a-zA-Z0-9_*]+)=') while s: m = opt_re....
null
null
null
What does this function do?
def create_srv_socket(address): listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listener.bind(address) listener.listen(64) print 'Listening at {}'.format(address) return listener
null
null
null
Build and return a listening server socket.
pcsd
def create srv socket address listener = socket socket socket AF INET socket SOCK STREAM listener setsockopt socket SOL SOCKET socket SO REUSEADDR 1 listener bind address listener listen 64 print 'Listening at {}' format address return listener
10152
def create_srv_socket(address): listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listener.bind(address) listener.listen(64) print 'Listening at {}'.format(address) return listener
Build and return a listening server socket.
build and return a listening server socket .
Question: What does this function do? Code: def create_srv_socket(address): listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listener.bind(address) listener.listen(64) print 'Listening at {}'.format(address) return listener
null
null
null
What does this function do?
@inspect_command(alias=u'dump_reserved') def reserved(state, **kwargs): reserved_tasks = (state.tset(worker_state.reserved_requests) - state.tset(worker_state.active_requests)) if (not reserved_tasks): return [] return [request.info() for request in reserved_tasks]
null
null
null
List of currently reserved tasks, not including scheduled/active.
pcsd
@inspect command alias=u'dump reserved' def reserved state **kwargs reserved tasks = state tset worker state reserved requests - state tset worker state active requests if not reserved tasks return [] return [request info for request in reserved tasks]
10153
@inspect_command(alias=u'dump_reserved') def reserved(state, **kwargs): reserved_tasks = (state.tset(worker_state.reserved_requests) - state.tset(worker_state.active_requests)) if (not reserved_tasks): return [] return [request.info() for request in reserved_tasks]
List of currently reserved tasks, not including scheduled/active.
list of currently reserved tasks , not including scheduled / active .
Question: What does this function do? Code: @inspect_command(alias=u'dump_reserved') def reserved(state, **kwargs): reserved_tasks = (state.tset(worker_state.reserved_requests) - state.tset(worker_state.active_requests)) if (not reserved_tasks): return [] return [request.info() for request in reserved_tasks]
null
null
null
What does this function do?
@webauth.SecurityCheck @renderers.ErrorHandler() def RenderGenericRenderer(request): if (LEGACY_RENDERERS_AUTH_MANAGER and (not LEGACY_RENDERERS_AUTH_MANAGER.CheckPermissions(request.user, 'legacy_renderers'))): return AccessDenied('User is not allowed to use legacy renderers.') try: (action, renderer_name) = req...
null
null
null
Django handler for rendering registered GUI Elements.
pcsd
@webauth Security Check @renderers Error Handler def Render Generic Renderer request if LEGACY RENDERERS AUTH MANAGER and not LEGACY RENDERERS AUTH MANAGER Check Permissions request user 'legacy renderers' return Access Denied 'User is not allowed to use legacy renderers ' try action renderer name = request path split ...
10162
@webauth.SecurityCheck @renderers.ErrorHandler() def RenderGenericRenderer(request): if (LEGACY_RENDERERS_AUTH_MANAGER and (not LEGACY_RENDERERS_AUTH_MANAGER.CheckPermissions(request.user, 'legacy_renderers'))): return AccessDenied('User is not allowed to use legacy renderers.') try: (action, renderer_name) = req...
Django handler for rendering registered GUI Elements.
django handler for rendering registered gui elements .
Question: What does this function do? Code: @webauth.SecurityCheck @renderers.ErrorHandler() def RenderGenericRenderer(request): if (LEGACY_RENDERERS_AUTH_MANAGER and (not LEGACY_RENDERERS_AUTH_MANAGER.CheckPermissions(request.user, 'legacy_renderers'))): return AccessDenied('User is not allowed to use legacy ren...
null
null
null
What does this function do?
def cell_with_item(cell_name, item): if (cell_name is None): return item return ((cell_name + _CELL_ITEM_SEP) + str(item))
null
null
null
Turn cell_name and item into <cell_name>@<item>.
pcsd
def cell with item cell name item if cell name is None return item return cell name + CELL ITEM SEP + str item
10164
def cell_with_item(cell_name, item): if (cell_name is None): return item return ((cell_name + _CELL_ITEM_SEP) + str(item))
Turn cell_name and item into <cell_name>@<item>.
turn cell _ name and item into @ .
Question: What does this function do? Code: def cell_with_item(cell_name, item): if (cell_name is None): return item return ((cell_name + _CELL_ITEM_SEP) + str(item))
null
null
null
What does this function do?
def conv1d_sd(input, filters, image_shape, filter_shape, border_mode='valid', subsample=(1,), filter_flip=True): if (border_mode not in ('valid', 0, (0,))): raise RuntimeError(('Unsupported border_mode for conv1d_sd: %s' % border_mode)) (batch_size, num_input_channels, input_length) = image_shape (num_filters, num...
null
null
null
using a single dot product
pcsd
def conv1d sd input filters image shape filter shape border mode='valid' subsample= 1 filter flip=True if border mode not in 'valid' 0 0 raise Runtime Error 'Unsupported border mode for conv1d sd %s' % border mode batch size num input channels input length = image shape num filters num input channels filter length = fi...
10165
def conv1d_sd(input, filters, image_shape, filter_shape, border_mode='valid', subsample=(1,), filter_flip=True): if (border_mode not in ('valid', 0, (0,))): raise RuntimeError(('Unsupported border_mode for conv1d_sd: %s' % border_mode)) (batch_size, num_input_channels, input_length) = image_shape (num_filters, num...
using a single dot product
using a single dot product
Question: What does this function do? Code: def conv1d_sd(input, filters, image_shape, filter_shape, border_mode='valid', subsample=(1,), filter_flip=True): if (border_mode not in ('valid', 0, (0,))): raise RuntimeError(('Unsupported border_mode for conv1d_sd: %s' % border_mode)) (batch_size, num_input_channels,...
null
null
null
What does this function do?
def _RecCopyFiles(rebalance, server_id, dspath, subpath, pool_cache, removed_list): fulldir = utils.JoinPath(dspath, subpath) mapping = rebalance.mapping for comp in os.listdir(fulldir): if (comp == constants.REBALANCE_DIRECTORY): continue path = utils.JoinPath(fulldir, comp) (name, unused_extension) = os.p...
null
null
null
Recursively send files for moving to the required data server.
pcsd
def Rec Copy Files rebalance server id dspath subpath pool cache removed list fulldir = utils Join Path dspath subpath mapping = rebalance mapping for comp in os listdir fulldir if comp == constants REBALANCE DIRECTORY continue path = utils Join Path fulldir comp name unused extension = os path splitext comp if name in...
10166
def _RecCopyFiles(rebalance, server_id, dspath, subpath, pool_cache, removed_list): fulldir = utils.JoinPath(dspath, subpath) mapping = rebalance.mapping for comp in os.listdir(fulldir): if (comp == constants.REBALANCE_DIRECTORY): continue path = utils.JoinPath(fulldir, comp) (name, unused_extension) = os.p...
Recursively send files for moving to the required data server.
recursively send files for moving to the required data server .
Question: What does this function do? Code: def _RecCopyFiles(rebalance, server_id, dspath, subpath, pool_cache, removed_list): fulldir = utils.JoinPath(dspath, subpath) mapping = rebalance.mapping for comp in os.listdir(fulldir): if (comp == constants.REBALANCE_DIRECTORY): continue path = utils.JoinPath(f...
null
null
null
What does this function do?
@receiver(COURSE_CERT_AWARDED, sender=GeneratedCertificate) def create_course_badge(sender, user, course_key, status, **kwargs): course_badge_check(user, course_key)
null
null
null
Standard signal hook to create course badges when a certificate has been generated.
pcsd
@receiver COURSE CERT AWARDED sender=Generated Certificate def create course badge sender user course key status **kwargs course badge check user course key
10170
@receiver(COURSE_CERT_AWARDED, sender=GeneratedCertificate) def create_course_badge(sender, user, course_key, status, **kwargs): course_badge_check(user, course_key)
Standard signal hook to create course badges when a certificate has been generated.
standard signal hook to create course badges when a certificate has been generated .
Question: What does this function do? Code: @receiver(COURSE_CERT_AWARDED, sender=GeneratedCertificate) def create_course_badge(sender, user, course_key, status, **kwargs): course_badge_check(user, course_key)
null
null
null
What does this function do?
def setup_version_redirection(config): settings = config.get_settings() redirect_enabled = settings['version_prefix_redirect_enabled'] version_prefix_redirection_enabled = asbool(redirect_enabled) route_prefix = config.route_prefix config.registry.route_prefix = route_prefix if (not version_prefix_redirection_ena...
null
null
null
Add a view which redirects to the current version of the API.
pcsd
def setup version redirection config settings = config get settings redirect enabled = settings['version prefix redirect enabled'] version prefix redirection enabled = asbool redirect enabled route prefix = config route prefix config registry route prefix = route prefix if not version prefix redirection enabled return ...
10171
def setup_version_redirection(config): settings = config.get_settings() redirect_enabled = settings['version_prefix_redirect_enabled'] version_prefix_redirection_enabled = asbool(redirect_enabled) route_prefix = config.route_prefix config.registry.route_prefix = route_prefix if (not version_prefix_redirection_ena...
Add a view which redirects to the current version of the API.
add a view which redirects to the current version of the api .
Question: What does this function do? Code: def setup_version_redirection(config): settings = config.get_settings() redirect_enabled = settings['version_prefix_redirect_enabled'] version_prefix_redirection_enabled = asbool(redirect_enabled) route_prefix = config.route_prefix config.registry.route_prefix = route...
null
null
null
What does this function do?
@handle_response_format @treeio_login_required @module_admin_required() def page_edit(request, page_id, response_format='html'): page = get_object_or_404(Page, pk=page_id) if request.POST: form = PageForm(request.POST, instance=page) if form.is_valid(): page = form.save() return HttpResponseRedirect(reverse...
null
null
null
Static Page edit
pcsd
@handle response format @treeio login required @module admin required def page edit request page id response format='html' page = get object or 404 Page pk=page id if request POST form = Page Form request POST instance=page if form is valid page = form save return Http Response Redirect reverse 'core admin page view' a...
10177
@handle_response_format @treeio_login_required @module_admin_required() def page_edit(request, page_id, response_format='html'): page = get_object_or_404(Page, pk=page_id) if request.POST: form = PageForm(request.POST, instance=page) if form.is_valid(): page = form.save() return HttpResponseRedirect(reverse...
Static Page edit
static page edit
Question: What does this function do? Code: @handle_response_format @treeio_login_required @module_admin_required() def page_edit(request, page_id, response_format='html'): page = get_object_or_404(Page, pk=page_id) if request.POST: form = PageForm(request.POST, instance=page) if form.is_valid(): page = for...
null
null
null
What does this function do?
def pixelCollision(rect1, rect2, hitmask1, hitmask2): rect = rect1.clip(rect2) if ((rect.width == 0) or (rect.height == 0)): return False (x1, y1) = ((rect.x - rect1.x), (rect.y - rect1.y)) (x2, y2) = ((rect.x - rect2.x), (rect.y - rect2.y)) for x in range(rect.width): for y in range(rect.height): if (hitma...
null
null
null
Checks if two objects collide and not just their rects
pcsd
def pixel Collision rect1 rect2 hitmask1 hitmask2 rect = rect1 clip rect2 if rect width == 0 or rect height == 0 return False x1 y1 = rect x - rect1 x rect y - rect1 y x2 y2 = rect x - rect2 x rect y - rect2 y for x in range rect width for y in range rect height if hitmask1[ x1 + x ][ y1 + y ] and hitmask2[ x2 + x ][ y...
10178
def pixelCollision(rect1, rect2, hitmask1, hitmask2): rect = rect1.clip(rect2) if ((rect.width == 0) or (rect.height == 0)): return False (x1, y1) = ((rect.x - rect1.x), (rect.y - rect1.y)) (x2, y2) = ((rect.x - rect2.x), (rect.y - rect2.y)) for x in range(rect.width): for y in range(rect.height): if (hitma...
Checks if two objects collide and not just their rects
checks if two objects collide and not just their rects
Question: What does this function do? Code: def pixelCollision(rect1, rect2, hitmask1, hitmask2): rect = rect1.clip(rect2) if ((rect.width == 0) or (rect.height == 0)): return False (x1, y1) = ((rect.x - rect1.x), (rect.y - rect1.y)) (x2, y2) = ((rect.x - rect2.x), (rect.y - rect2.y)) for x in range(rect.widt...
null
null
null
What does this function do?
def parse_http(pkt): payload = pkt.getlayer(Raw).load (usr, pswd) = (None, None) if (('username' in payload) or ('password' in payload)): usr = re.search('username=(.*?)(&|$| )', payload) pswd = re.search('password=(.*?)(&|$| )', payload) if (usr is not None): usr = usr.groups(0)[0] if (pswd is not None):...
null
null
null
Parse out the username/password from an HTTP request. This will also parse out any basic authorization requests.
pcsd
def parse http pkt payload = pkt getlayer Raw load usr pswd = None None if 'username' in payload or 'password' in payload usr = re search 'username= *? &|$| ' payload pswd = re search 'password= *? &|$| ' payload if usr is not None usr = usr groups 0 [0] if pswd is not None pswd = pswd groups 0 [0] elif 'Authorization ...
10180
def parse_http(pkt): payload = pkt.getlayer(Raw).load (usr, pswd) = (None, None) if (('username' in payload) or ('password' in payload)): usr = re.search('username=(.*?)(&|$| )', payload) pswd = re.search('password=(.*?)(&|$| )', payload) if (usr is not None): usr = usr.groups(0)[0] if (pswd is not None):...
Parse out the username/password from an HTTP request. This will also parse out any basic authorization requests.
parse out the username / password from an http request .
Question: What does this function do? Code: def parse_http(pkt): payload = pkt.getlayer(Raw).load (usr, pswd) = (None, None) if (('username' in payload) or ('password' in payload)): usr = re.search('username=(.*?)(&|$| )', payload) pswd = re.search('password=(.*?)(&|$| )', payload) if (usr is not None): ...
null
null
null
What does this function do?
def getLoopsDifference(importRadius, loopLists): halfImportRadius = (0.5 * importRadius) radiusSide = (0.01 * importRadius) negativeLoops = getLoopsUnion(importRadius, loopLists[1:]) intercircle.directLoops(False, negativeLoops) positiveLoops = loopLists[0] intercircle.directLoops(True, positiveLoops) corners = ...
null
null
null
Get difference loops.
pcsd
def get Loops Difference import Radius loop Lists half Import Radius = 0 5 * import Radius radius Side = 0 01 * import Radius negative Loops = get Loops Union import Radius loop Lists[1 ] intercircle direct Loops False negative Loops positive Loops = loop Lists[0] intercircle direct Loops True positive Loops corners = ...
10183
def getLoopsDifference(importRadius, loopLists): halfImportRadius = (0.5 * importRadius) radiusSide = (0.01 * importRadius) negativeLoops = getLoopsUnion(importRadius, loopLists[1:]) intercircle.directLoops(False, negativeLoops) positiveLoops = loopLists[0] intercircle.directLoops(True, positiveLoops) corners = ...
Get difference loops.
get difference loops .
Question: What does this function do? Code: def getLoopsDifference(importRadius, loopLists): halfImportRadius = (0.5 * importRadius) radiusSide = (0.01 * importRadius) negativeLoops = getLoopsUnion(importRadius, loopLists[1:]) intercircle.directLoops(False, negativeLoops) positiveLoops = loopLists[0] intercirc...
null
null
null
What does this function do?
def ClientInit(): if (stats.STATS is None): stats.STATS = stats.StatsCollector() config_lib.SetPlatformArchContext() config_lib.ParseConfigCommandLine() log.LogInit() registry.Init()
null
null
null
Run all startup routines for the client.
pcsd
def Client Init if stats STATS is None stats STATS = stats Stats Collector config lib Set Platform Arch Context config lib Parse Config Command Line log Log Init registry Init
10184
def ClientInit(): if (stats.STATS is None): stats.STATS = stats.StatsCollector() config_lib.SetPlatformArchContext() config_lib.ParseConfigCommandLine() log.LogInit() registry.Init()
Run all startup routines for the client.
run all startup routines for the client .
Question: What does this function do? Code: def ClientInit(): if (stats.STATS is None): stats.STATS = stats.StatsCollector() config_lib.SetPlatformArchContext() config_lib.ParseConfigCommandLine() log.LogInit() registry.Init()
null
null
null
What does this function do?
@cache_permission def can_author_translation(user, project): return check_permission(user, project, 'trans.author_translation')
null
null
null
Checks whether user can author translation on given project.
pcsd
@cache permission def can author translation user project return check permission user project 'trans author translation'
10187
@cache_permission def can_author_translation(user, project): return check_permission(user, project, 'trans.author_translation')
Checks whether user can author translation on given project.
checks whether user can author translation on given project .
Question: What does this function do? Code: @cache_permission def can_author_translation(user, project): return check_permission(user, project, 'trans.author_translation')
null
null
null
What does this function do?
def application_to_app_label(application): if isinstance(application, string_types): app_label = application.split('.')[(-1)] else: app_label = application.__name__.split('.')[(-1)] return app_label
null
null
null
Works out the app label from either the app label, the app name, or the module
pcsd
def application to app label application if isinstance application string types app label = application split ' ' [ -1 ] else app label = application name split ' ' [ -1 ] return app label
10191
def application_to_app_label(application): if isinstance(application, string_types): app_label = application.split('.')[(-1)] else: app_label = application.__name__.split('.')[(-1)] return app_label
Works out the app label from either the app label, the app name, or the module
works out the app label from either the app label , the app name , or the module
Question: What does this function do? Code: def application_to_app_label(application): if isinstance(application, string_types): app_label = application.split('.')[(-1)] else: app_label = application.__name__.split('.')[(-1)] return app_label
null
null
null
What does this function do?
def compress_tokens(tokens): result = [tokens[0]] for tok in tokens[1:]: if ((not result[(-1)].post_tags) and (not tok.pre_tags) and (result[(-1)].annotation == tok.annotation)): compress_merge_back(result, tok) else: result.append(tok) return result
null
null
null
Combine adjacent tokens when there is no HTML between the tokens, and they share an annotation
pcsd
def compress tokens tokens result = [tokens[0]] for tok in tokens[1 ] if not result[ -1 ] post tags and not tok pre tags and result[ -1 ] annotation == tok annotation compress merge back result tok else result append tok return result
10210
def compress_tokens(tokens): result = [tokens[0]] for tok in tokens[1:]: if ((not result[(-1)].post_tags) and (not tok.pre_tags) and (result[(-1)].annotation == tok.annotation)): compress_merge_back(result, tok) else: result.append(tok) return result
Combine adjacent tokens when there is no HTML between the tokens, and they share an annotation
combine adjacent tokens when there is no html between the tokens , and they share an annotation
Question: What does this function do? Code: def compress_tokens(tokens): result = [tokens[0]] for tok in tokens[1:]: if ((not result[(-1)].post_tags) and (not tok.pre_tags) and (result[(-1)].annotation == tok.annotation)): compress_merge_back(result, tok) else: result.append(tok) return result
null
null
null
What does this function do?
def DA_DESeq2(input_path, out_path, mapping_fp, mapping_category, subcategory_1, subcategory_2, DESeq2_diagnostic_plots): tmp_bt = load_table(input_path) (tmp_pmf, _) = parse_mapping_file_to_dict(mapping_fp) check_mapping_file_category(tmp_bt, mapping_fp, mapping_category, subcategory_1, subcategory_2) tmp_bt.add_m...
null
null
null
perform DESeq2 negative binomial Wald differential abundance test on a raw abundance OTU matrix
pcsd
def DA DE Seq2 input path out path mapping fp mapping category subcategory 1 subcategory 2 DE Seq2 diagnostic plots tmp bt = load table input path tmp pmf = parse mapping file to dict mapping fp check mapping file category tmp bt mapping fp mapping category subcategory 1 subcategory 2 tmp bt add metadata tmp pmf 'sampl...
10214
def DA_DESeq2(input_path, out_path, mapping_fp, mapping_category, subcategory_1, subcategory_2, DESeq2_diagnostic_plots): tmp_bt = load_table(input_path) (tmp_pmf, _) = parse_mapping_file_to_dict(mapping_fp) check_mapping_file_category(tmp_bt, mapping_fp, mapping_category, subcategory_1, subcategory_2) tmp_bt.add_m...
perform DESeq2 negative binomial Wald differential abundance test on a raw abundance OTU matrix
perform deseq2 negative binomial wald differential abundance test on a raw abundance otu matrix
Question: What does this function do? Code: def DA_DESeq2(input_path, out_path, mapping_fp, mapping_category, subcategory_1, subcategory_2, DESeq2_diagnostic_plots): tmp_bt = load_table(input_path) (tmp_pmf, _) = parse_mapping_file_to_dict(mapping_fp) check_mapping_file_category(tmp_bt, mapping_fp, mapping_catego...
null
null
null
What does this function do?
def write_features_to_file(filename, locs, desc): savetxt(filename, hstack((locs, desc)))
null
null
null
Save feature location and descriptor to file.
pcsd
def write features to file filename locs desc savetxt filename hstack locs desc
10215
def write_features_to_file(filename, locs, desc): savetxt(filename, hstack((locs, desc)))
Save feature location and descriptor to file.
save feature location and descriptor to file .
Question: What does this function do? Code: def write_features_to_file(filename, locs, desc): savetxt(filename, hstack((locs, desc)))
null
null
null
What does this function do?
def alerting_authority(): return s3_rest_controller()
null
null
null
RESTful CRUD controller
pcsd
def alerting authority return s3 rest controller
10218
def alerting_authority(): return s3_rest_controller()
RESTful CRUD controller
restful crud controller
Question: What does this function do? Code: def alerting_authority(): return s3_rest_controller()
null
null
null
What does this function do?
def _apikey(): return __opts__.get('bamboohr', {}).get('apikey', None)
null
null
null
Get the API key
pcsd
def apikey return opts get 'bamboohr' {} get 'apikey' None
10223
def _apikey(): return __opts__.get('bamboohr', {}).get('apikey', None)
Get the API key
get the api key
Question: What does this function do? Code: def _apikey(): return __opts__.get('bamboohr', {}).get('apikey', None)
null
null
null
What does this function do?
def file_list_emptydirs(load): _init() return []
null
null
null
Return a list of all empty directories on the master
pcsd
def file list emptydirs load init return []
10225
def file_list_emptydirs(load): _init() return []
Return a list of all empty directories on the master
return a list of all empty directories on the master
Question: What does this function do? Code: def file_list_emptydirs(load): _init() return []
null
null
null
What does this function do?
def get_tab_by_locator(tab_list, usage_key_string): tab_location = UsageKey.from_string(usage_key_string) item = modulestore().get_item(tab_location) static_tab = StaticTab(name=item.display_name, url_slug=item.location.name) return CourseTabList.get_tab_by_id(tab_list, static_tab.tab_id)
null
null
null
Look for a tab with the specified locator. Returns the first matching tab.
pcsd
def get tab by locator tab list usage key string tab location = Usage Key from string usage key string item = modulestore get item tab location static tab = Static Tab name=item display name url slug=item location name return Course Tab List get tab by id tab list static tab tab id
10233
def get_tab_by_locator(tab_list, usage_key_string): tab_location = UsageKey.from_string(usage_key_string) item = modulestore().get_item(tab_location) static_tab = StaticTab(name=item.display_name, url_slug=item.location.name) return CourseTabList.get_tab_by_id(tab_list, static_tab.tab_id)
Look for a tab with the specified locator. Returns the first matching tab.
look for a tab with the specified locator .
Question: What does this function do? Code: def get_tab_by_locator(tab_list, usage_key_string): tab_location = UsageKey.from_string(usage_key_string) item = modulestore().get_item(tab_location) static_tab = StaticTab(name=item.display_name, url_slug=item.location.name) return CourseTabList.get_tab_by_id(tab_list...
null
null
null
What does this function do?
def access(authorization_code): return get_oauth_service().get_raw_access_token(data={'code': authorization_code, 'grant_type': 'authorization_code', 'redirect_uri': constants.CALLBACK}).json()['refresh_token']
null
null
null
obtain the refresh token
pcsd
def access authorization code return get oauth service get raw access token data={'code' authorization code 'grant type' 'authorization code' 'redirect uri' constants CALLBACK} json ['refresh token']
10241
def access(authorization_code): return get_oauth_service().get_raw_access_token(data={'code': authorization_code, 'grant_type': 'authorization_code', 'redirect_uri': constants.CALLBACK}).json()['refresh_token']
obtain the refresh token
obtain the refresh token
Question: What does this function do? Code: def access(authorization_code): return get_oauth_service().get_raw_access_token(data={'code': authorization_code, 'grant_type': 'authorization_code', 'redirect_uri': constants.CALLBACK}).json()['refresh_token']
null
null
null
What does this function do?
def p_statement_bad(p): print ('MALFORMED STATEMENT AT LINE %s' % p[1]) p[0] = None p.parser.error = 1
null
null
null
statement : INTEGER error NEWLINE
pcsd
def p statement bad p print 'MALFORMED STATEMENT AT LINE %s' % p[1] p[0] = None p parser error = 1
10243
def p_statement_bad(p): print ('MALFORMED STATEMENT AT LINE %s' % p[1]) p[0] = None p.parser.error = 1
statement : INTEGER error NEWLINE
statement : integer error newline
Question: What does this function do? Code: def p_statement_bad(p): print ('MALFORMED STATEMENT AT LINE %s' % p[1]) p[0] = None p.parser.error = 1
null
null
null
What does this function do?
def _get_config_file(user, config): uinfo = __salt__['user.info'](user) if (not uinfo): raise CommandExecutionError("User '{0}' does not exist".format(user)) home = uinfo['home'] config = _expand_authorized_keys_path(config, user, home) if (not os.path.isabs(config)): config = os.path.join(home, config) retur...
null
null
null
Get absolute path to a user\'s ssh_config.
pcsd
def get config file user config uinfo = salt ['user info'] user if not uinfo raise Command Execution Error "User '{0}' does not exist" format user home = uinfo['home'] config = expand authorized keys path config user home if not os path isabs config config = os path join home config return config
10249
def _get_config_file(user, config): uinfo = __salt__['user.info'](user) if (not uinfo): raise CommandExecutionError("User '{0}' does not exist".format(user)) home = uinfo['home'] config = _expand_authorized_keys_path(config, user, home) if (not os.path.isabs(config)): config = os.path.join(home, config) retur...
Get absolute path to a user\'s ssh_config.
get absolute path to a users ssh _ config .
Question: What does this function do? Code: def _get_config_file(user, config): uinfo = __salt__['user.info'](user) if (not uinfo): raise CommandExecutionError("User '{0}' does not exist".format(user)) home = uinfo['home'] config = _expand_authorized_keys_path(config, user, home) if (not os.path.isabs(config)...
null
null
null
What does this function do?
def _get_epochs_delayed_ssp(): raw = read_raw_fif(raw_fname) events = read_events(event_name) picks = _get_picks(raw) reject = dict(mag=4e-12) epochs_delayed_ssp = Epochs(raw, events[:10], event_id, tmin, tmax, picks=picks, proj='delayed', reject=reject) return epochs_delayed_ssp
null
null
null
Get epochs with delayed SSP.
pcsd
def get epochs delayed ssp raw = read raw fif raw fname events = read events event name picks = get picks raw reject = dict mag=4e-12 epochs delayed ssp = Epochs raw events[ 10] event id tmin tmax picks=picks proj='delayed' reject=reject return epochs delayed ssp
10252
def _get_epochs_delayed_ssp(): raw = read_raw_fif(raw_fname) events = read_events(event_name) picks = _get_picks(raw) reject = dict(mag=4e-12) epochs_delayed_ssp = Epochs(raw, events[:10], event_id, tmin, tmax, picks=picks, proj='delayed', reject=reject) return epochs_delayed_ssp
Get epochs with delayed SSP.
get epochs with delayed ssp .
Question: What does this function do? Code: def _get_epochs_delayed_ssp(): raw = read_raw_fif(raw_fname) events = read_events(event_name) picks = _get_picks(raw) reject = dict(mag=4e-12) epochs_delayed_ssp = Epochs(raw, events[:10], event_id, tmin, tmax, picks=picks, proj='delayed', reject=reject) return epoch...
null
null
null
What does this function do?
def _partial_fit_binary(estimator, X, y): estimator.partial_fit(X, y, np.array((0, 1))) return estimator
null
null
null
Partially fit a single binary estimator.
pcsd
def partial fit binary estimator X y estimator partial fit X y np array 0 1 return estimator
10255
def _partial_fit_binary(estimator, X, y): estimator.partial_fit(X, y, np.array((0, 1))) return estimator
Partially fit a single binary estimator.
partially fit a single binary estimator .
Question: What does this function do? Code: def _partial_fit_binary(estimator, X, y): estimator.partial_fit(X, y, np.array((0, 1))) return estimator
null
null
null
What does this function do?
@contextfunction def administration_group_list(context, groups, skip_group=False): request = context['request'] response_format = 'html' if ('response_format' in context): response_format = context['response_format'] return Markup(render_to_string('core/administration/tags/group_list', {'groups': groups, 'skip_gr...
null
null
null
Print a list of groups
pcsd
@contextfunction def administration group list context groups skip group=False request = context['request'] response format = 'html' if 'response format' in context response format = context['response format'] return Markup render to string 'core/administration/tags/group list' {'groups' groups 'skip group' skip group}...
10256
@contextfunction def administration_group_list(context, groups, skip_group=False): request = context['request'] response_format = 'html' if ('response_format' in context): response_format = context['response_format'] return Markup(render_to_string('core/administration/tags/group_list', {'groups': groups, 'skip_gr...
Print a list of groups
print a list of groups
Question: What does this function do? Code: @contextfunction def administration_group_list(context, groups, skip_group=False): request = context['request'] response_format = 'html' if ('response_format' in context): response_format = context['response_format'] return Markup(render_to_string('core/administratio...
null
null
null
What does this function do?
def is_form_submitted(): return (request and (request.method in ('PUT', 'POST')))
null
null
null
Check if current method is PUT or POST
pcsd
def is form submitted return request and request method in 'PUT' 'POST'
10260
def is_form_submitted(): return (request and (request.method in ('PUT', 'POST')))
Check if current method is PUT or POST
check if current method is put or post
Question: What does this function do? Code: def is_form_submitted(): return (request and (request.method in ('PUT', 'POST')))
null
null
null
What does this function do?
@pytest.fixture(scope='session') def hide(pootle_content_type): return _require_permission('hide', 'Cannot access a project', pootle_content_type)
null
null
null
Require the `hide` permission.
pcsd
@pytest fixture scope='session' def hide pootle content type return require permission 'hide' 'Cannot access a project' pootle content type
10278
@pytest.fixture(scope='session') def hide(pootle_content_type): return _require_permission('hide', 'Cannot access a project', pootle_content_type)
Require the `hide` permission.
require the hide permission .
Question: What does this function do? Code: @pytest.fixture(scope='session') def hide(pootle_content_type): return _require_permission('hide', 'Cannot access a project', pootle_content_type)
null
null
null
What does this function do?
def wait_for_http_server(host, port): for i in range(10): conn = httplib.HTTPConnection(host, port) conn.request('GET', '/') if (conn.getresponse().status == 200): break time.sleep(0.1) else: template = "Test HTTP server on host %s and port %s did not return '200 OK' after 10 tries" message = (template...
null
null
null
Wait for an HTTP server to boot up.
pcsd
def wait for http server host port for i in range 10 conn = httplib HTTP Connection host port conn request 'GET' '/' if conn getresponse status == 200 break time sleep 0 1 else template = "Test HTTP server on host %s and port %s did not return '200 OK' after 10 tries" message = template % host port raise Exception mess...
10288
def wait_for_http_server(host, port): for i in range(10): conn = httplib.HTTPConnection(host, port) conn.request('GET', '/') if (conn.getresponse().status == 200): break time.sleep(0.1) else: template = "Test HTTP server on host %s and port %s did not return '200 OK' after 10 tries" message = (template...
Wait for an HTTP server to boot up.
wait for an http server to boot up .
Question: What does this function do? Code: def wait_for_http_server(host, port): for i in range(10): conn = httplib.HTTPConnection(host, port) conn.request('GET', '/') if (conn.getresponse().status == 200): break time.sleep(0.1) else: template = "Test HTTP server on host %s and port %s did not return...
null
null
null
What does this function do?
def getPathsFromEndpoints(endpoints, fillInset, pixelDictionary, width): if (len(endpoints) < 2): return [[]] for beginningEndpoint in endpoints[::2]: beginningPoint = beginningEndpoint.point addSegmentToPixelTable(beginningPoint, beginningEndpoint.otherEndpoint.point, pixelDictionary, 0, 0, width) endpointFir...
null
null
null
Get paths from endpoints.
pcsd
def get Paths From Endpoints endpoints fill Inset pixel Dictionary width if len endpoints < 2 return [[]] for beginning Endpoint in endpoints[ 2] beginning Point = beginning Endpoint point add Segment To Pixel Table beginning Point beginning Endpoint other Endpoint point pixel Dictionary 0 0 width endpoint First = endp...
10299
def getPathsFromEndpoints(endpoints, fillInset, pixelDictionary, width): if (len(endpoints) < 2): return [[]] for beginningEndpoint in endpoints[::2]: beginningPoint = beginningEndpoint.point addSegmentToPixelTable(beginningPoint, beginningEndpoint.otherEndpoint.point, pixelDictionary, 0, 0, width) endpointFir...
Get paths from endpoints.
get paths from endpoints .
Question: What does this function do? Code: def getPathsFromEndpoints(endpoints, fillInset, pixelDictionary, width): if (len(endpoints) < 2): return [[]] for beginningEndpoint in endpoints[::2]: beginningPoint = beginningEndpoint.point addSegmentToPixelTable(beginningPoint, beginningEndpoint.otherEndpoint.po...
null
null
null
What does this function do?
@pytest.fixture def disable_bears(mocker): mocker.patch.object(coalib.collecting.Collectors, '_import_bears', autospec=True, return_value=[])
null
null
null
Disable all bears that would otherwise be found with `collect_bears(...)`.
pcsd
@pytest fixture def disable bears mocker mocker patch object coalib collecting Collectors ' import bears' autospec=True return value=[]
10305
@pytest.fixture def disable_bears(mocker): mocker.patch.object(coalib.collecting.Collectors, '_import_bears', autospec=True, return_value=[])
Disable all bears that would otherwise be found with `collect_bears(...)`.
disable all bears that would otherwise be found with collect _ bears .
Question: What does this function do? Code: @pytest.fixture def disable_bears(mocker): mocker.patch.object(coalib.collecting.Collectors, '_import_bears', autospec=True, return_value=[])
null
null
null
What does this function do?
def _SendRecv(): port = int(os.getenv(DEVSHELL_ENV, 0)) if (port == 0): raise NoDevshellServer() import socket sock = socket.socket() sock.connect(('localhost', port)) data = CREDENTIAL_INFO_REQUEST_JSON msg = ('%s\n%s' % (len(data), data)) sock.sendall(msg.encode()) header = sock.recv(6).decode() if ('\n' ...
null
null
null
Communicate with the Developer Shell server socket.
pcsd
def Send Recv port = int os getenv DEVSHELL ENV 0 if port == 0 raise No Devshell Server import socket sock = socket socket sock connect 'localhost' port data = CREDENTIAL INFO REQUEST JSON msg = '%s %s' % len data data sock sendall msg encode header = sock recv 6 decode if ' ' not in header raise Communication Error 's...
10309
def _SendRecv(): port = int(os.getenv(DEVSHELL_ENV, 0)) if (port == 0): raise NoDevshellServer() import socket sock = socket.socket() sock.connect(('localhost', port)) data = CREDENTIAL_INFO_REQUEST_JSON msg = ('%s\n%s' % (len(data), data)) sock.sendall(msg.encode()) header = sock.recv(6).decode() if ('\n' ...
Communicate with the Developer Shell server socket.
communicate with the developer shell server socket .
Question: What does this function do? Code: def _SendRecv(): port = int(os.getenv(DEVSHELL_ENV, 0)) if (port == 0): raise NoDevshellServer() import socket sock = socket.socket() sock.connect(('localhost', port)) data = CREDENTIAL_INFO_REQUEST_JSON msg = ('%s\n%s' % (len(data), data)) sock.sendall(msg.encod...
null
null
null
What does this function do?
def validate_textbooks_json(text): try: textbooks = json.loads(text) except ValueError: raise TextbookValidationError('invalid JSON') if (not isinstance(textbooks, (list, tuple))): raise TextbookValidationError('must be JSON list') for textbook in textbooks: validate_textbook_json(textbook) all_ids = [text...
null
null
null
Validate the given text as representing a single PDF textbook
pcsd
def validate textbooks json text try textbooks = json loads text except Value Error raise Textbook Validation Error 'invalid JSON' if not isinstance textbooks list tuple raise Textbook Validation Error 'must be JSON list' for textbook in textbooks validate textbook json textbook all ids = [textbook['id'] for textbook i...
10310
def validate_textbooks_json(text): try: textbooks = json.loads(text) except ValueError: raise TextbookValidationError('invalid JSON') if (not isinstance(textbooks, (list, tuple))): raise TextbookValidationError('must be JSON list') for textbook in textbooks: validate_textbook_json(textbook) all_ids = [text...
Validate the given text as representing a single PDF textbook
validate the given text as representing a single pdf textbook
Question: What does this function do? Code: def validate_textbooks_json(text): try: textbooks = json.loads(text) except ValueError: raise TextbookValidationError('invalid JSON') if (not isinstance(textbooks, (list, tuple))): raise TextbookValidationError('must be JSON list') for textbook in textbooks: va...
null
null
null
What does this function do?
def _list_files(folder, pattern): for (root, folders, files) in os.walk(folder): for filename in files: if fnmatch.fnmatch(filename, pattern): (yield os.path.join(root, filename))
null
null
null
Lists all files below the given folder that match the pattern.
pcsd
def list files folder pattern for root folders files in os walk folder for filename in files if fnmatch fnmatch filename pattern yield os path join root filename
10312
def _list_files(folder, pattern): for (root, folders, files) in os.walk(folder): for filename in files: if fnmatch.fnmatch(filename, pattern): (yield os.path.join(root, filename))
Lists all files below the given folder that match the pattern.
lists all files below the given folder that match the pattern .
Question: What does this function do? Code: def _list_files(folder, pattern): for (root, folders, files) in os.walk(folder): for filename in files: if fnmatch.fnmatch(filename, pattern): (yield os.path.join(root, filename))
null
null
null
What does this function do?
def get_socket_inherit(socket): try: if iswindows: import win32api, win32con flags = win32api.GetHandleInformation(socket.fileno()) return bool((flags & win32con.HANDLE_FLAG_INHERIT)) else: import fcntl flags = fcntl.fcntl(socket.fileno(), fcntl.F_GETFD) return (not bool((flags & fcntl.FD_CLOEXEC...
null
null
null
Returns True if the socket has been set to allow inheritance across forks and execs to child processes, otherwise False
pcsd
def get socket inherit socket try if iswindows import win32api win32con flags = win32api Get Handle Information socket fileno return bool flags & win32con HANDLE FLAG INHERIT else import fcntl flags = fcntl fcntl socket fileno fcntl F GETFD return not bool flags & fcntl FD CLOEXEC except import traceback traceback prin...
10313
def get_socket_inherit(socket): try: if iswindows: import win32api, win32con flags = win32api.GetHandleInformation(socket.fileno()) return bool((flags & win32con.HANDLE_FLAG_INHERIT)) else: import fcntl flags = fcntl.fcntl(socket.fileno(), fcntl.F_GETFD) return (not bool((flags & fcntl.FD_CLOEXEC...
Returns True if the socket has been set to allow inheritance across forks and execs to child processes, otherwise False
returns true if the socket has been set to allow inheritance across forks and execs to child processes , otherwise false
Question: What does this function do? Code: def get_socket_inherit(socket): try: if iswindows: import win32api, win32con flags = win32api.GetHandleInformation(socket.fileno()) return bool((flags & win32con.HANDLE_FLAG_INHERIT)) else: import fcntl flags = fcntl.fcntl(socket.fileno(), fcntl.F_GETFD...
null
null
null
What does this function do?
def _construct_signal_from_epochs(epochs, events, sfreq, tmin): (n_epochs, n_channels, n_times) = epochs.shape tmax = (tmin + (n_times / float(sfreq))) start = (np.min(events[:, 0]) + int((tmin * sfreq))) stop = ((np.max(events[:, 0]) + int((tmax * sfreq))) + 1) n_samples = (stop - start) (n_epochs, n_channels, n...
null
null
null
Reconstruct pseudo continuous signal from epochs.
pcsd
def construct signal from epochs epochs events sfreq tmin n epochs n channels n times = epochs shape tmax = tmin + n times / float sfreq start = np min events[ 0] + int tmin * sfreq stop = np max events[ 0] + int tmax * sfreq + 1 n samples = stop - start n epochs n channels n times = epochs shape events pos = events[ 0...
10324
def _construct_signal_from_epochs(epochs, events, sfreq, tmin): (n_epochs, n_channels, n_times) = epochs.shape tmax = (tmin + (n_times / float(sfreq))) start = (np.min(events[:, 0]) + int((tmin * sfreq))) stop = ((np.max(events[:, 0]) + int((tmax * sfreq))) + 1) n_samples = (stop - start) (n_epochs, n_channels, n...
Reconstruct pseudo continuous signal from epochs.
reconstruct pseudo continuous signal from epochs .
Question: What does this function do? Code: def _construct_signal_from_epochs(epochs, events, sfreq, tmin): (n_epochs, n_channels, n_times) = epochs.shape tmax = (tmin + (n_times / float(sfreq))) start = (np.min(events[:, 0]) + int((tmin * sfreq))) stop = ((np.max(events[:, 0]) + int((tmax * sfreq))) + 1) n_sam...
null
null
null
What does this function do?
def tracks_for_id(track_id): candidates = [track_for_mbid(track_id)] candidates.extend(plugins.track_for_id(track_id)) return filter(None, candidates)
null
null
null
Get a list of tracks for an ID.
pcsd
def tracks for id track id candidates = [track for mbid track id ] candidates extend plugins track for id track id return filter None candidates
10328
def tracks_for_id(track_id): candidates = [track_for_mbid(track_id)] candidates.extend(plugins.track_for_id(track_id)) return filter(None, candidates)
Get a list of tracks for an ID.
get a list of tracks for an id .
Question: What does this function do? Code: def tracks_for_id(track_id): candidates = [track_for_mbid(track_id)] candidates.extend(plugins.track_for_id(track_id)) return filter(None, candidates)
null
null
null
What does this function do?
def EnablePrivilege(privilegeStr, hToken=None): if (hToken == None): TOKEN_ADJUST_PRIVILEGES = 32 TOKEN_QUERY = 8 hToken = HANDLE(INVALID_HANDLE_VALUE) hProcess = windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION, False, windll.kernel32.GetCurrentProcessId()) windll.advapi32.OpenProcessToken(hProcess, (T...
null
null
null
Enable Privilege on token, if no token is given the function gets the token of the current process.
pcsd
def Enable Privilege privilege Str h Token=None if h Token == None TOKEN ADJUST PRIVILEGES = 32 TOKEN QUERY = 8 h Token = HANDLE INVALID HANDLE VALUE h Process = windll kernel32 Open Process PROCESS QUERY INFORMATION False windll kernel32 Get Current Process Id windll advapi32 Open Process Token h Process TOKEN ADJUST ...
10336
def EnablePrivilege(privilegeStr, hToken=None): if (hToken == None): TOKEN_ADJUST_PRIVILEGES = 32 TOKEN_QUERY = 8 hToken = HANDLE(INVALID_HANDLE_VALUE) hProcess = windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION, False, windll.kernel32.GetCurrentProcessId()) windll.advapi32.OpenProcessToken(hProcess, (T...
Enable Privilege on token, if no token is given the function gets the token of the current process.
enable privilege on token , if no token is given the function gets the token of the current process .
Question: What does this function do? Code: def EnablePrivilege(privilegeStr, hToken=None): if (hToken == None): TOKEN_ADJUST_PRIVILEGES = 32 TOKEN_QUERY = 8 hToken = HANDLE(INVALID_HANDLE_VALUE) hProcess = windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION, False, windll.kernel32.GetCurrentProcessId()) ...
null
null
null
What does this function do?
def unset(bot, update, chat_data): if ('job' not in chat_data): update.message.reply_text('You have no active timer') return job = chat_data['job'] job.schedule_removal() del chat_data['job'] update.message.reply_text('Timer successfully unset!')
null
null
null
Removes the job if the user changed their mind
pcsd
def unset bot update chat data if 'job' not in chat data update message reply text 'You have no active timer' return job = chat data['job'] job schedule removal del chat data['job'] update message reply text 'Timer successfully unset!'
10343
def unset(bot, update, chat_data): if ('job' not in chat_data): update.message.reply_text('You have no active timer') return job = chat_data['job'] job.schedule_removal() del chat_data['job'] update.message.reply_text('Timer successfully unset!')
Removes the job if the user changed their mind
removes the job if the user changed their mind
Question: What does this function do? Code: def unset(bot, update, chat_data): if ('job' not in chat_data): update.message.reply_text('You have no active timer') return job = chat_data['job'] job.schedule_removal() del chat_data['job'] update.message.reply_text('Timer successfully unset!')
null
null
null
What does this function do?
def _get_user_usage_data(users, groups=None, period_start=None, period_end=None, group_id=None): groups = (groups or set([user.group for user in users])) user_data = OrderedDict() group_data = OrderedDict() exercise_logs = ExerciseLog.objects.filter(user__in=users) video_logs = VideoLog.objects.filter(user__in=use...
null
null
null
Returns facility user data, within the given date range.
pcsd
def get user usage data users groups=None period start=None period end=None group id=None groups = groups or set [user group for user in users] user data = Ordered Dict group data = Ordered Dict exercise logs = Exercise Log objects filter user in=users video logs = Video Log objects filter user in=users total seconds w...
10347
def _get_user_usage_data(users, groups=None, period_start=None, period_end=None, group_id=None): groups = (groups or set([user.group for user in users])) user_data = OrderedDict() group_data = OrderedDict() exercise_logs = ExerciseLog.objects.filter(user__in=users) video_logs = VideoLog.objects.filter(user__in=use...
Returns facility user data, within the given date range.
returns facility user data , within the given date range .
Question: What does this function do? Code: def _get_user_usage_data(users, groups=None, period_start=None, period_end=None, group_id=None): groups = (groups or set([user.group for user in users])) user_data = OrderedDict() group_data = OrderedDict() exercise_logs = ExerciseLog.objects.filter(user__in=users) vi...
null
null
null
What does this function do?
def instance_type_extra_specs_get(context, flavor_id): return IMPL.instance_type_extra_specs_get(context, flavor_id)
null
null
null
Get all extra specs for an instance type.
pcsd
def instance type extra specs get context flavor id return IMPL instance type extra specs get context flavor id
10350
def instance_type_extra_specs_get(context, flavor_id): return IMPL.instance_type_extra_specs_get(context, flavor_id)
Get all extra specs for an instance type.
get all extra specs for an instance type .
Question: What does this function do? Code: def instance_type_extra_specs_get(context, flavor_id): return IMPL.instance_type_extra_specs_get(context, flavor_id)
null
null
null
What does this function do?
@flaskbb.command('download-emojis') @with_appcontext def download_emoji(): click.secho('[+] Downloading emojis...', fg='cyan') HOSTNAME = 'https://api.github.com' REPO = '/repos/arvida/emoji-cheat-sheet.com/contents/public/graphics/emojis' FULL_URL = '{}{}'.format(HOSTNAME, REPO) DOWNLOAD_PATH = os.path.join(curre...
null
null
null
Downloads emojis from emoji-cheat-sheet.com. This command is probably going to be removed in future version.
pcsd
@flaskbb command 'download-emojis' @with appcontext def download emoji click secho '[+] Downloading emojis ' fg='cyan' HOSTNAME = 'https //api github com' REPO = '/repos/arvida/emoji-cheat-sheet com/contents/public/graphics/emojis' FULL URL = '{}{}' format HOSTNAME REPO DOWNLOAD PATH = os path join current app static f...
10354
@flaskbb.command('download-emojis') @with_appcontext def download_emoji(): click.secho('[+] Downloading emojis...', fg='cyan') HOSTNAME = 'https://api.github.com' REPO = '/repos/arvida/emoji-cheat-sheet.com/contents/public/graphics/emojis' FULL_URL = '{}{}'.format(HOSTNAME, REPO) DOWNLOAD_PATH = os.path.join(curre...
Downloads emojis from emoji-cheat-sheet.com. This command is probably going to be removed in future version.
downloads emojis from emoji - cheat - sheet . com .
Question: What does this function do? Code: @flaskbb.command('download-emojis') @with_appcontext def download_emoji(): click.secho('[+] Downloading emojis...', fg='cyan') HOSTNAME = 'https://api.github.com' REPO = '/repos/arvida/emoji-cheat-sheet.com/contents/public/graphics/emojis' FULL_URL = '{}{}'.format(HOST...
null
null
null
What does this function do?
def get_edit_filters(): edit_filetypes = get_edit_filetypes() return _get_filters(edit_filetypes)
null
null
null
Return filters associated with the file types supported by the Editor
pcsd
def get edit filters edit filetypes = get edit filetypes return get filters edit filetypes
10360
def get_edit_filters(): edit_filetypes = get_edit_filetypes() return _get_filters(edit_filetypes)
Return filters associated with the file types supported by the Editor
return filters associated with the file types supported by the editor
Question: What does this function do? Code: def get_edit_filters(): edit_filetypes = get_edit_filetypes() return _get_filters(edit_filetypes)
null
null
null
What does this function do?
def _if_modified_since_passes(last_modified, if_modified_since): return ((not last_modified) or (last_modified > if_modified_since))
null
null
null
Test the If-Modified-Since comparison as defined in section 3.3 of RFC 7232.
pcsd
def if modified since passes last modified if modified since return not last modified or last modified > if modified since
10364
def _if_modified_since_passes(last_modified, if_modified_since): return ((not last_modified) or (last_modified > if_modified_since))
Test the If-Modified-Since comparison as defined in section 3.3 of RFC 7232.
test the if - modified - since comparison as defined in section 3 . 3 of rfc 7232 .
Question: What does this function do? Code: def _if_modified_since_passes(last_modified, if_modified_since): return ((not last_modified) or (last_modified > if_modified_since))