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 _re_compile(regex): return re.compile(regex, (re.I | re.UNICODE))
null
null
null
Compile a string to regex, I and UNICODE.
pcsd
def re compile regex return re compile regex re I | re UNICODE
15899
def _re_compile(regex): return re.compile(regex, (re.I | re.UNICODE))
Compile a string to regex, I and UNICODE.
compile a string to regex , i and unicode .
Question: What does this function do? Code: def _re_compile(regex): return re.compile(regex, (re.I | re.UNICODE))
null
null
null
What does this function do?
def _range_string_to_set(range_str): if ('..' in range_str): (range_start, range_end) = range_str.split('..') range_start = int(range_start, 16) range_end = int(range_end, 16) return set(range(range_start, (range_end + 1))) else: return {int(range_str, 16)}
null
null
null
Convert a range encoding in a string to a set.
pcsd
def range string to set range str if ' ' in range str range start range end = range str split ' ' range start = int range start 16 range end = int range end 16 return set range range start range end + 1 else return {int range str 16 }
15902
def _range_string_to_set(range_str): if ('..' in range_str): (range_start, range_end) = range_str.split('..') range_start = int(range_start, 16) range_end = int(range_end, 16) return set(range(range_start, (range_end + 1))) else: return {int(range_str, 16)}
Convert a range encoding in a string to a set.
convert a range encoding in a string to a set .
Question: What does this function do? Code: def _range_string_to_set(range_str): if ('..' in range_str): (range_start, range_end) = range_str.split('..') range_start = int(range_start, 16) range_end = int(range_end, 16) return set(range(range_start, (range_end + 1))) else: return {int(range_str, 16)}
null
null
null
What does this function do?
def s3_is_mobile_client(request): env = request.env if (env.http_x_wap_profile or env.http_profile): return True if (env.http_accept and (env.http_accept.find('text/vnd.wap.wml') > 0)): return True keys = ['iphone', 'ipod', 'android', 'opera mini', 'blackberry', 'palm', 'windows ce', 'iemobile', 'smartphone', '...
null
null
null
Simple UA Test whether client is a mobile device
pcsd
def s3 is mobile client request env = request env if env http x wap profile or env http profile return True if env http accept and env http accept find 'text/vnd wap wml' > 0 return True keys = ['iphone' 'ipod' 'android' 'opera mini' 'blackberry' 'palm' 'windows ce' 'iemobile' 'smartphone' 'medi' 'sk-0' 'vk-v' 'aptu' '...
15903
def s3_is_mobile_client(request): env = request.env if (env.http_x_wap_profile or env.http_profile): return True if (env.http_accept and (env.http_accept.find('text/vnd.wap.wml') > 0)): return True keys = ['iphone', 'ipod', 'android', 'opera mini', 'blackberry', 'palm', 'windows ce', 'iemobile', 'smartphone', '...
Simple UA Test whether client is a mobile device
simple ua test whether client is a mobile device
Question: What does this function do? Code: def s3_is_mobile_client(request): env = request.env if (env.http_x_wap_profile or env.http_profile): return True if (env.http_accept and (env.http_accept.find('text/vnd.wap.wml') > 0)): return True keys = ['iphone', 'ipod', 'android', 'opera mini', 'blackberry', 'p...
null
null
null
What does this function do?
def req_item_onaccept(form): form_vars = form.vars req_id = form_vars.get('req_id', None) if (not req_id): req_id = s3_get_last_record_id('req_req') if (not req_id): raise HTTP(500, 'Cannot get req_id') req_update_status(req_id) item_id = form_vars.get('item_id', None) db = current.db citable = db.supply_ca...
null
null
null
Update Request Status Update req_item_category link table
pcsd
def req item onaccept form form vars = form vars req id = form vars get 'req id' None if not req id req id = s3 get last record id 'req req' if not req id raise HTTP 500 'Cannot get req id' req update status req id item id = form vars get 'item id' None db = current db citable = db supply catalog item cats = db citable...
15905
def req_item_onaccept(form): form_vars = form.vars req_id = form_vars.get('req_id', None) if (not req_id): req_id = s3_get_last_record_id('req_req') if (not req_id): raise HTTP(500, 'Cannot get req_id') req_update_status(req_id) item_id = form_vars.get('item_id', None) db = current.db citable = db.supply_ca...
Update Request Status Update req_item_category link table
update request status
Question: What does this function do? Code: def req_item_onaccept(form): form_vars = form.vars req_id = form_vars.get('req_id', None) if (not req_id): req_id = s3_get_last_record_id('req_req') if (not req_id): raise HTTP(500, 'Cannot get req_id') req_update_status(req_id) item_id = form_vars.get('item_id',...
null
null
null
What does this function do?
def setup_package(): util.positional_parameters_enforcement = 'EXCEPTION'
null
null
null
Run on testing package.
pcsd
def setup package util positional parameters enforcement = 'EXCEPTION'
15910
def setup_package(): util.positional_parameters_enforcement = 'EXCEPTION'
Run on testing package.
run on testing package .
Question: What does this function do? Code: def setup_package(): util.positional_parameters_enforcement = 'EXCEPTION'
null
null
null
What does this function do?
def ClosureTable(model_class, foreign_key=None): if (foreign_key is None): for field_obj in model_class._meta.rel.values(): if (field_obj.rel_model is model_class): foreign_key = field_obj break else: raise ValueError('Unable to find self-referential foreign key.') primary_key = model_class._meta.pr...
null
null
null
Model factory for the transitive closure extension.
pcsd
def Closure Table model class foreign key=None if foreign key is None for field obj in model class meta rel values if field obj rel model is model class foreign key = field obj break else raise Value Error 'Unable to find self-referential foreign key ' primary key = model class meta primary key class Base Closure Table...
15911
def ClosureTable(model_class, foreign_key=None): if (foreign_key is None): for field_obj in model_class._meta.rel.values(): if (field_obj.rel_model is model_class): foreign_key = field_obj break else: raise ValueError('Unable to find self-referential foreign key.') primary_key = model_class._meta.pr...
Model factory for the transitive closure extension.
model factory for the transitive closure extension .
Question: What does this function do? Code: def ClosureTable(model_class, foreign_key=None): if (foreign_key is None): for field_obj in model_class._meta.rel.values(): if (field_obj.rel_model is model_class): foreign_key = field_obj break else: raise ValueError('Unable to find self-referential for...
null
null
null
What does this function do?
def pass_context(f): def new_func(*args, **kwargs): return f(get_current_context(), *args, **kwargs) return update_wrapper(new_func, f)
null
null
null
Marks a callback as wanting to receive the current context object as first argument.
pcsd
def pass context f def new func *args **kwargs return f get current context *args **kwargs return update wrapper new func f
15916
def pass_context(f): def new_func(*args, **kwargs): return f(get_current_context(), *args, **kwargs) return update_wrapper(new_func, f)
Marks a callback as wanting to receive the current context object as first argument.
marks a callback as wanting to receive the current context object as first argument .
Question: What does this function do? Code: def pass_context(f): def new_func(*args, **kwargs): return f(get_current_context(), *args, **kwargs) return update_wrapper(new_func, f)
null
null
null
What does this function do?
def ntop(address): af = (((len(address) == 4) and socket.AF_INET) or socket.AF_INET6) return socket.inet_ntop(af, address)
null
null
null
Convert address to its string representation
pcsd
def ntop address af = len address == 4 and socket AF INET or socket AF INET6 return socket inet ntop af address
15918
def ntop(address): af = (((len(address) == 4) and socket.AF_INET) or socket.AF_INET6) return socket.inet_ntop(af, address)
Convert address to its string representation
convert address to its string representation
Question: What does this function do? Code: def ntop(address): af = (((len(address) == 4) and socket.AF_INET) or socket.AF_INET6) return socket.inet_ntop(af, address)
null
null
null
What does this function do?
def _convert_paths(paths): new_paths = [] for path in paths: new_path = _convert_2to3(path) new_paths.append(new_path) return new_paths
null
null
null
Convert the given files, and return the paths to the converted files.
pcsd
def convert paths paths new paths = [] for path in paths new path = convert 2to3 path new paths append new path return new paths
15919
def _convert_paths(paths): new_paths = [] for path in paths: new_path = _convert_2to3(path) new_paths.append(new_path) return new_paths
Convert the given files, and return the paths to the converted files.
convert the given files , and return the paths to the converted files .
Question: What does this function do? Code: def _convert_paths(paths): new_paths = [] for path in paths: new_path = _convert_2to3(path) new_paths.append(new_path) return new_paths
null
null
null
What does this function do?
def get_venv_packages(venv_path): with open(get_index_filename(venv_path)) as reader: return set((p.strip() for p in reader.read().split('\n') if p.strip()))
null
null
null
Returns the packages installed in the virtual environment using the package index file.
pcsd
def get venv packages venv path with open get index filename venv path as reader return set p strip for p in reader read split ' ' if p strip
15922
def get_venv_packages(venv_path): with open(get_index_filename(venv_path)) as reader: return set((p.strip() for p in reader.read().split('\n') if p.strip()))
Returns the packages installed in the virtual environment using the package index file.
returns the packages installed in the virtual environment using the package index file .
Question: What does this function do? Code: def get_venv_packages(venv_path): with open(get_index_filename(venv_path)) as reader: return set((p.strip() for p in reader.read().split('\n') if p.strip()))
null
null
null
What does this function do?
@require_POST @csrf_protect def snippet_save(request): if (not test_user_authenticated(request)): return login(request, next='/cobbler_web/snippet/list', expired=True) editmode = request.POST.get('editmode', 'edit') snippet_name = request.POST.get('snippet_name', None) snippetdata = request.POST.get('snippetdata'...
null
null
null
This snippet saves a snippet once edited.
pcsd
@require POST @csrf protect def snippet save request if not test user authenticated request return login request next='/cobbler web/snippet/list' expired=True editmode = request POST get 'editmode' 'edit' snippet name = request POST get 'snippet name' None snippetdata = request POST get 'snippetdata' '' replace '\r ' '...
15924
@require_POST @csrf_protect def snippet_save(request): if (not test_user_authenticated(request)): return login(request, next='/cobbler_web/snippet/list', expired=True) editmode = request.POST.get('editmode', 'edit') snippet_name = request.POST.get('snippet_name', None) snippetdata = request.POST.get('snippetdata'...
This snippet saves a snippet once edited.
this snippet saves a snippet once edited .
Question: What does this function do? Code: @require_POST @csrf_protect def snippet_save(request): if (not test_user_authenticated(request)): return login(request, next='/cobbler_web/snippet/list', expired=True) editmode = request.POST.get('editmode', 'edit') snippet_name = request.POST.get('snippet_name', None...
null
null
null
What does this function do?
@pytest.mark.django_db def test_hash(store0): unit = store0.units[0] suggestions = review.get(Suggestion)() (suggestion, created_) = suggestions.add(unit, 'gras') first_hash = suggestion.target_hash suggestion.translator_comment = 'my nice comment' second_hash = suggestion.target_hash assert (first_hash != secon...
null
null
null
Tests that target hash changes when suggestion is modified
pcsd
@pytest mark django db def test hash store0 unit = store0 units[0] suggestions = review get Suggestion suggestion created = suggestions add unit 'gras' first hash = suggestion target hash suggestion translator comment = 'my nice comment' second hash = suggestion target hash assert first hash != second hash suggestion t...
15926
@pytest.mark.django_db def test_hash(store0): unit = store0.units[0] suggestions = review.get(Suggestion)() (suggestion, created_) = suggestions.add(unit, 'gras') first_hash = suggestion.target_hash suggestion.translator_comment = 'my nice comment' second_hash = suggestion.target_hash assert (first_hash != secon...
Tests that target hash changes when suggestion is modified
tests that target hash changes when suggestion is modified
Question: What does this function do? Code: @pytest.mark.django_db def test_hash(store0): unit = store0.units[0] suggestions = review.get(Suggestion)() (suggestion, created_) = suggestions.add(unit, 'gras') first_hash = suggestion.target_hash suggestion.translator_comment = 'my nice comment' second_hash = sugg...
null
null
null
What does this function do?
def _find_milestone_revisions(config, milestone, branch=None): script = alembic_script.ScriptDirectory.from_config(config) return [(m.revision, label) for m in _get_revisions(script) for label in (m.branch_labels or [None]) if ((milestone in getattr(m.module, 'neutron_milestone', [])) and ((branch is None) or (branch...
null
null
null
Return the revision(s) for a given milestone.
pcsd
def find milestone revisions config milestone branch=None script = alembic script Script Directory from config config return [ m revision label for m in get revisions script for label in m branch labels or [None] if milestone in getattr m module 'neutron milestone' [] and branch is None or branch in m branch labels ]
15933
def _find_milestone_revisions(config, milestone, branch=None): script = alembic_script.ScriptDirectory.from_config(config) return [(m.revision, label) for m in _get_revisions(script) for label in (m.branch_labels or [None]) if ((milestone in getattr(m.module, 'neutron_milestone', [])) and ((branch is None) or (branch...
Return the revision(s) for a given milestone.
return the revision ( s ) for a given milestone .
Question: What does this function do? Code: def _find_milestone_revisions(config, milestone, branch=None): script = alembic_script.ScriptDirectory.from_config(config) return [(m.revision, label) for m in _get_revisions(script) for label in (m.branch_labels or [None]) if ((milestone in getattr(m.module, 'neutron_mi...
null
null
null
What does this function do?
def read(*paths): with open(os.path.join(*paths), 'r') as f: return f.read()
null
null
null
Build a file path from paths and return the contents.
pcsd
def read *paths with open os path join *paths 'r' as f return f read
15935
def read(*paths): with open(os.path.join(*paths), 'r') as f: return f.read()
Build a file path from paths and return the contents.
build a file path from paths and return the contents .
Question: What does this function do? Code: def read(*paths): with open(os.path.join(*paths), 'r') as f: return f.read()
null
null
null
What does this function do?
def DeleteResourceSample(): client = CreateClient() doc = gdata.docs.data.Resource(type='document', title='My Sample Doc') doc = client.CreateResource(doc) client.DeleteResource(doc)
null
null
null
Delete a resource (after creating it).
pcsd
def Delete Resource Sample client = Create Client doc = gdata docs data Resource type='document' title='My Sample Doc' doc = client Create Resource doc client Delete Resource doc
15936
def DeleteResourceSample(): client = CreateClient() doc = gdata.docs.data.Resource(type='document', title='My Sample Doc') doc = client.CreateResource(doc) client.DeleteResource(doc)
Delete a resource (after creating it).
delete a resource .
Question: What does this function do? Code: def DeleteResourceSample(): client = CreateClient() doc = gdata.docs.data.Resource(type='document', title='My Sample Doc') doc = client.CreateResource(doc) client.DeleteResource(doc)
null
null
null
What does this function do?
def doc_parse_markup(content, markup): (_, _, p) = doc_rev_parser(content, (TEMPLATE_TITLE_PREFIX + 'test'), category=TEMPLATES_CATEGORY) doc = pq(p.parse(markup)) return (doc, p)
null
null
null
Create a doc with given content and parse given markup.
pcsd
def doc parse markup content markup p = doc rev parser content TEMPLATE TITLE PREFIX + 'test' category=TEMPLATES CATEGORY doc = pq p parse markup return doc p
15937
def doc_parse_markup(content, markup): (_, _, p) = doc_rev_parser(content, (TEMPLATE_TITLE_PREFIX + 'test'), category=TEMPLATES_CATEGORY) doc = pq(p.parse(markup)) return (doc, p)
Create a doc with given content and parse given markup.
create a doc with given content and parse given markup .
Question: What does this function do? Code: def doc_parse_markup(content, markup): (_, _, p) = doc_rev_parser(content, (TEMPLATE_TITLE_PREFIX + 'test'), category=TEMPLATES_CATEGORY) doc = pq(p.parse(markup)) return (doc, p)
null
null
null
What does this function do?
def recursive_glob(path, pattern): for (root, dirnames, filenames) in os.walk(path, followlinks=True): for filename in fnmatch.filter(filenames, pattern): (yield os.path.join(root, filename))
null
null
null
recursively walk path directories and return files matching the pattern
pcsd
def recursive glob path pattern for root dirnames filenames in os walk path followlinks=True for filename in fnmatch filter filenames pattern yield os path join root filename
15941
def recursive_glob(path, pattern): for (root, dirnames, filenames) in os.walk(path, followlinks=True): for filename in fnmatch.filter(filenames, pattern): (yield os.path.join(root, filename))
recursively walk path directories and return files matching the pattern
recursively walk path directories and return files matching the pattern
Question: What does this function do? Code: def recursive_glob(path, pattern): for (root, dirnames, filenames) in os.walk(path, followlinks=True): for filename in fnmatch.filter(filenames, pattern): (yield os.path.join(root, filename))
null
null
null
What does this function do?
def fmt_search(value, search_match): if search_match: caseless = re.compile(re.escape(search_match), re.IGNORECASE) for variation in re.findall(caseless, value): value = re.sub(caseless, u'<span class="hlmatch">{0}</span>'.format(variation), value) return value
null
null
null
Formats search match
pcsd
def fmt search value search match if search match caseless = re compile re escape search match re IGNORECASE for variation in re findall caseless value value = re sub caseless u'<span class="hlmatch">{0}</span>' format variation value return value
15943
def fmt_search(value, search_match): if search_match: caseless = re.compile(re.escape(search_match), re.IGNORECASE) for variation in re.findall(caseless, value): value = re.sub(caseless, u'<span class="hlmatch">{0}</span>'.format(variation), value) return value
Formats search match
formats search match
Question: What does this function do? Code: def fmt_search(value, search_match): if search_match: caseless = re.compile(re.escape(search_match), re.IGNORECASE) for variation in re.findall(caseless, value): value = re.sub(caseless, u'<span class="hlmatch">{0}</span>'.format(variation), value) return value
null
null
null
What does this function do?
def __virtual__(): if ('locale.get_locale' in __salt__): return True else: return (False, __salt__.missing_fun_string('locale.get_locale'))
null
null
null
Only load if the locale module is available in __salt__
pcsd
def virtual if 'locale get locale' in salt return True else return False salt missing fun string 'locale get locale'
15954
def __virtual__(): if ('locale.get_locale' in __salt__): return True else: return (False, __salt__.missing_fun_string('locale.get_locale'))
Only load if the locale module is available in __salt__
only load if the locale module is available in _ _ salt _ _
Question: What does this function do? Code: def __virtual__(): if ('locale.get_locale' in __salt__): return True else: return (False, __salt__.missing_fun_string('locale.get_locale'))
null
null
null
What does this function do?
def EvaluatePrefix(prefix, path_regex): if path_regex.match(prefix): return 'MATCH' path_regex_string = path_regex.pattern if (not path_regex_string.startswith(KNOWN_PATH_REGEX_PREFIX)): logging.warning('Unrecognized regex format, being pessimistic: %s', path_regex_string) return 'POSSIBLE' literal_prefix = _...
null
null
null
Estimate if subjects beginning with prefix might match path_regex.
pcsd
def Evaluate Prefix prefix path regex if path regex match prefix return 'MATCH' path regex string = path regex pattern if not path regex string startswith KNOWN PATH REGEX PREFIX logging warning 'Unrecognized regex format being pessimistic %s' path regex string return 'POSSIBLE' literal prefix = Literal Prefix path reg...
15958
def EvaluatePrefix(prefix, path_regex): if path_regex.match(prefix): return 'MATCH' path_regex_string = path_regex.pattern if (not path_regex_string.startswith(KNOWN_PATH_REGEX_PREFIX)): logging.warning('Unrecognized regex format, being pessimistic: %s', path_regex_string) return 'POSSIBLE' literal_prefix = _...
Estimate if subjects beginning with prefix might match path_regex.
estimate if subjects beginning with prefix might match path _ regex .
Question: What does this function do? Code: def EvaluatePrefix(prefix, path_regex): if path_regex.match(prefix): return 'MATCH' path_regex_string = path_regex.pattern if (not path_regex_string.startswith(KNOWN_PATH_REGEX_PREFIX)): logging.warning('Unrecognized regex format, being pessimistic: %s', path_regex_...
null
null
null
What does this function do?
def quota_create(context, project_id, resource, limit, allocated=0): return IMPL.quota_create(context, project_id, resource, limit, allocated=allocated)
null
null
null
Create a quota for the given project and resource.
pcsd
def quota create context project id resource limit allocated=0 return IMPL quota create context project id resource limit allocated=allocated
15960
def quota_create(context, project_id, resource, limit, allocated=0): return IMPL.quota_create(context, project_id, resource, limit, allocated=allocated)
Create a quota for the given project and resource.
create a quota for the given project and resource .
Question: What does this function do? Code: def quota_create(context, project_id, resource, limit, allocated=0): return IMPL.quota_create(context, project_id, resource, limit, allocated=allocated)
null
null
null
What does this function do?
def cpu_stats(): return _psplatform.cpu_stats()
null
null
null
Return CPU statistics.
pcsd
def cpu stats return psplatform cpu stats
15962
def cpu_stats(): return _psplatform.cpu_stats()
Return CPU statistics.
return cpu statistics .
Question: What does this function do? Code: def cpu_stats(): return _psplatform.cpu_stats()
null
null
null
What does this function do?
def upgrade(migrate_engine): meta = MetaData(bind=migrate_engine) bdm = Table('block_device_mapping', meta, autoload=True) for index in bdm.indexes: if (index.name == INDEX_NAME): index.drop()
null
null
null
Remove duplicate index from block_device_mapping table.
pcsd
def upgrade migrate engine meta = Meta Data bind=migrate engine bdm = Table 'block device mapping' meta autoload=True for index in bdm indexes if index name == INDEX NAME index drop
15963
def upgrade(migrate_engine): meta = MetaData(bind=migrate_engine) bdm = Table('block_device_mapping', meta, autoload=True) for index in bdm.indexes: if (index.name == INDEX_NAME): index.drop()
Remove duplicate index from block_device_mapping table.
remove duplicate index from block _ device _ mapping table .
Question: What does this function do? Code: def upgrade(migrate_engine): meta = MetaData(bind=migrate_engine) bdm = Table('block_device_mapping', meta, autoload=True) for index in bdm.indexes: if (index.name == INDEX_NAME): index.drop()
null
null
null
What does this function do?
@gen.coroutine def AddFollowers(client, obj_store, user_id, device_id, request): request['user_id'] = user_id (yield Activity.VerifyActivityId(client, user_id, device_id, request['activity']['activity_id'])) _ValidateContacts(request['contacts']) (yield gen.Task(Operation.CreateAndExecute, client, user_id, device_i...
null
null
null
Add resolved contacts as followers of an existing viewpoint.
pcsd
@gen coroutine def Add Followers client obj store user id device id request request['user id'] = user id yield Activity Verify Activity Id client user id device id request['activity']['activity id'] Validate Contacts request['contacts'] yield gen Task Operation Create And Execute client user id device id 'Add Followers...
15976
@gen.coroutine def AddFollowers(client, obj_store, user_id, device_id, request): request['user_id'] = user_id (yield Activity.VerifyActivityId(client, user_id, device_id, request['activity']['activity_id'])) _ValidateContacts(request['contacts']) (yield gen.Task(Operation.CreateAndExecute, client, user_id, device_i...
Add resolved contacts as followers of an existing viewpoint.
add resolved contacts as followers of an existing viewpoint .
Question: What does this function do? Code: @gen.coroutine def AddFollowers(client, obj_store, user_id, device_id, request): request['user_id'] = user_id (yield Activity.VerifyActivityId(client, user_id, device_id, request['activity']['activity_id'])) _ValidateContacts(request['contacts']) (yield gen.Task(Operat...
null
null
null
What does this function do?
def abs(mat, target=None): if (not target): target = mat err_code = _cudamat.apply_abs(mat.p_mat, target.p_mat) if err_code: raise generate_exception(err_code) return target
null
null
null
Apply abs to each element of the matrix mat.
pcsd
def abs mat target=None if not target target = mat err code = cudamat apply abs mat p mat target p mat if err code raise generate exception err code return target
15979
def abs(mat, target=None): if (not target): target = mat err_code = _cudamat.apply_abs(mat.p_mat, target.p_mat) if err_code: raise generate_exception(err_code) return target
Apply abs to each element of the matrix mat.
apply abs to each element of the matrix mat .
Question: What does this function do? Code: def abs(mat, target=None): if (not target): target = mat err_code = _cudamat.apply_abs(mat.p_mat, target.p_mat) if err_code: raise generate_exception(err_code) return target
null
null
null
What does this function do?
def unbox_usecase2(x): res = 0 for v in x: res += len(v) return res
null
null
null
Expect a set of tuples
pcsd
def unbox usecase2 x res = 0 for v in x res += len v return res
15985
def unbox_usecase2(x): res = 0 for v in x: res += len(v) return res
Expect a set of tuples
expect a set of tuples
Question: What does this function do? Code: def unbox_usecase2(x): res = 0 for v in x: res += len(v) return res
null
null
null
What does this function do?
def windowSequenceEval(DS, winsz, result): si_old = 0 idx = 0 x = [] y = [] seq_res = [] for (i, si) in enumerate(DS['sequence_index'][1:].astype(int)): tar = DS['target'][(si - 1)] curr_x = si_old correct = 0.0 wrong = 0.0 while (curr_x < si): x.append(curr_x) if (result[idx] == tar): correct...
null
null
null
take results of a window-based classification and assess/plot them on the sequence WARNING: NOT TESTED!
pcsd
def window Sequence Eval DS winsz result si old = 0 idx = 0 x = [] y = [] seq res = [] for i si in enumerate DS['sequence index'][1 ] astype int tar = DS['target'][ si - 1 ] curr x = si old correct = 0 0 wrong = 0 0 while curr x < si x append curr x if result[idx] == tar correct += 1 0 y += [1 0 1 0] else wrong += 1 0 ...
15988
def windowSequenceEval(DS, winsz, result): si_old = 0 idx = 0 x = [] y = [] seq_res = [] for (i, si) in enumerate(DS['sequence_index'][1:].astype(int)): tar = DS['target'][(si - 1)] curr_x = si_old correct = 0.0 wrong = 0.0 while (curr_x < si): x.append(curr_x) if (result[idx] == tar): correct...
take results of a window-based classification and assess/plot them on the sequence WARNING: NOT TESTED!
take results of a window - based classification and assess / plot them on the sequence
Question: What does this function do? Code: def windowSequenceEval(DS, winsz, result): si_old = 0 idx = 0 x = [] y = [] seq_res = [] for (i, si) in enumerate(DS['sequence_index'][1:].astype(int)): tar = DS['target'][(si - 1)] curr_x = si_old correct = 0.0 wrong = 0.0 while (curr_x < si): x.append(...
null
null
null
What does this function do?
def one_one_in_other(book_id_val_map, db, field, *args): deleted = tuple(((k,) for (k, v) in book_id_val_map.iteritems() if (v is None))) if deleted: db.executemany((u'DELETE FROM %s WHERE book=?' % field.metadata[u'table']), deleted) for book_id in deleted: field.table.book_col_map.pop(book_id[0], None) upda...
null
null
null
Set a one-one field in the non-books table, like comments
pcsd
def one one in other book id val map db field *args deleted = tuple k for k v in book id val map iteritems if v is None if deleted db executemany u'DELETE FROM %s WHERE book=?' % field metadata[u'table'] deleted for book id in deleted field table book col map pop book id[0] None updated = {k v for k v in book id val ma...
16006
def one_one_in_other(book_id_val_map, db, field, *args): deleted = tuple(((k,) for (k, v) in book_id_val_map.iteritems() if (v is None))) if deleted: db.executemany((u'DELETE FROM %s WHERE book=?' % field.metadata[u'table']), deleted) for book_id in deleted: field.table.book_col_map.pop(book_id[0], None) upda...
Set a one-one field in the non-books table, like comments
set a one - one field in the non - books table , like comments
Question: What does this function do? Code: def one_one_in_other(book_id_val_map, db, field, *args): deleted = tuple(((k,) for (k, v) in book_id_val_map.iteritems() if (v is None))) if deleted: db.executemany((u'DELETE FROM %s WHERE book=?' % field.metadata[u'table']), deleted) for book_id in deleted: field...
null
null
null
What does this function do?
def write_csv(results, headers, filename): with open(filename, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=headers) writer.writeheader() writer.writerows(results)
null
null
null
Write a set of results to a CSV file.
pcsd
def write csv results headers filename with open filename 'w' as csvfile writer = csv Dict Writer csvfile fieldnames=headers writer writeheader writer writerows results
16009
def write_csv(results, headers, filename): with open(filename, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=headers) writer.writeheader() writer.writerows(results)
Write a set of results to a CSV file.
write a set of results to a csv file .
Question: What does this function do? Code: def write_csv(results, headers, filename): with open(filename, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=headers) writer.writeheader() writer.writerows(results)
null
null
null
What does this function do?
def get_flow(context, db, driver, host, snapshot_id, ref): LOG.debug('Input parameters: context=%(context)s, db=%(db)s,driver=%(driver)s, host=%(host)s, snapshot_id=(snapshot_id)s, ref=%(ref)s.', {'context': context, 'db': db, 'driver': driver, 'host': host, 'snapshot_id': snapshot_id, 'ref': ref}) flow_name = (ACTIO...
null
null
null
Constructs and returns the manager entry point flow.
pcsd
def get flow context db driver host snapshot id ref LOG debug 'Input parameters context=% context s db=% db s driver=% driver s host=% host s snapshot id= snapshot id s ref=% ref s ' {'context' context 'db' db 'driver' driver 'host' host 'snapshot id' snapshot id 'ref' ref} flow name = ACTION replace ' ' ' ' + ' manage...
16016
def get_flow(context, db, driver, host, snapshot_id, ref): LOG.debug('Input parameters: context=%(context)s, db=%(db)s,driver=%(driver)s, host=%(host)s, snapshot_id=(snapshot_id)s, ref=%(ref)s.', {'context': context, 'db': db, 'driver': driver, 'host': host, 'snapshot_id': snapshot_id, 'ref': ref}) flow_name = (ACTIO...
Constructs and returns the manager entry point flow.
constructs and returns the manager entry point flow .
Question: What does this function do? Code: def get_flow(context, db, driver, host, snapshot_id, ref): LOG.debug('Input parameters: context=%(context)s, db=%(db)s,driver=%(driver)s, host=%(host)s, snapshot_id=(snapshot_id)s, ref=%(ref)s.', {'context': context, 'db': db, 'driver': driver, 'host': host, 'snapshot_id'...
null
null
null
What does this function do?
def getManipulatedPaths(close, loop, prefix, sideLength, xmlElement): rotatePoints(loop, prefix, xmlElement) return [loop]
null
null
null
Get equated paths.
pcsd
def get Manipulated Paths close loop prefix side Length xml Element rotate Points loop prefix xml Element return [loop]
16018
def getManipulatedPaths(close, loop, prefix, sideLength, xmlElement): rotatePoints(loop, prefix, xmlElement) return [loop]
Get equated paths.
get equated paths .
Question: What does this function do? Code: def getManipulatedPaths(close, loop, prefix, sideLength, xmlElement): rotatePoints(loop, prefix, xmlElement) return [loop]
null
null
null
What does this function do?
def _trim_id(data): old_id = data['id'] del data['id'] return (old_id, data)
null
null
null
Trims ID from JSON
pcsd
def trim id data old id = data['id'] del data['id'] return old id data
16019
def _trim_id(data): old_id = data['id'] del data['id'] return (old_id, data)
Trims ID from JSON
trims id from json
Question: What does this function do? Code: def _trim_id(data): old_id = data['id'] del data['id'] return (old_id, data)
null
null
null
What does this function do?
def transferClosestFillLoop(extrusionHalfWidth, oldOrderedLocation, remainingFillLoops, skein): closestDistance = 1e+18 closestFillLoop = None for remainingFillLoop in remainingFillLoops: distance = getNearestDistanceIndex(oldOrderedLocation.dropAxis(2), remainingFillLoop).distance if (distance < closestDistance...
null
null
null
Transfer the closest remaining fill loop.
pcsd
def transfer Closest Fill Loop extrusion Half Width old Ordered Location remaining Fill Loops skein closest Distance = 1e+18 closest Fill Loop = None for remaining Fill Loop in remaining Fill Loops distance = get Nearest Distance Index old Ordered Location drop Axis 2 remaining Fill Loop distance if distance < closest ...
16020
def transferClosestFillLoop(extrusionHalfWidth, oldOrderedLocation, remainingFillLoops, skein): closestDistance = 1e+18 closestFillLoop = None for remainingFillLoop in remainingFillLoops: distance = getNearestDistanceIndex(oldOrderedLocation.dropAxis(2), remainingFillLoop).distance if (distance < closestDistance...
Transfer the closest remaining fill loop.
transfer the closest remaining fill loop .
Question: What does this function do? Code: def transferClosestFillLoop(extrusionHalfWidth, oldOrderedLocation, remainingFillLoops, skein): closestDistance = 1e+18 closestFillLoop = None for remainingFillLoop in remainingFillLoops: distance = getNearestDistanceIndex(oldOrderedLocation.dropAxis(2), remainingFill...
null
null
null
What does this function do?
def getNewRepository(): return ClipRepository()
null
null
null
Get the repository constructor.
pcsd
def get New Repository return Clip Repository
16021
def getNewRepository(): return ClipRepository()
Get the repository constructor.
get the repository constructor .
Question: What does this function do? Code: def getNewRepository(): return ClipRepository()
null
null
null
What does this function do?
def java_fat_library(name, srcs=[], deps=[], resources=[], source_encoding=None, warnings=None, exclusions=[], **kwargs): target = JavaFatLibrary(name, srcs, deps, resources, source_encoding, warnings, exclusions, kwargs) blade.blade.register_target(target)
null
null
null
Define java_fat_library target.
pcsd
def java fat library name srcs=[] deps=[] resources=[] source encoding=None warnings=None exclusions=[] **kwargs target = Java Fat Library name srcs deps resources source encoding warnings exclusions kwargs blade blade register target target
16032
def java_fat_library(name, srcs=[], deps=[], resources=[], source_encoding=None, warnings=None, exclusions=[], **kwargs): target = JavaFatLibrary(name, srcs, deps, resources, source_encoding, warnings, exclusions, kwargs) blade.blade.register_target(target)
Define java_fat_library target.
define java _ fat _ library target .
Question: What does this function do? Code: def java_fat_library(name, srcs=[], deps=[], resources=[], source_encoding=None, warnings=None, exclusions=[], **kwargs): target = JavaFatLibrary(name, srcs, deps, resources, source_encoding, warnings, exclusions, kwargs) blade.blade.register_target(target)
null
null
null
What does this function do?
def ext_pillar(minion_id, pillar, *args, **kwargs): return MySQLExtPillar().fetch(minion_id, pillar, *args, **kwargs)
null
null
null
Execute queries against MySQL, merge and return as a dict
pcsd
def ext pillar minion id pillar *args **kwargs return My SQL Ext Pillar fetch minion id pillar *args **kwargs
16035
def ext_pillar(minion_id, pillar, *args, **kwargs): return MySQLExtPillar().fetch(minion_id, pillar, *args, **kwargs)
Execute queries against MySQL, merge and return as a dict
execute queries against mysql , merge and return as a dict
Question: What does this function do? Code: def ext_pillar(minion_id, pillar, *args, **kwargs): return MySQLExtPillar().fetch(minion_id, pillar, *args, **kwargs)
null
null
null
What does this function do?
def timestamp_utc(value): try: return dt_util.utc_from_timestamp(value).strftime(DATE_STR_FORMAT) except (ValueError, TypeError): return value
null
null
null
Filter to convert given timestamp to UTC date/time.
pcsd
def timestamp utc value try return dt util utc from timestamp value strftime DATE STR FORMAT except Value Error Type Error return value
16047
def timestamp_utc(value): try: return dt_util.utc_from_timestamp(value).strftime(DATE_STR_FORMAT) except (ValueError, TypeError): return value
Filter to convert given timestamp to UTC date/time.
filter to convert given timestamp to utc date / time .
Question: What does this function do? Code: def timestamp_utc(value): try: return dt_util.utc_from_timestamp(value).strftime(DATE_STR_FORMAT) except (ValueError, TypeError): return value
null
null
null
What does this function do?
def password_changed(password, user=None, password_validators=None): if (password_validators is None): password_validators = get_default_password_validators() for validator in password_validators: password_changed = getattr(validator, 'password_changed', (lambda *a: None)) password_changed(password, user)
null
null
null
Inform all validators that have implemented a password_changed() method that the password has been changed.
pcsd
def password changed password user=None password validators=None if password validators is None password validators = get default password validators for validator in password validators password changed = getattr validator 'password changed' lambda *a None password changed password user
16050
def password_changed(password, user=None, password_validators=None): if (password_validators is None): password_validators = get_default_password_validators() for validator in password_validators: password_changed = getattr(validator, 'password_changed', (lambda *a: None)) password_changed(password, user)
Inform all validators that have implemented a password_changed() method that the password has been changed.
inform all validators that have implemented a password _ changed ( ) method that the password has been changed .
Question: What does this function do? Code: def password_changed(password, user=None, password_validators=None): if (password_validators is None): password_validators = get_default_password_validators() for validator in password_validators: password_changed = getattr(validator, 'password_changed', (lambda *a: ...
null
null
null
What does this function do?
@app.route('/<username>/follow') def follow_user(username): if (not g.user): abort(401) whom_id = get_user_id(username) if (whom_id is None): abort(404) db = get_db() db.execute('insert into follower (who_id, whom_id) values (?, ?)', [session['user_id'], whom_id]) db.commit() flash(('You are now following "%...
null
null
null
Adds the current user as follower of the given user.
pcsd
@app route '/<username>/follow' def follow user username if not g user abort 401 whom id = get user id username if whom id is None abort 404 db = get db db execute 'insert into follower who id whom id values ? ? ' [session['user id'] whom id] db commit flash 'You are now following "%s"' % username return redirect url f...
16054
@app.route('/<username>/follow') def follow_user(username): if (not g.user): abort(401) whom_id = get_user_id(username) if (whom_id is None): abort(404) db = get_db() db.execute('insert into follower (who_id, whom_id) values (?, ?)', [session['user_id'], whom_id]) db.commit() flash(('You are now following "%...
Adds the current user as follower of the given user.
adds the current user as follower of the given user .
Question: What does this function do? Code: @app.route('/<username>/follow') def follow_user(username): if (not g.user): abort(401) whom_id = get_user_id(username) if (whom_id is None): abort(404) db = get_db() db.execute('insert into follower (who_id, whom_id) values (?, ?)', [session['user_id'], whom_id])...
null
null
null
What does this function do?
def parse_distances(lines, results): distances = {} sequences = [] raw_aa_distances_flag = False ml_aa_distances_flag = False matrix_row_re = re.compile('(.+)\\s{5,15}') for line in lines: line_floats_res = line_floats_re.findall(line) line_floats = [_nan_float(val) for val in line_floats_res] if ('AA dista...
null
null
null
Parse amino acid sequence distance results.
pcsd
def parse distances lines results distances = {} sequences = [] raw aa distances flag = False ml aa distances flag = False matrix row re = re compile ' + \\s{5 15}' for line in lines line floats res = line floats re findall line line floats = [ nan float val for val in line floats res] if 'AA distances' in line raw aa ...
16057
def parse_distances(lines, results): distances = {} sequences = [] raw_aa_distances_flag = False ml_aa_distances_flag = False matrix_row_re = re.compile('(.+)\\s{5,15}') for line in lines: line_floats_res = line_floats_re.findall(line) line_floats = [_nan_float(val) for val in line_floats_res] if ('AA dista...
Parse amino acid sequence distance results.
parse amino acid sequence distance results .
Question: What does this function do? Code: def parse_distances(lines, results): distances = {} sequences = [] raw_aa_distances_flag = False ml_aa_distances_flag = False matrix_row_re = re.compile('(.+)\\s{5,15}') for line in lines: line_floats_res = line_floats_re.findall(line) line_floats = [_nan_float(v...
null
null
null
What does this function do?
def _is_list_like(obj): return ((not is_string_like(obj)) and iterable(obj))
null
null
null
Returns whether the obj is iterable and not a string
pcsd
def is list like obj return not is string like obj and iterable obj
16062
def _is_list_like(obj): return ((not is_string_like(obj)) and iterable(obj))
Returns whether the obj is iterable and not a string
returns whether the obj is iterable and not a string
Question: What does this function do? Code: def _is_list_like(obj): return ((not is_string_like(obj)) and iterable(obj))
null
null
null
What does this function do?
def __virtual__(algorithm='sha512'): if ((not hasattr(hashlib, 'algorithms')) and (not hasattr(hashlib, algorithm))): return (False, 'The random execution module cannot be loaded: only available in Python >= 2.7.') return __virtualname__
null
null
null
Sanity check for compatibility with Python 2.6 / 2.7
pcsd
def virtual algorithm='sha512' if not hasattr hashlib 'algorithms' and not hasattr hashlib algorithm return False 'The random execution module cannot be loaded only available in Python >= 2 7 ' return virtualname
16067
def __virtual__(algorithm='sha512'): if ((not hasattr(hashlib, 'algorithms')) and (not hasattr(hashlib, algorithm))): return (False, 'The random execution module cannot be loaded: only available in Python >= 2.7.') return __virtualname__
Sanity check for compatibility with Python 2.6 / 2.7
sanity check for compatibility with python 2 . 6 / 2 . 7
Question: What does this function do? Code: def __virtual__(algorithm='sha512'): if ((not hasattr(hashlib, 'algorithms')) and (not hasattr(hashlib, algorithm))): return (False, 'The random execution module cannot be loaded: only available in Python >= 2.7.') return __virtualname__
null
null
null
What does this function do?
@utils.arg('--all-tenants', action='store_const', const=1, default=0, help=_('Start server(s) in another tenant by name (Admin only).')) @utils.arg('server', metavar='<server>', nargs='+', help=_('Name or ID of server(s).')) def do_start(cs, args): find_args = {'all_tenants': args.all_tenants} utils.do_action_on_many...
null
null
null
Start the server(s).
pcsd
@utils arg '--all-tenants' action='store const' const=1 default=0 help= 'Start server s in another tenant by name Admin only ' @utils arg 'server' metavar='<server>' nargs='+' help= 'Name or ID of server s ' def do start cs args find args = {'all tenants' args all tenants} utils do action on many lambda s find server c...
16069
@utils.arg('--all-tenants', action='store_const', const=1, default=0, help=_('Start server(s) in another tenant by name (Admin only).')) @utils.arg('server', metavar='<server>', nargs='+', help=_('Name or ID of server(s).')) def do_start(cs, args): find_args = {'all_tenants': args.all_tenants} utils.do_action_on_many...
Start the server(s).
start the server ( s ) .
Question: What does this function do? Code: @utils.arg('--all-tenants', action='store_const', const=1, default=0, help=_('Start server(s) in another tenant by name (Admin only).')) @utils.arg('server', metavar='<server>', nargs='+', help=_('Name or ID of server(s).')) def do_start(cs, args): find_args = {'all_tenan...
null
null
null
What does this function do?
def win_cmd(command, **kwargs): logging_command = kwargs.get('logging_command', None) try: proc = NonBlockingPopen(command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, stream_stds=kwargs.get('display_ssh_output', True), logging_command=logging_command) if (logging_command is None): log.debug("E...
null
null
null
Wrapper for commands to be run against Windows boxes
pcsd
def win cmd command **kwargs logging command = kwargs get 'logging command' None try proc = Non Blocking Popen command shell=True stderr=subprocess PIPE stdout=subprocess PIPE stream stds=kwargs get 'display ssh output' True logging command=logging command if logging command is None log debug "Executing command PID %s ...
16070
def win_cmd(command, **kwargs): logging_command = kwargs.get('logging_command', None) try: proc = NonBlockingPopen(command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, stream_stds=kwargs.get('display_ssh_output', True), logging_command=logging_command) if (logging_command is None): log.debug("E...
Wrapper for commands to be run against Windows boxes
wrapper for commands to be run against windows boxes
Question: What does this function do? Code: def win_cmd(command, **kwargs): logging_command = kwargs.get('logging_command', None) try: proc = NonBlockingPopen(command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, stream_stds=kwargs.get('display_ssh_output', True), logging_command=logging_command) ...
null
null
null
What does this function do?
def human_readable(size, precision=1): return ((('%.' + str(precision)) + 'f') % ((size / (1024.0 * 1024.0)),))
null
null
null
Convert a size in bytes into megabytes
pcsd
def human readable size precision=1 return '% ' + str precision + 'f' % size / 1024 0 * 1024 0
16073
def human_readable(size, precision=1): return ((('%.' + str(precision)) + 'f') % ((size / (1024.0 * 1024.0)),))
Convert a size in bytes into megabytes
convert a size in bytes into megabytes
Question: What does this function do? Code: def human_readable(size, precision=1): return ((('%.' + str(precision)) + 'f') % ((size / (1024.0 * 1024.0)),))
null
null
null
What does this function do?
def commit(using=None): if (using is None): using = DEFAULT_DB_ALIAS connection = connections[using] connection._commit() set_clean(using=using)
null
null
null
Does the commit itself and resets the dirty flag.
pcsd
def commit using=None if using is None using = DEFAULT DB ALIAS connection = connections[using] connection commit set clean using=using
16075
def commit(using=None): if (using is None): using = DEFAULT_DB_ALIAS connection = connections[using] connection._commit() set_clean(using=using)
Does the commit itself and resets the dirty flag.
does the commit itself and resets the dirty flag .
Question: What does this function do? Code: def commit(using=None): if (using is None): using = DEFAULT_DB_ALIAS connection = connections[using] connection._commit() set_clean(using=using)
null
null
null
What does this function do?
def snapshot_metadata_update(context, snapshot_id, metadata, delete): return IMPL.snapshot_metadata_update(context, snapshot_id, metadata, delete)
null
null
null
Update metadata if it exists, otherwise create it.
pcsd
def snapshot metadata update context snapshot id metadata delete return IMPL snapshot metadata update context snapshot id metadata delete
16080
def snapshot_metadata_update(context, snapshot_id, metadata, delete): return IMPL.snapshot_metadata_update(context, snapshot_id, metadata, delete)
Update metadata if it exists, otherwise create it.
update metadata if it exists , otherwise create it .
Question: What does this function do? Code: def snapshot_metadata_update(context, snapshot_id, metadata, delete): return IMPL.snapshot_metadata_update(context, snapshot_id, metadata, delete)
null
null
null
What does this function do?
def send_poetry(sock, poetry_file, num_bytes, delay): inputf = open(poetry_file) while True: bytes = inputf.read(num_bytes) if (not bytes): sock.close() inputf.close() return print ('Sending %d bytes' % len(bytes)) try: sock.sendall(bytes) except socket.error: sock.close() inputf.close() ...
null
null
null
Send some poetry slowly down the socket.
pcsd
def send poetry sock poetry file num bytes delay inputf = open poetry file while True bytes = inputf read num bytes if not bytes sock close inputf close return print 'Sending %d bytes' % len bytes try sock sendall bytes except socket error sock close inputf close return time sleep delay
16086
def send_poetry(sock, poetry_file, num_bytes, delay): inputf = open(poetry_file) while True: bytes = inputf.read(num_bytes) if (not bytes): sock.close() inputf.close() return print ('Sending %d bytes' % len(bytes)) try: sock.sendall(bytes) except socket.error: sock.close() inputf.close() ...
Send some poetry slowly down the socket.
send some poetry slowly down the socket .
Question: What does this function do? Code: def send_poetry(sock, poetry_file, num_bytes, delay): inputf = open(poetry_file) while True: bytes = inputf.read(num_bytes) if (not bytes): sock.close() inputf.close() return print ('Sending %d bytes' % len(bytes)) try: sock.sendall(bytes) except so...
null
null
null
What does this function do?
@raises(ActionError) def test_parse_command_action_error(): arg_str = 'selector invalid_action' screenshot._parse_command(arg_str)
null
null
null
Test ActionError(s) raised by screenshot._parse_command() function.
pcsd
@raises Action Error def test parse command action error arg str = 'selector invalid action' screenshot parse command arg str
16092
@raises(ActionError) def test_parse_command_action_error(): arg_str = 'selector invalid_action' screenshot._parse_command(arg_str)
Test ActionError(s) raised by screenshot._parse_command() function.
test actionerror ( s ) raised by screenshot . _ parse _ command ( ) function .
Question: What does this function do? Code: @raises(ActionError) def test_parse_command_action_error(): arg_str = 'selector invalid_action' screenshot._parse_command(arg_str)
null
null
null
What does this function do?
def warnOnException(func): def w(*args, **kwds): try: func(*args, **kwds) except: printExc('Ignored exception:') return w
null
null
null
Decorator that catches/ignores exceptions and prints a stack trace.
pcsd
def warn On Exception func def w *args **kwds try func *args **kwds except print Exc 'Ignored exception ' return w
16093
def warnOnException(func): def w(*args, **kwds): try: func(*args, **kwds) except: printExc('Ignored exception:') return w
Decorator that catches/ignores exceptions and prints a stack trace.
decorator that catches / ignores exceptions and prints a stack trace .
Question: What does this function do? Code: def warnOnException(func): def w(*args, **kwds): try: func(*args, **kwds) except: printExc('Ignored exception:') return w
null
null
null
What does this function do?
def disabled(name): ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} stat = __salt__['rdp.status']() if stat: if __opts__['test']: ret['result'] = None ret['comment'] = 'RDP will be disabled' return ret ret['result'] = __salt__['rdp.disable']() ret['changes'] = {'RDP was disabled': T...
null
null
null
Disable the RDP service
pcsd
def disabled name ret = {'name' name 'result' True 'changes' {} 'comment' ''} stat = salt ['rdp status'] if stat if opts ['test'] ret['result'] = None ret['comment'] = 'RDP will be disabled' return ret ret['result'] = salt ['rdp disable'] ret['changes'] = {'RDP was disabled' True} return ret ret['comment'] = 'RDP is di...
16114
def disabled(name): ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} stat = __salt__['rdp.status']() if stat: if __opts__['test']: ret['result'] = None ret['comment'] = 'RDP will be disabled' return ret ret['result'] = __salt__['rdp.disable']() ret['changes'] = {'RDP was disabled': T...
Disable the RDP service
disable the rdp service
Question: What does this function do? Code: def disabled(name): ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} stat = __salt__['rdp.status']() if stat: if __opts__['test']: ret['result'] = None ret['comment'] = 'RDP will be disabled' return ret ret['result'] = __salt__['rdp.disabl...
null
null
null
What does this function do?
@utils.decorator def transactional_async(func, args, kwds, **options): options.setdefault('propagation', datastore_rpc.TransactionOptions.ALLOWED) if (args or kwds): return transaction_async((lambda : func(*args, **kwds)), **options) return transaction_async(func, **options)
null
null
null
The async version of @ndb.transaction.
pcsd
@utils decorator def transactional async func args kwds **options options setdefault 'propagation' datastore rpc Transaction Options ALLOWED if args or kwds return transaction async lambda func *args **kwds **options return transaction async func **options
16115
@utils.decorator def transactional_async(func, args, kwds, **options): options.setdefault('propagation', datastore_rpc.TransactionOptions.ALLOWED) if (args or kwds): return transaction_async((lambda : func(*args, **kwds)), **options) return transaction_async(func, **options)
The async version of @ndb.transaction.
the async version of @ ndb . transaction .
Question: What does this function do? Code: @utils.decorator def transactional_async(func, args, kwds, **options): options.setdefault('propagation', datastore_rpc.TransactionOptions.ALLOWED) if (args or kwds): return transaction_async((lambda : func(*args, **kwds)), **options) return transaction_async(func, **o...
null
null
null
What does this function do?
def set_activity_type_requires(tablename, sector_ids): attable = s3db.project_activity_type if sector_ids: atstable = s3db.project_activity_type_sector rows = db().select(attable.id, atstable.sector_id, left=atstable.on((attable.id == atstable.activity_type_id))) activity_type_ids = [row.project_activity_type.i...
null
null
null
Filters the activity_type_id based on the sector_id
pcsd
def set activity type requires tablename sector ids attable = s3db project activity type if sector ids atstable = s3db project activity type sector rows = db select attable id atstable sector id left=atstable on attable id == atstable activity type id activity type ids = [row project activity type id for row in rows if...
16117
def set_activity_type_requires(tablename, sector_ids): attable = s3db.project_activity_type if sector_ids: atstable = s3db.project_activity_type_sector rows = db().select(attable.id, atstable.sector_id, left=atstable.on((attable.id == atstable.activity_type_id))) activity_type_ids = [row.project_activity_type.i...
Filters the activity_type_id based on the sector_id
filters the activity _ type _ id based on the sector _ id
Question: What does this function do? Code: def set_activity_type_requires(tablename, sector_ids): attable = s3db.project_activity_type if sector_ids: atstable = s3db.project_activity_type_sector rows = db().select(attable.id, atstable.sector_id, left=atstable.on((attable.id == atstable.activity_type_id))) a...
null
null
null
What does this function do?
def api_version(f): @wraps(f) def wrapped(*args, **kwargs): rv = f(*args, **kwargs) rv.headers[u'API-Version'] = __version__ return rv return wrapped
null
null
null
Add the \'API-Version\' header to all responses
pcsd
def api version f @wraps f def wrapped *args **kwargs rv = f *args **kwargs rv headers[u'API-Version'] = version return rv return wrapped
16130
def api_version(f): @wraps(f) def wrapped(*args, **kwargs): rv = f(*args, **kwargs) rv.headers[u'API-Version'] = __version__ return rv return wrapped
Add the \'API-Version\' header to all responses
add the api - version header to all responses
Question: What does this function do? Code: def api_version(f): @wraps(f) def wrapped(*args, **kwargs): rv = f(*args, **kwargs) rv.headers[u'API-Version'] = __version__ return rv return wrapped
null
null
null
What does this function do?
def content_type(content_type): def decorator(method): method.content_type = content_type return method return decorator
null
null
null
Attaches the supplied content_type to a Hug formatting function
pcsd
def content type content type def decorator method method content type = content type return method return decorator
16137
def content_type(content_type): def decorator(method): method.content_type = content_type return method return decorator
Attaches the supplied content_type to a Hug formatting function
attaches the supplied content _ type to a hug formatting function
Question: What does this function do? Code: def content_type(content_type): def decorator(method): method.content_type = content_type return method return decorator
null
null
null
What does this function do?
def _allow_CTRL_C_other(): pass
null
null
null
Take CTRL+C into account (not implemented).
pcsd
def allow CTRL C other pass
16143
def _allow_CTRL_C_other(): pass
Take CTRL+C into account (not implemented).
take ctrl + c into account .
Question: What does this function do? Code: def _allow_CTRL_C_other(): pass
null
null
null
What does this function do?
@check_login_required @check_local_site_access def preview_reply_email(request, review_request_id, review_id, reply_id, format, text_template_name=u'notifications/reply_email.txt', html_template_name=u'notifications/reply_email.html', local_site=None): if (not settings.DEBUG): raise Http404 (review_request, respons...
null
null
null
Previews the e-mail message that would be sent for a reply to a review of a review request. This is mainly used for debugging.
pcsd
@check login required @check local site access def preview reply email request review request id review id reply id format text template name=u'notifications/reply email txt' html template name=u'notifications/reply email html' local site=None if not settings DEBUG raise Http404 review request response = find review re...
16150
@check_login_required @check_local_site_access def preview_reply_email(request, review_request_id, review_id, reply_id, format, text_template_name=u'notifications/reply_email.txt', html_template_name=u'notifications/reply_email.html', local_site=None): if (not settings.DEBUG): raise Http404 (review_request, respons...
Previews the e-mail message that would be sent for a reply to a review of a review request. This is mainly used for debugging.
previews the e - mail message that would be sent for a reply to a review of a review request .
Question: What does this function do? Code: @check_login_required @check_local_site_access def preview_reply_email(request, review_request_id, review_id, reply_id, format, text_template_name=u'notifications/reply_email.txt', html_template_name=u'notifications/reply_email.html', local_site=None): if (not settings.DE...
null
null
null
What does this function do?
def dumps(value): return base64.b64encode(pickle.dumps(value, pickle.HIGHEST_PROTOCOL))
null
null
null
Pickle a value
pcsd
def dumps value return base64 b64encode pickle dumps value pickle HIGHEST PROTOCOL
16162
def dumps(value): return base64.b64encode(pickle.dumps(value, pickle.HIGHEST_PROTOCOL))
Pickle a value
pickle a value
Question: What does this function do? Code: def dumps(value): return base64.b64encode(pickle.dumps(value, pickle.HIGHEST_PROTOCOL))
null
null
null
What does this function do?
def _timestamp(pathname): try: s = os.stat(pathname) except OSError: return None return long(s[8])
null
null
null
Return the file modification time as a Long.
pcsd
def timestamp pathname try s = os stat pathname except OS Error return None return long s[8]
16170
def _timestamp(pathname): try: s = os.stat(pathname) except OSError: return None return long(s[8])
Return the file modification time as a Long.
return the file modification time as a long .
Question: What does this function do? Code: def _timestamp(pathname): try: s = os.stat(pathname) except OSError: return None return long(s[8])
null
null
null
What does this function do?
def _proc(msg, level_color='DEBUG'): msg = msg.split(MAGIC) r = '' i = 0 cmd = False while (i < len(msg)): m = msg[i] i += 1 if cmd: best = None bestlen = 0 for (k, v) in COMMANDS.iteritems(): if (len(k) > bestlen): if m.startswith(k): best = (k, v) bestlen = len(k) special =...
null
null
null
Do some replacements on the text
pcsd
def proc msg level color='DEBUG' msg = msg split MAGIC r = '' i = 0 cmd = False while i < len msg m = msg[i] i += 1 if cmd best = None bestlen = 0 for k v in COMMANDS iteritems if len k > bestlen if m startswith k best = k v bestlen = len k special = None if best is not None and best[0] endswith ' ' special = best m = ...
16172
def _proc(msg, level_color='DEBUG'): msg = msg.split(MAGIC) r = '' i = 0 cmd = False while (i < len(msg)): m = msg[i] i += 1 if cmd: best = None bestlen = 0 for (k, v) in COMMANDS.iteritems(): if (len(k) > bestlen): if m.startswith(k): best = (k, v) bestlen = len(k) special =...
Do some replacements on the text
do some replacements on the text
Question: What does this function do? Code: def _proc(msg, level_color='DEBUG'): msg = msg.split(MAGIC) r = '' i = 0 cmd = False while (i < len(msg)): m = msg[i] i += 1 if cmd: best = None bestlen = 0 for (k, v) in COMMANDS.iteritems(): if (len(k) > bestlen): if m.startswith(k): be...
null
null
null
What does this function do?
def dictfetchall(cursor): desc = cursor.description for row in cursor.fetchall(): (yield _dict_helper(desc, row))
null
null
null
Returns all rows from a cursor as a dict
pcsd
def dictfetchall cursor desc = cursor description for row in cursor fetchall yield dict helper desc row
16175
def dictfetchall(cursor): desc = cursor.description for row in cursor.fetchall(): (yield _dict_helper(desc, row))
Returns all rows from a cursor as a dict
returns all rows from a cursor as a dict
Question: What does this function do? Code: def dictfetchall(cursor): desc = cursor.description for row in cursor.fetchall(): (yield _dict_helper(desc, row))
null
null
null
What does this function do?
def getNewRepository(): return TowerRepository()
null
null
null
Get the repository constructor.
pcsd
def get New Repository return Tower Repository
16183
def getNewRepository(): return TowerRepository()
Get the repository constructor.
get the repository constructor .
Question: What does this function do? Code: def getNewRepository(): return TowerRepository()
null
null
null
What does this function do?
def is_mt_res(item): return item.startswith('Packages/Material Theme/')
null
null
null
Check if a Material Theme resource.
pcsd
def is mt res item return item startswith 'Packages/Material Theme/'
16199
def is_mt_res(item): return item.startswith('Packages/Material Theme/')
Check if a Material Theme resource.
check if a material theme resource .
Question: What does this function do? Code: def is_mt_res(item): return item.startswith('Packages/Material Theme/')
null
null
null
What does this function do?
def touch_import(package, name, node): def is_import_stmt(node): return ((node.type == syms.simple_stmt) and node.children and is_import(node.children[0])) root = find_root(node) if does_tree_import(package, name, root): return insert_pos = offset = 0 for (idx, node) in enumerate(root.children): if (not is_i...
null
null
null
Works like `does_tree_import` but adds an import statement if it was not imported.
pcsd
def touch import package name node def is import stmt node return node type == syms simple stmt and node children and is import node children[0] root = find root node if does tree import package name root return insert pos = offset = 0 for idx node in enumerate root children if not is import stmt node continue for offs...
16201
def touch_import(package, name, node): def is_import_stmt(node): return ((node.type == syms.simple_stmt) and node.children and is_import(node.children[0])) root = find_root(node) if does_tree_import(package, name, root): return insert_pos = offset = 0 for (idx, node) in enumerate(root.children): if (not is_i...
Works like `does_tree_import` but adds an import statement if it was not imported.
works like does _ tree _ import but adds an import statement if it was not imported .
Question: What does this function do? Code: def touch_import(package, name, node): def is_import_stmt(node): return ((node.type == syms.simple_stmt) and node.children and is_import(node.children[0])) root = find_root(node) if does_tree_import(package, name, root): return insert_pos = offset = 0 for (idx, no...
null
null
null
What does this function do?
def assert_element_text_matches(output, path, expression): text = xml_find_text(output, path) if (re.match(expression, text) is None): errmsg = ("Expected element with path '%s' to contain text matching '%s', instead text '%s' was found." % (path, expression, text)) raise AssertionError(errmsg)
null
null
null
Asserts the text of the first element matching the specified path matches the specified regular expression.
pcsd
def assert element text matches output path expression text = xml find text output path if re match expression text is None errmsg = "Expected element with path '%s' to contain text matching '%s' instead text '%s' was found " % path expression text raise Assertion Error errmsg
16203
def assert_element_text_matches(output, path, expression): text = xml_find_text(output, path) if (re.match(expression, text) is None): errmsg = ("Expected element with path '%s' to contain text matching '%s', instead text '%s' was found." % (path, expression, text)) raise AssertionError(errmsg)
Asserts the text of the first element matching the specified path matches the specified regular expression.
asserts the text of the first element matching the specified path matches the specified regular expression .
Question: What does this function do? Code: def assert_element_text_matches(output, path, expression): text = xml_find_text(output, path) if (re.match(expression, text) is None): errmsg = ("Expected element with path '%s' to contain text matching '%s', instead text '%s' was found." % (path, expression, text)) ...
null
null
null
What does this function do?
def log_signals(obj): def log_slot(obj, signal, *args): 'Slot connected to a signal to log it.' dbg = dbg_signal(signal, args) try: r = repr(obj) except RuntimeError: r = '<deleted>' log.signals.debug('Signal in {}: {}'.format(r, dbg)) def connect_log_slot(obj): 'Helper function to connect all signa...
null
null
null
Log all signals of an object or class. Can be used as class decorator.
pcsd
def log signals obj def log slot obj signal *args 'Slot connected to a signal to log it ' dbg = dbg signal signal args try r = repr obj except Runtime Error r = '<deleted>' log signals debug 'Signal in {} {}' format r dbg def connect log slot obj 'Helper function to connect all signals to a logging slot ' metaobj = obj...
16211
def log_signals(obj): def log_slot(obj, signal, *args): 'Slot connected to a signal to log it.' dbg = dbg_signal(signal, args) try: r = repr(obj) except RuntimeError: r = '<deleted>' log.signals.debug('Signal in {}: {}'.format(r, dbg)) def connect_log_slot(obj): 'Helper function to connect all signa...
Log all signals of an object or class. Can be used as class decorator.
log all signals of an object or class .
Question: What does this function do? Code: def log_signals(obj): def log_slot(obj, signal, *args): 'Slot connected to a signal to log it.' dbg = dbg_signal(signal, args) try: r = repr(obj) except RuntimeError: r = '<deleted>' log.signals.debug('Signal in {}: {}'.format(r, dbg)) def connect_log_slo...
null
null
null
What does this function do?
def load_windowstime(buf, pos): unix_epoch = 11644473600 (val1, pos) = load_le32(buf, pos) (val2, pos) = load_le32(buf, pos) (secs, n1secs) = divmod(((val2 << 32) | val1), 10000000) dt = datetime.fromtimestamp((secs - unix_epoch), UTC) dt = dt.replace(microsecond=(n1secs // 10)) return (dt, pos)
null
null
null
Load LE64 windows timestamp
pcsd
def load windowstime buf pos unix epoch = 11644473600 val1 pos = load le32 buf pos val2 pos = load le32 buf pos secs n1secs = divmod val2 << 32 | val1 10000000 dt = datetime fromtimestamp secs - unix epoch UTC dt = dt replace microsecond= n1secs // 10 return dt pos
16220
def load_windowstime(buf, pos): unix_epoch = 11644473600 (val1, pos) = load_le32(buf, pos) (val2, pos) = load_le32(buf, pos) (secs, n1secs) = divmod(((val2 << 32) | val1), 10000000) dt = datetime.fromtimestamp((secs - unix_epoch), UTC) dt = dt.replace(microsecond=(n1secs // 10)) return (dt, pos)
Load LE64 windows timestamp
load le64 windows timestamp
Question: What does this function do? Code: def load_windowstime(buf, pos): unix_epoch = 11644473600 (val1, pos) = load_le32(buf, pos) (val2, pos) = load_le32(buf, pos) (secs, n1secs) = divmod(((val2 << 32) | val1), 10000000) dt = datetime.fromtimestamp((secs - unix_epoch), UTC) dt = dt.replace(microsecond=(n1...
null
null
null
What does this function do?
def validate_input_element_identifiers(element_identifiers): log.debug(('Validating %d element identifiers for collection creation.' % len(element_identifiers))) identifier_names = set() for element_identifier in element_identifiers: if ('__object__' in element_identifier): message = (ERROR_MESSAGE_INVALID_PARA...
null
null
null
Scan through the list of element identifiers supplied by the API consumer and verify the structure is valid.
pcsd
def validate input element identifiers element identifiers log debug 'Validating %d element identifiers for collection creation ' % len element identifiers identifier names = set for element identifier in element identifiers if ' object ' in element identifier message = ERROR MESSAGE INVALID PARAMETER FOUND % ' object ...
16222
def validate_input_element_identifiers(element_identifiers): log.debug(('Validating %d element identifiers for collection creation.' % len(element_identifiers))) identifier_names = set() for element_identifier in element_identifiers: if ('__object__' in element_identifier): message = (ERROR_MESSAGE_INVALID_PARA...
Scan through the list of element identifiers supplied by the API consumer and verify the structure is valid.
scan through the list of element identifiers supplied by the api consumer and verify the structure is valid .
Question: What does this function do? Code: def validate_input_element_identifiers(element_identifiers): log.debug(('Validating %d element identifiers for collection creation.' % len(element_identifiers))) identifier_names = set() for element_identifier in element_identifiers: if ('__object__' in element_identi...
null
null
null
What does this function do?
@pytest.fixture def admin_group(db): return Group.objects.create(name='Admins', rules='*:*')
null
null
null
Create the Admins group.
pcsd
@pytest fixture def admin group db return Group objects create name='Admins' rules='* *'
16223
@pytest.fixture def admin_group(db): return Group.objects.create(name='Admins', rules='*:*')
Create the Admins group.
create the admins group .
Question: What does this function do? Code: @pytest.fixture def admin_group(db): return Group.objects.create(name='Admins', rules='*:*')
null
null
null
What does this function do?
@register.filter def can_read(obj, user): return obj.can_read(user)
null
null
null
Takes article or related to article model. Check if user can read article.
pcsd
@register filter def can read obj user return obj can read user
16224
@register.filter def can_read(obj, user): return obj.can_read(user)
Takes article or related to article model. Check if user can read article.
takes article or related to article model .
Question: What does this function do? Code: @register.filter def can_read(obj, user): return obj.can_read(user)
null
null
null
What does this function do?
def force_mapping(m): if isinstance(m, (LazyObject, LazySettings)): m = m._wrapped return (DictAttribute(m) if (not isinstance(m, Mapping)) else m)
null
null
null
Wrap object into supporting the mapping interface if necessary.
pcsd
def force mapping m if isinstance m Lazy Object Lazy Settings m = m wrapped return Dict Attribute m if not isinstance m Mapping else m
16231
def force_mapping(m): if isinstance(m, (LazyObject, LazySettings)): m = m._wrapped return (DictAttribute(m) if (not isinstance(m, Mapping)) else m)
Wrap object into supporting the mapping interface if necessary.
wrap object into supporting the mapping interface if necessary .
Question: What does this function do? Code: def force_mapping(m): if isinstance(m, (LazyObject, LazySettings)): m = m._wrapped return (DictAttribute(m) if (not isinstance(m, Mapping)) else m)
null
null
null
What does this function do?
def xen_mem(name): global conn global conn_info return (conn_info[1] * 1024)
null
null
null
Return node memory
pcsd
def xen mem name global conn global conn info return conn info[1] * 1024
16239
def xen_mem(name): global conn global conn_info return (conn_info[1] * 1024)
Return node memory
return node memory
Question: What does this function do? Code: def xen_mem(name): global conn global conn_info return (conn_info[1] * 1024)
null
null
null
What does this function do?
def to_md(journal): out = [] (year, month) = ((-1), (-1)) for e in journal.entries: if (not (e.date.year == year)): year = e.date.year out.append(str(year)) out.append(((u'=' * len(str(year))) + u'\n')) if (not (e.date.month == month)): month = e.date.month out.append(e.date.strftime(u'%B')) ou...
null
null
null
Returns a markdown representation of the Journal
pcsd
def to md journal out = [] year month = -1 -1 for e in journal entries if not e date year == year year = e date year out append str year out append u'=' * len str year + u' ' if not e date month == month month = e date month out append e date strftime u'%B' out append u'-' * len e date strftime u'%B' + u' ' out append ...
16240
def to_md(journal): out = [] (year, month) = ((-1), (-1)) for e in journal.entries: if (not (e.date.year == year)): year = e.date.year out.append(str(year)) out.append(((u'=' * len(str(year))) + u'\n')) if (not (e.date.month == month)): month = e.date.month out.append(e.date.strftime(u'%B')) ou...
Returns a markdown representation of the Journal
returns a markdown representation of the journal
Question: What does this function do? Code: def to_md(journal): out = [] (year, month) = ((-1), (-1)) for e in journal.entries: if (not (e.date.year == year)): year = e.date.year out.append(str(year)) out.append(((u'=' * len(str(year))) + u'\n')) if (not (e.date.month == month)): month = e.date.mo...
null
null
null
What does this function do?
def WriteCheckpointFile(net, t_op, best=False): ckpt_dir = os.path.join(t_op.checkpoint_prefix, t_op.checkpoint_directory) if (not os.path.isdir(ckpt_dir)): os.makedirs(ckpt_dir) if best: tag = 'BEST' checkpoint_file = ('%s_%s' % (net.name, tag)) checkpoint_file = os.path.join(ckpt_dir, checkpoint_file) pr...
null
null
null
Writes out the model to disk.
pcsd
def Write Checkpoint File net t op best=False ckpt dir = os path join t op checkpoint prefix t op checkpoint directory if not os path isdir ckpt dir os makedirs ckpt dir if best tag = 'BEST' checkpoint file = '%s %s' % net name tag checkpoint file = os path join ckpt dir checkpoint file print 'Writing current best mode...
16248
def WriteCheckpointFile(net, t_op, best=False): ckpt_dir = os.path.join(t_op.checkpoint_prefix, t_op.checkpoint_directory) if (not os.path.isdir(ckpt_dir)): os.makedirs(ckpt_dir) if best: tag = 'BEST' checkpoint_file = ('%s_%s' % (net.name, tag)) checkpoint_file = os.path.join(ckpt_dir, checkpoint_file) pr...
Writes out the model to disk.
writes out the model to disk .
Question: What does this function do? Code: def WriteCheckpointFile(net, t_op, best=False): ckpt_dir = os.path.join(t_op.checkpoint_prefix, t_op.checkpoint_directory) if (not os.path.isdir(ckpt_dir)): os.makedirs(ckpt_dir) if best: tag = 'BEST' checkpoint_file = ('%s_%s' % (net.name, tag)) checkpoint_file...
null
null
null
What does this function do?
def value_to_display(value, minmax=False): try: numeric_numpy_types = (int64, int32, float64, float32, complex128, complex64) if isinstance(value, recarray): fields = value.names display = ('Field names: ' + ', '.join(fields)) elif isinstance(value, MaskedArray): display = 'Masked array' elif isinstan...
null
null
null
Convert value for display purpose
pcsd
def value to display value minmax=False try numeric numpy types = int64 int32 float64 float32 complex128 complex64 if isinstance value recarray fields = value names display = 'Field names ' + ' ' join fields elif isinstance value Masked Array display = 'Masked array' elif isinstance value ndarray if minmax try display ...
16259
def value_to_display(value, minmax=False): try: numeric_numpy_types = (int64, int32, float64, float32, complex128, complex64) if isinstance(value, recarray): fields = value.names display = ('Field names: ' + ', '.join(fields)) elif isinstance(value, MaskedArray): display = 'Masked array' elif isinstan...
Convert value for display purpose
convert value for display purpose
Question: What does this function do? Code: def value_to_display(value, minmax=False): try: numeric_numpy_types = (int64, int32, float64, float32, complex128, complex64) if isinstance(value, recarray): fields = value.names display = ('Field names: ' + ', '.join(fields)) elif isinstance(value, MaskedArra...
null
null
null
What does this function do?
def inspect_error(): error('Internal Python error in the inspect module.\nBelow is the traceback from this internal error.\n')
null
null
null
Print a message about internal inspect errors. These are unfortunately quite common.
pcsd
def inspect error error 'Internal Python error in the inspect module Below is the traceback from this internal error '
16264
def inspect_error(): error('Internal Python error in the inspect module.\nBelow is the traceback from this internal error.\n')
Print a message about internal inspect errors. These are unfortunately quite common.
print a message about internal inspect errors .
Question: What does this function do? Code: def inspect_error(): error('Internal Python error in the inspect module.\nBelow is the traceback from this internal error.\n')
null
null
null
What does this function do?
def get_color_name(value): if (not is_known_type(value)): return CUSTOM_TYPE_COLOR for (typ, name) in list(COLORS.items()): if isinstance(value, typ): return name else: np_dtype = get_numpy_dtype(value) if ((np_dtype is None) or (not hasattr(value, 'size'))): return UNSUPPORTED_COLOR elif (value.size...
null
null
null
Return color name depending on value type
pcsd
def get color name value if not is known type value return CUSTOM TYPE COLOR for typ name in list COLORS items if isinstance value typ return name else np dtype = get numpy dtype value if np dtype is None or not hasattr value 'size' return UNSUPPORTED COLOR elif value size == 1 return SCALAR COLOR else return ARRAY COL...
16275
def get_color_name(value): if (not is_known_type(value)): return CUSTOM_TYPE_COLOR for (typ, name) in list(COLORS.items()): if isinstance(value, typ): return name else: np_dtype = get_numpy_dtype(value) if ((np_dtype is None) or (not hasattr(value, 'size'))): return UNSUPPORTED_COLOR elif (value.size...
Return color name depending on value type
return color name depending on value type
Question: What does this function do? Code: def get_color_name(value): if (not is_known_type(value)): return CUSTOM_TYPE_COLOR for (typ, name) in list(COLORS.items()): if isinstance(value, typ): return name else: np_dtype = get_numpy_dtype(value) if ((np_dtype is None) or (not hasattr(value, 'size'))):...
null
null
null
What does this function do?
def _handle_links(event): global tree tree = spanning_tree._calc_spanning_tree()
null
null
null
Handle discovery link events to update the spanning tree
pcsd
def handle links event global tree tree = spanning tree calc spanning tree
16278
def _handle_links(event): global tree tree = spanning_tree._calc_spanning_tree()
Handle discovery link events to update the spanning tree
handle discovery link events to update the spanning tree
Question: What does this function do? Code: def _handle_links(event): global tree tree = spanning_tree._calc_spanning_tree()
null
null
null
What does this function do?
def close_logger(): for handler in _logger.handlers: _logger.removeHandler(handler) if isinstance(handler, logging.FileHandler): handler.close()
null
null
null
Closes the logger handler for the file, so we can remove the file after a test.
pcsd
def close logger for handler in logger handlers logger remove Handler handler if isinstance handler logging File Handler handler close
16294
def close_logger(): for handler in _logger.handlers: _logger.removeHandler(handler) if isinstance(handler, logging.FileHandler): handler.close()
Closes the logger handler for the file, so we can remove the file after a test.
closes the logger handler for the file , so we can remove the file after a test .
Question: What does this function do? Code: def close_logger(): for handler in _logger.handlers: _logger.removeHandler(handler) if isinstance(handler, logging.FileHandler): handler.close()
null
null
null
What does this function do?
def DeleteArtifactsFromDatastore(artifact_names, reload_artifacts=True, token=None): artifacts = sorted(REGISTRY.GetArtifacts(reload_datastore_artifacts=reload_artifacts)) to_delete = set(artifact_names) deps = set() for artifact_obj in artifacts: if (artifact_obj.name in to_delete): continue if (artifact_ob...
null
null
null
Deletes a list of artifacts from the data store.
pcsd
def Delete Artifacts From Datastore artifact names reload artifacts=True token=None artifacts = sorted REGISTRY Get Artifacts reload datastore artifacts=reload artifacts to delete = set artifact names deps = set for artifact obj in artifacts if artifact obj name in to delete continue if artifact obj Get Artifact Depend...
16305
def DeleteArtifactsFromDatastore(artifact_names, reload_artifacts=True, token=None): artifacts = sorted(REGISTRY.GetArtifacts(reload_datastore_artifacts=reload_artifacts)) to_delete = set(artifact_names) deps = set() for artifact_obj in artifacts: if (artifact_obj.name in to_delete): continue if (artifact_ob...
Deletes a list of artifacts from the data store.
deletes a list of artifacts from the data store .
Question: What does this function do? Code: def DeleteArtifactsFromDatastore(artifact_names, reload_artifacts=True, token=None): artifacts = sorted(REGISTRY.GetArtifacts(reload_datastore_artifacts=reload_artifacts)) to_delete = set(artifact_names) deps = set() for artifact_obj in artifacts: if (artifact_obj.na...
null
null
null
What does this function do?
def resource_data_get_by_key(context, resource_id, key): result = context.session.query(models.ResourceData).filter_by(resource_id=resource_id).filter_by(key=key).first() if (not result): raise exception.NotFound(_('No resource data found')) return result
null
null
null
Looks up resource_data by resource_id and key. Does not decrypt resource_data.
pcsd
def resource data get by key context resource id key result = context session query models Resource Data filter by resource id=resource id filter by key=key first if not result raise exception Not Found 'No resource data found' return result
16308
def resource_data_get_by_key(context, resource_id, key): result = context.session.query(models.ResourceData).filter_by(resource_id=resource_id).filter_by(key=key).first() if (not result): raise exception.NotFound(_('No resource data found')) return result
Looks up resource_data by resource_id and key. Does not decrypt resource_data.
looks up resource _ data by resource _ id and key .
Question: What does this function do? Code: def resource_data_get_by_key(context, resource_id, key): result = context.session.query(models.ResourceData).filter_by(resource_id=resource_id).filter_by(key=key).first() if (not result): raise exception.NotFound(_('No resource data found')) return result
null
null
null
What does this function do?
@content_type('multipart/form-data') def multipart(body, **header_params): if (header_params and ('boundary' in header_params)): if (type(header_params['boundary']) is str): header_params['boundary'] = header_params['boundary'].encode() form = parse_multipart((body.stream if hasattr(body, 'stream') else body), h...
null
null
null
Converts multipart form data into native Python objects
pcsd
@content type 'multipart/form-data' def multipart body **header params if header params and 'boundary' in header params if type header params['boundary'] is str header params['boundary'] = header params['boundary'] encode form = parse multipart body stream if hasattr body 'stream' else body header params for key value ...
16313
@content_type('multipart/form-data') def multipart(body, **header_params): if (header_params and ('boundary' in header_params)): if (type(header_params['boundary']) is str): header_params['boundary'] = header_params['boundary'].encode() form = parse_multipart((body.stream if hasattr(body, 'stream') else body), h...
Converts multipart form data into native Python objects
converts multipart form data into native python objects
Question: What does this function do? Code: @content_type('multipart/form-data') def multipart(body, **header_params): if (header_params and ('boundary' in header_params)): if (type(header_params['boundary']) is str): header_params['boundary'] = header_params['boundary'].encode() form = parse_multipart((body....
null
null
null
What does this function do?
def get_directory_handle(path): return CreateFileW(path, FILE_LIST_DIRECTORY, WATCHDOG_FILE_SHARE_FLAGS, None, OPEN_EXISTING, WATCHDOG_FILE_FLAGS, None)
null
null
null
Returns a Windows handle to the specified directory path.
pcsd
def get directory handle path return Create File W path FILE LIST DIRECTORY WATCHDOG FILE SHARE FLAGS None OPEN EXISTING WATCHDOG FILE FLAGS None
16315
def get_directory_handle(path): return CreateFileW(path, FILE_LIST_DIRECTORY, WATCHDOG_FILE_SHARE_FLAGS, None, OPEN_EXISTING, WATCHDOG_FILE_FLAGS, None)
Returns a Windows handle to the specified directory path.
returns a windows handle to the specified directory path .
Question: What does this function do? Code: def get_directory_handle(path): return CreateFileW(path, FILE_LIST_DIRECTORY, WATCHDOG_FILE_SHARE_FLAGS, None, OPEN_EXISTING, WATCHDOG_FILE_FLAGS, None)
null
null
null
What does this function do?
@must_be_logged_in def owncloud_add_user_account(auth, **kwargs): host_url = request.json.get('host') host = furl() host.host = host_url.rstrip('/').replace('https://', '').replace('http://', '') host.scheme = 'https' username = request.json.get('username') password = request.json.get('password') try: oc = own...
null
null
null
Verifies new external account credentials and adds to user\'s list This view expects `host`, `username` and `password` fields in the JSON body of the request.
pcsd
@must be logged in def owncloud add user account auth **kwargs host url = request json get 'host' host = furl host host = host url rstrip '/' replace 'https //' '' replace 'http //' '' host scheme = 'https' username = request json get 'username' password = request json get 'password' try oc = owncloud Client host url v...
16321
@must_be_logged_in def owncloud_add_user_account(auth, **kwargs): host_url = request.json.get('host') host = furl() host.host = host_url.rstrip('/').replace('https://', '').replace('http://', '') host.scheme = 'https' username = request.json.get('username') password = request.json.get('password') try: oc = own...
Verifies new external account credentials and adds to user\'s list This view expects `host`, `username` and `password` fields in the JSON body of the request.
verifies new external account credentials and adds to users list
Question: What does this function do? Code: @must_be_logged_in def owncloud_add_user_account(auth, **kwargs): host_url = request.json.get('host') host = furl() host.host = host_url.rstrip('/').replace('https://', '').replace('http://', '') host.scheme = 'https' username = request.json.get('username') password ...
null
null
null
What does this function do?
def _check_channel_names(inst, ref_names): if isinstance(ref_names, str): ref_names = [ref_names] ref_idx = pick_channels(inst.info['ch_names'], ref_names) assert_true(len(ref_idx), len(ref_names)) inst.info._check_consistency()
null
null
null
Check channel names.
pcsd
def check channel names inst ref names if isinstance ref names str ref names = [ref names] ref idx = pick channels inst info['ch names'] ref names assert true len ref idx len ref names inst info check consistency
16326
def _check_channel_names(inst, ref_names): if isinstance(ref_names, str): ref_names = [ref_names] ref_idx = pick_channels(inst.info['ch_names'], ref_names) assert_true(len(ref_idx), len(ref_names)) inst.info._check_consistency()
Check channel names.
check channel names .
Question: What does this function do? Code: def _check_channel_names(inst, ref_names): if isinstance(ref_names, str): ref_names = [ref_names] ref_idx = pick_channels(inst.info['ch_names'], ref_names) assert_true(len(ref_idx), len(ref_names)) inst.info._check_consistency()
null
null
null
What does this function do?
def _add_role_and_annotate(var, role, annotations=()): add_role(var, role) for annotation in annotations: add_annotation(var, annotation)
null
null
null
Add a role and zero or more annotations to a variable.
pcsd
def add role and annotate var role annotations= add role var role for annotation in annotations add annotation var annotation
16350
def _add_role_and_annotate(var, role, annotations=()): add_role(var, role) for annotation in annotations: add_annotation(var, annotation)
Add a role and zero or more annotations to a variable.
add a role and zero or more annotations to a variable .
Question: What does this function do? Code: def _add_role_and_annotate(var, role, annotations=()): add_role(var, role) for annotation in annotations: add_annotation(var, annotation)
null
null
null
What does this function do?
def sign_seq(poly_seq, x): return [sign(LC(poly_seq[i], x)) for i in range(len(poly_seq))]
null
null
null
Given a sequence of polynomials poly_seq, it returns the sequence of signs of the leading coefficients of the polynomials in poly_seq.
pcsd
def sign seq poly seq x return [sign LC poly seq[i] x for i in range len poly seq ]
16351
def sign_seq(poly_seq, x): return [sign(LC(poly_seq[i], x)) for i in range(len(poly_seq))]
Given a sequence of polynomials poly_seq, it returns the sequence of signs of the leading coefficients of the polynomials in poly_seq.
given a sequence of polynomials poly _ seq , it returns the sequence of signs of the leading coefficients of the polynomials in poly _ seq .
Question: What does this function do? Code: def sign_seq(poly_seq, x): return [sign(LC(poly_seq[i], x)) for i in range(len(poly_seq))]
null
null
null
What does this function do?
def CheckForCopyright(filename, lines, error): for line in range(1, min(len(lines), 11)): if re.search('Copyright', lines[line], re.I): break else: error(filename, 0, 'legal/copyright', 5, 'No copyright message found. You should have a line: "Copyright [year] <Copyright Owner>"')
null
null
null
Logs an error if no Copyright message appears at the top of the file.
pcsd
def Check For Copyright filename lines error for line in range 1 min len lines 11 if re search 'Copyright' lines[line] re I break else error filename 0 'legal/copyright' 5 'No copyright message found You should have a line "Copyright [year] <Copyright Owner>"'
16353
def CheckForCopyright(filename, lines, error): for line in range(1, min(len(lines), 11)): if re.search('Copyright', lines[line], re.I): break else: error(filename, 0, 'legal/copyright', 5, 'No copyright message found. You should have a line: "Copyright [year] <Copyright Owner>"')
Logs an error if no Copyright message appears at the top of the file.
logs an error if no copyright message appears at the top of the file .
Question: What does this function do? Code: def CheckForCopyright(filename, lines, error): for line in range(1, min(len(lines), 11)): if re.search('Copyright', lines[line], re.I): break else: error(filename, 0, 'legal/copyright', 5, 'No copyright message found. You should have a line: "Copyright [year] <Co...
null
null
null
What does this function do?
def skill_provision(): mode = session.s3.hrm.mode def prep(r): if (mode is not None): auth.permission.fail() return True s3.prep = prep output = s3_rest_controller() return output
null
null
null
Skill Provisions Controller
pcsd
def skill provision mode = session s3 hrm mode def prep r if mode is not None auth permission fail return True s3 prep = prep output = s3 rest controller return output
16354
def skill_provision(): mode = session.s3.hrm.mode def prep(r): if (mode is not None): auth.permission.fail() return True s3.prep = prep output = s3_rest_controller() return output
Skill Provisions Controller
skill provisions controller
Question: What does this function do? Code: def skill_provision(): mode = session.s3.hrm.mode def prep(r): if (mode is not None): auth.permission.fail() return True s3.prep = prep output = s3_rest_controller() return output
null
null
null
What does this function do?
def diagnose(data): print ('Diagnostic running on Beautiful Soup %s' % __version__) print ('Python version %s' % sys.version) basic_parsers = ['html.parser', 'html5lib', 'lxml'] for name in basic_parsers: for builder in builder_registry.builders: if (name in builder.features): break else: basic_parser...
null
null
null
Diagnostic suite for isolating common problems.
pcsd
def diagnose data print 'Diagnostic running on Beautiful Soup %s' % version print 'Python version %s' % sys version basic parsers = ['html parser' 'html5lib' 'lxml'] for name in basic parsers for builder in builder registry builders if name in builder features break else basic parsers remove name print 'I noticed that ...
16357
def diagnose(data): print ('Diagnostic running on Beautiful Soup %s' % __version__) print ('Python version %s' % sys.version) basic_parsers = ['html.parser', 'html5lib', 'lxml'] for name in basic_parsers: for builder in builder_registry.builders: if (name in builder.features): break else: basic_parser...
Diagnostic suite for isolating common problems.
diagnostic suite for isolating common problems .
Question: What does this function do? Code: def diagnose(data): print ('Diagnostic running on Beautiful Soup %s' % __version__) print ('Python version %s' % sys.version) basic_parsers = ['html.parser', 'html5lib', 'lxml'] for name in basic_parsers: for builder in builder_registry.builders: if (name in build...
null
null
null
What does this function do?
def _normalize_handler_method(method): return method.lower().replace('-', '_')
null
null
null
Transforms an HTTP method into a valid Python identifier.
pcsd
def normalize handler method method return method lower replace '-' ' '
16358
def _normalize_handler_method(method): return method.lower().replace('-', '_')
Transforms an HTTP method into a valid Python identifier.
transforms an http method into a valid python identifier .
Question: What does this function do? Code: def _normalize_handler_method(method): return method.lower().replace('-', '_')
null
null
null
What does this function do?
def getLoopsDifference(importRadius, loopLists): negativeLoops = getLoopsUnified(importRadius, loopLists[1:]) intercircle.directLoops(False, negativeLoops) positiveLoops = loopLists[0] intercircle.directLoops(True, positiveLoops) radiusSide = (0.01 * importRadius) corners = getLoopsListsIntersections(loopLists) ...
null
null
null
Get difference loops.
pcsd
def get Loops Difference import Radius loop Lists negative Loops = get Loops Unified import Radius loop Lists[1 ] intercircle direct Loops False negative Loops positive Loops = loop Lists[0] intercircle direct Loops True positive Loops radius Side = 0 01 * import Radius corners = get Loops Lists Intersections loop List...
16359
def getLoopsDifference(importRadius, loopLists): negativeLoops = getLoopsUnified(importRadius, loopLists[1:]) intercircle.directLoops(False, negativeLoops) positiveLoops = loopLists[0] intercircle.directLoops(True, positiveLoops) radiusSide = (0.01 * importRadius) corners = getLoopsListsIntersections(loopLists) ...
Get difference loops.
get difference loops .
Question: What does this function do? Code: def getLoopsDifference(importRadius, loopLists): negativeLoops = getLoopsUnified(importRadius, loopLists[1:]) intercircle.directLoops(False, negativeLoops) positiveLoops = loopLists[0] intercircle.directLoops(True, positiveLoops) radiusSide = (0.01 * importRadius) co...
null
null
null
What does this function do?
@require_POST @login_required def request_course_creator(request): user_requested_access(request.user) return JsonResponse({'Status': 'OK'})
null
null
null
User has requested course creation access.
pcsd
@require POST @login required def request course creator request user requested access request user return Json Response {'Status' 'OK'}
16360
@require_POST @login_required def request_course_creator(request): user_requested_access(request.user) return JsonResponse({'Status': 'OK'})
User has requested course creation access.
user has requested course creation access .
Question: What does this function do? Code: @require_POST @login_required def request_course_creator(request): user_requested_access(request.user) return JsonResponse({'Status': 'OK'})
null
null
null
What does this function do?
def border_crossing(): return s3_rest_controller(rheader=s3db.transport_rheader)
null
null
null
RESTful CRUD controller
pcsd
def border crossing return s3 rest controller rheader=s3db transport rheader
16364
def border_crossing(): return s3_rest_controller(rheader=s3db.transport_rheader)
RESTful CRUD controller
restful crud controller
Question: What does this function do? Code: def border_crossing(): return s3_rest_controller(rheader=s3db.transport_rheader)
null
null
null
What does this function do?
@log_call def task_update(context, task_id, values): global DATA task_values = copy.deepcopy(values) task_info_values = _pop_task_info_values(task_values) try: task = DATA['tasks'][task_id] except KeyError: LOG.debug('No task found with ID %s', task_id) raise exception.TaskNotFound(task_id=task_id) task.upd...
null
null
null
Update a task object
pcsd
@log call def task update context task id values global DATA task values = copy deepcopy values task info values = pop task info values task values try task = DATA['tasks'][task id] except Key Error LOG debug 'No task found with ID %s' task id raise exception Task Not Found task id=task id task update task values task[...
16374
@log_call def task_update(context, task_id, values): global DATA task_values = copy.deepcopy(values) task_info_values = _pop_task_info_values(task_values) try: task = DATA['tasks'][task_id] except KeyError: LOG.debug('No task found with ID %s', task_id) raise exception.TaskNotFound(task_id=task_id) task.upd...
Update a task object
update a task object
Question: What does this function do? Code: @log_call def task_update(context, task_id, values): global DATA task_values = copy.deepcopy(values) task_info_values = _pop_task_info_values(task_values) try: task = DATA['tasks'][task_id] except KeyError: LOG.debug('No task found with ID %s', task_id) raise ex...
null
null
null
What does this function do?
def p_statement(t): print t[1]
null
null
null
statement : expression
pcsd
def p statement t print t[1]
16379
def p_statement(t): print t[1]
statement : expression
statement : expression
Question: What does this function do? Code: def p_statement(t): print t[1]
null
null
null
What does this function do?
@library.global_function def url(viewname, *args, **kwargs): return reverse(viewname, args=args, kwargs=kwargs)
null
null
null
Helper for Django\'s ``reverse`` in templates.
pcsd
@library global function def url viewname *args **kwargs return reverse viewname args=args kwargs=kwargs
16383
@library.global_function def url(viewname, *args, **kwargs): return reverse(viewname, args=args, kwargs=kwargs)
Helper for Django\'s ``reverse`` in templates.
helper for djangos reverse in templates .
Question: What does this function do? Code: @library.global_function def url(viewname, *args, **kwargs): return reverse(viewname, args=args, kwargs=kwargs)
null
null
null
What does this function do?
def run_script(dist_spec, script_name): ns = sys._getframe(1).f_globals name = ns['__name__'] ns.clear() ns['__name__'] = name require(dist_spec)[0].run_script(script_name, ns)
null
null
null
Locate distribution `dist_spec` and run its `script_name` script
pcsd
def run script dist spec script name ns = sys getframe 1 f globals name = ns[' name '] ns clear ns[' name '] = name require dist spec [0] run script script name ns
16384
def run_script(dist_spec, script_name): ns = sys._getframe(1).f_globals name = ns['__name__'] ns.clear() ns['__name__'] = name require(dist_spec)[0].run_script(script_name, ns)
Locate distribution `dist_spec` and run its `script_name` script
locate distribution dist _ spec and run its script _ name script
Question: What does this function do? Code: def run_script(dist_spec, script_name): ns = sys._getframe(1).f_globals name = ns['__name__'] ns.clear() ns['__name__'] = name require(dist_spec)[0].run_script(script_name, ns)
null
null
null
What does this function do?
def is_hashable(obj): try: hash(obj) except TypeError: return False return True
null
null
null
Returns true if *obj* can be hashed
pcsd
def is hashable obj try hash obj except Type Error return False return True
16386
def is_hashable(obj): try: hash(obj) except TypeError: return False return True
Returns true if *obj* can be hashed
returns true if * obj * can be hashed
Question: What does this function do? Code: def is_hashable(obj): try: hash(obj) except TypeError: return False return True
null
null
null
What does this function do?
def _validate_constraints(supported_constraints, model): message = u'Optimizer cannot handle {0} constraints.' if (any(six.itervalues(model.fixed)) and (u'fixed' not in supported_constraints)): raise UnsupportedConstraintError(message.format(u'fixed parameter')) if (any(six.itervalues(model.tied)) and (u'tied' not...
null
null
null
Make sure model constraints are supported by the current fitter.
pcsd
def validate constraints supported constraints model message = u'Optimizer cannot handle {0} constraints ' if any six itervalues model fixed and u'fixed' not in supported constraints raise Unsupported Constraint Error message format u'fixed parameter' if any six itervalues model tied and u'tied' not in supported constr...
16388
def _validate_constraints(supported_constraints, model): message = u'Optimizer cannot handle {0} constraints.' if (any(six.itervalues(model.fixed)) and (u'fixed' not in supported_constraints)): raise UnsupportedConstraintError(message.format(u'fixed parameter')) if (any(six.itervalues(model.tied)) and (u'tied' not...
Make sure model constraints are supported by the current fitter.
make sure model constraints are supported by the current fitter .
Question: What does this function do? Code: def _validate_constraints(supported_constraints, model): message = u'Optimizer cannot handle {0} constraints.' if (any(six.itervalues(model.fixed)) and (u'fixed' not in supported_constraints)): raise UnsupportedConstraintError(message.format(u'fixed parameter')) if (a...