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
When does the code compute the homogeneity and completeness and v - measure scores ?
def homogeneity_completeness_v_measure(labels_true, labels_pred): (labels_true, labels_pred) = check_clusterings(labels_true, labels_pred) if (len(labels_true) == 0): return (1.0, 1.0, 1.0) entropy_C = entropy(labels_true) entropy_K = entropy(labels_pred) contingency = contingency_matrix(labels_true, labels_pred, sparse=True) MI = mutual_info_score(None, None, contingency=contingency) homogeneity = ((MI / entropy_C) if entropy_C else 1.0) completeness = ((MI / entropy_K) if entropy_K else 1.0) if ((homogeneity + completeness) == 0.0): v_measure_score = 0.0 else: v_measure_score = (((2.0 * homogeneity) * completeness) / (homogeneity + completeness)) return (homogeneity, completeness, v_measure_score)
null
null
null
at once
codeqa
def homogeneity completeness v measure labels true labels pred labels true labels pred check clusterings labels true labels pred if len labels true 0 return 1 0 1 0 1 0 entropy C entropy labels true entropy K entropy labels pred contingency contingency matrix labels true labels pred sparse True MI mutual info score None None contingency contingency homogeneity MI / entropy C if entropy C else 1 0 completeness MI / entropy K if entropy K else 1 0 if homogeneity + completeness 0 0 v measure score 0 0else v measure score 2 0 * homogeneity * completeness / homogeneity + completeness return homogeneity completeness v measure score
null
null
null
null
Question: When does the code compute the homogeneity and completeness and v - measure scores ? Code: def homogeneity_completeness_v_measure(labels_true, labels_pred): (labels_true, labels_pred) = check_clusterings(labels_true, labels_pred) if (len(labels_true) == 0): return (1.0, 1.0, 1.0) entropy_C = entropy(labels_true) entropy_K = entropy(labels_pred) contingency = contingency_matrix(labels_true, labels_pred, sparse=True) MI = mutual_info_score(None, None, contingency=contingency) homogeneity = ((MI / entropy_C) if entropy_C else 1.0) completeness = ((MI / entropy_K) if entropy_K else 1.0) if ((homogeneity + completeness) == 0.0): v_measure_score = 0.0 else: v_measure_score = (((2.0 * homogeneity) * completeness) / (homogeneity + completeness)) return (homogeneity, completeness, v_measure_score)
null
null
null
What does the code compute at once ?
def homogeneity_completeness_v_measure(labels_true, labels_pred): (labels_true, labels_pred) = check_clusterings(labels_true, labels_pred) if (len(labels_true) == 0): return (1.0, 1.0, 1.0) entropy_C = entropy(labels_true) entropy_K = entropy(labels_pred) contingency = contingency_matrix(labels_true, labels_pred, sparse=True) MI = mutual_info_score(None, None, contingency=contingency) homogeneity = ((MI / entropy_C) if entropy_C else 1.0) completeness = ((MI / entropy_K) if entropy_K else 1.0) if ((homogeneity + completeness) == 0.0): v_measure_score = 0.0 else: v_measure_score = (((2.0 * homogeneity) * completeness) / (homogeneity + completeness)) return (homogeneity, completeness, v_measure_score)
null
null
null
the homogeneity and completeness and v - measure scores
codeqa
def homogeneity completeness v measure labels true labels pred labels true labels pred check clusterings labels true labels pred if len labels true 0 return 1 0 1 0 1 0 entropy C entropy labels true entropy K entropy labels pred contingency contingency matrix labels true labels pred sparse True MI mutual info score None None contingency contingency homogeneity MI / entropy C if entropy C else 1 0 completeness MI / entropy K if entropy K else 1 0 if homogeneity + completeness 0 0 v measure score 0 0else v measure score 2 0 * homogeneity * completeness / homogeneity + completeness return homogeneity completeness v measure score
null
null
null
null
Question: What does the code compute at once ? Code: def homogeneity_completeness_v_measure(labels_true, labels_pred): (labels_true, labels_pred) = check_clusterings(labels_true, labels_pred) if (len(labels_true) == 0): return (1.0, 1.0, 1.0) entropy_C = entropy(labels_true) entropy_K = entropy(labels_pred) contingency = contingency_matrix(labels_true, labels_pred, sparse=True) MI = mutual_info_score(None, None, contingency=contingency) homogeneity = ((MI / entropy_C) if entropy_C else 1.0) completeness = ((MI / entropy_K) if entropy_K else 1.0) if ((homogeneity + completeness) == 0.0): v_measure_score = 0.0 else: v_measure_score = (((2.0 * homogeneity) * completeness) / (homogeneity + completeness)) return (homogeneity, completeness, v_measure_score)
null
null
null
When did predictions compute ?
def _parallel_predict_proba(estimators, estimators_features, X, n_classes): n_samples = X.shape[0] proba = np.zeros((n_samples, n_classes)) for (estimator, features) in zip(estimators, estimators_features): if hasattr(estimator, 'predict_proba'): proba_estimator = estimator.predict_proba(X[:, features]) if (n_classes == len(estimator.classes_)): proba += proba_estimator else: proba[:, estimator.classes_] += proba_estimator[:, range(len(estimator.classes_))] else: predictions = estimator.predict(X[:, features]) for i in range(n_samples): proba[(i, predictions[i])] += 1 return proba
null
null
null
within a job
codeqa
def parallel predict proba estimators estimators features X n classes n samples X shape[ 0 ]proba np zeros n samples n classes for estimator features in zip estimators estimators features if hasattr estimator 'predict proba' proba estimator estimator predict proba X[ features] if n classes len estimator classes proba + proba estimatorelse proba[ estimator classes ] + proba estimator[ range len estimator classes ]else predictions estimator predict X[ features] for i in range n samples proba[ i predictions[i] ] + 1return proba
null
null
null
null
Question: When did predictions compute ? Code: def _parallel_predict_proba(estimators, estimators_features, X, n_classes): n_samples = X.shape[0] proba = np.zeros((n_samples, n_classes)) for (estimator, features) in zip(estimators, estimators_features): if hasattr(estimator, 'predict_proba'): proba_estimator = estimator.predict_proba(X[:, features]) if (n_classes == len(estimator.classes_)): proba += proba_estimator else: proba[:, estimator.classes_] += proba_estimator[:, range(len(estimator.classes_))] else: predictions = estimator.predict(X[:, features]) for i in range(n_samples): proba[(i, predictions[i])] += 1 return proba
null
null
null
What used to compute predictions within a job ?
def _parallel_predict_proba(estimators, estimators_features, X, n_classes): n_samples = X.shape[0] proba = np.zeros((n_samples, n_classes)) for (estimator, features) in zip(estimators, estimators_features): if hasattr(estimator, 'predict_proba'): proba_estimator = estimator.predict_proba(X[:, features]) if (n_classes == len(estimator.classes_)): proba += proba_estimator else: proba[:, estimator.classes_] += proba_estimator[:, range(len(estimator.classes_))] else: predictions = estimator.predict(X[:, features]) for i in range(n_samples): proba[(i, predictions[i])] += 1 return proba
null
null
null
private function
codeqa
def parallel predict proba estimators estimators features X n classes n samples X shape[ 0 ]proba np zeros n samples n classes for estimator features in zip estimators estimators features if hasattr estimator 'predict proba' proba estimator estimator predict proba X[ features] if n classes len estimator classes proba + proba estimatorelse proba[ estimator classes ] + proba estimator[ range len estimator classes ]else predictions estimator predict X[ features] for i in range n samples proba[ i predictions[i] ] + 1return proba
null
null
null
null
Question: What used to compute predictions within a job ? Code: def _parallel_predict_proba(estimators, estimators_features, X, n_classes): n_samples = X.shape[0] proba = np.zeros((n_samples, n_classes)) for (estimator, features) in zip(estimators, estimators_features): if hasattr(estimator, 'predict_proba'): proba_estimator = estimator.predict_proba(X[:, features]) if (n_classes == len(estimator.classes_)): proba += proba_estimator else: proba[:, estimator.classes_] += proba_estimator[:, range(len(estimator.classes_))] else: predictions = estimator.predict(X[:, features]) for i in range(n_samples): proba[(i, predictions[i])] += 1 return proba
null
null
null
What did private function use ?
def _parallel_predict_proba(estimators, estimators_features, X, n_classes): n_samples = X.shape[0] proba = np.zeros((n_samples, n_classes)) for (estimator, features) in zip(estimators, estimators_features): if hasattr(estimator, 'predict_proba'): proba_estimator = estimator.predict_proba(X[:, features]) if (n_classes == len(estimator.classes_)): proba += proba_estimator else: proba[:, estimator.classes_] += proba_estimator[:, range(len(estimator.classes_))] else: predictions = estimator.predict(X[:, features]) for i in range(n_samples): proba[(i, predictions[i])] += 1 return proba
null
null
null
to compute predictions within a job
codeqa
def parallel predict proba estimators estimators features X n classes n samples X shape[ 0 ]proba np zeros n samples n classes for estimator features in zip estimators estimators features if hasattr estimator 'predict proba' proba estimator estimator predict proba X[ features] if n classes len estimator classes proba + proba estimatorelse proba[ estimator classes ] + proba estimator[ range len estimator classes ]else predictions estimator predict X[ features] for i in range n samples proba[ i predictions[i] ] + 1return proba
null
null
null
null
Question: What did private function use ? Code: def _parallel_predict_proba(estimators, estimators_features, X, n_classes): n_samples = X.shape[0] proba = np.zeros((n_samples, n_classes)) for (estimator, features) in zip(estimators, estimators_features): if hasattr(estimator, 'predict_proba'): proba_estimator = estimator.predict_proba(X[:, features]) if (n_classes == len(estimator.classes_)): proba += proba_estimator else: proba[:, estimator.classes_] += proba_estimator[:, range(len(estimator.classes_))] else: predictions = estimator.predict(X[:, features]) for i in range(n_samples): proba[(i, predictions[i])] += 1 return proba
null
null
null
How does the code redact a string ?
def redact(string): return global_redaction_engine.redact(string)
null
null
null
using the global redaction engine
codeqa
def redact string return global redaction engine redact string
null
null
null
null
Question: How does the code redact a string ? Code: def redact(string): return global_redaction_engine.redact(string)
null
null
null
What does the code redact using the global redaction engine ?
def redact(string): return global_redaction_engine.redact(string)
null
null
null
a string
codeqa
def redact string return global redaction engine redact string
null
null
null
null
Question: What does the code redact using the global redaction engine ? Code: def redact(string): return global_redaction_engine.redact(string)
null
null
null
What does the code get ?
def _get_ecg_channel_index(ch_name, inst): if (ch_name is None): ecg_idx = pick_types(inst.info, meg=False, eeg=False, stim=False, eog=False, ecg=True, emg=False, ref_meg=False, exclude='bads') else: if (ch_name not in inst.ch_names): raise ValueError(('%s not in channel list (%s)' % (ch_name, inst.ch_names))) ecg_idx = pick_channels(inst.ch_names, include=[ch_name]) if (len(ecg_idx) == 0): return None if (len(ecg_idx) > 1): warn(('More than one ECG channel found. Using only %s.' % inst.ch_names[ecg_idx[0]])) return ecg_idx[0]
null
null
null
ecg channel index
codeqa
def get ecg channel index ch name inst if ch name is None ecg idx pick types inst info meg False eeg False stim False eog False ecg True emg False ref meg False exclude 'bads' else if ch name not in inst ch names raise Value Error '%snotinchannellist %s ' % ch name inst ch names ecg idx pick channels inst ch names include [ch name] if len ecg idx 0 return Noneif len ecg idx > 1 warn ' Morethanone EC Gchannelfound Usingonly%s ' % inst ch names[ecg idx[ 0 ]] return ecg idx[ 0 ]
null
null
null
null
Question: What does the code get ? Code: def _get_ecg_channel_index(ch_name, inst): if (ch_name is None): ecg_idx = pick_types(inst.info, meg=False, eeg=False, stim=False, eog=False, ecg=True, emg=False, ref_meg=False, exclude='bads') else: if (ch_name not in inst.ch_names): raise ValueError(('%s not in channel list (%s)' % (ch_name, inst.ch_names))) ecg_idx = pick_channels(inst.ch_names, include=[ch_name]) if (len(ecg_idx) == 0): return None if (len(ecg_idx) > 1): warn(('More than one ECG channel found. Using only %s.' % inst.ch_names[ecg_idx[0]])) return ecg_idx[0]
null
null
null
For what purpose does google query ?
def g(phenny, input): query = input.group(2) if (not query): return phenny.reply('.g what?') query = query.encode('utf-8') uri = google_search(query) if uri: phenny.reply(uri) if (not hasattr(phenny.bot, 'last_seen_uri')): phenny.bot.last_seen_uri = {} phenny.bot.last_seen_uri[input.sender] = uri elif (uri is False): phenny.reply('Problem getting data from Google.') else: phenny.reply(("No results found for '%s'." % query))
null
null
null
for the specified input
codeqa
def g phenny input query input group 2 if not query return phenny reply ' gwhat?' query query encode 'utf- 8 ' uri google search query if uri phenny reply uri if not hasattr phenny bot 'last seen uri' phenny bot last seen uri {}phenny bot last seen uri[input sender] urielif uri is False phenny reply ' Problemgettingdatafrom Google ' else phenny reply " Noresultsfoundfor'%s' " % query
null
null
null
null
Question: For what purpose does google query ? Code: def g(phenny, input): query = input.group(2) if (not query): return phenny.reply('.g what?') query = query.encode('utf-8') uri = google_search(query) if uri: phenny.reply(uri) if (not hasattr(phenny.bot, 'last_seen_uri')): phenny.bot.last_seen_uri = {} phenny.bot.last_seen_uri[input.sender] = uri elif (uri is False): phenny.reply('Problem getting data from Google.') else: phenny.reply(("No results found for '%s'." % query))
null
null
null
Where did a higher order function implement ?
def get_course_in_cache(course_key): return get_block_structure_manager(course_key).get_collected()
null
null
null
on top of the block_structure
codeqa
def get course in cache course key return get block structure manager course key get collected
null
null
null
null
Question: Where did a higher order function implement ? Code: def get_course_in_cache(course_key): return get_block_structure_manager(course_key).get_collected()
null
null
null
What implemented on top of the block_structure ?
def get_course_in_cache(course_key): return get_block_structure_manager(course_key).get_collected()
null
null
null
a higher order function
codeqa
def get course in cache course key return get block structure manager course key get collected
null
null
null
null
Question: What implemented on top of the block_structure ? Code: def get_course_in_cache(course_key): return get_block_structure_manager(course_key).get_collected()
null
null
null
How does this method remove illegal characters from a dictionary ?
def fix_unicode_dict(d): new_dict = {} for (key, value) in d.items(): if isinstance(value, dict): new_dict[key] = fix_unicode_dict(value) elif isinstance(value, tuple): new_dict[key] = fix_unicode_array(list(value)) elif isinstance(value, list): new_dict[key] = fix_unicode_array(value) elif isinstance(value, (str, unicode)): new_dict[key] = value.decode('utf-8', 'ignore') else: new_dict[key] = value return new_dict
null
null
null
recursively
codeqa
def fix unicode dict d new dict {}for key value in d items if isinstance value dict new dict[key] fix unicode dict value elif isinstance value tuple new dict[key] fix unicode array list value elif isinstance value list new dict[key] fix unicode array value elif isinstance value str unicode new dict[key] value decode 'utf- 8 ' 'ignore' else new dict[key] valuereturn new dict
null
null
null
null
Question: How does this method remove illegal characters from a dictionary ? Code: def fix_unicode_dict(d): new_dict = {} for (key, value) in d.items(): if isinstance(value, dict): new_dict[key] = fix_unicode_dict(value) elif isinstance(value, tuple): new_dict[key] = fix_unicode_array(list(value)) elif isinstance(value, list): new_dict[key] = fix_unicode_array(value) elif isinstance(value, (str, unicode)): new_dict[key] = value.decode('utf-8', 'ignore') else: new_dict[key] = value return new_dict
null
null
null
What does this method remove from a dictionary recursively ?
def fix_unicode_dict(d): new_dict = {} for (key, value) in d.items(): if isinstance(value, dict): new_dict[key] = fix_unicode_dict(value) elif isinstance(value, tuple): new_dict[key] = fix_unicode_array(list(value)) elif isinstance(value, list): new_dict[key] = fix_unicode_array(value) elif isinstance(value, (str, unicode)): new_dict[key] = value.decode('utf-8', 'ignore') else: new_dict[key] = value return new_dict
null
null
null
illegal characters
codeqa
def fix unicode dict d new dict {}for key value in d items if isinstance value dict new dict[key] fix unicode dict value elif isinstance value tuple new dict[key] fix unicode array list value elif isinstance value list new dict[key] fix unicode array value elif isinstance value str unicode new dict[key] value decode 'utf- 8 ' 'ignore' else new dict[key] valuereturn new dict
null
null
null
null
Question: What does this method remove from a dictionary recursively ? Code: def fix_unicode_dict(d): new_dict = {} for (key, value) in d.items(): if isinstance(value, dict): new_dict[key] = fix_unicode_dict(value) elif isinstance(value, tuple): new_dict[key] = fix_unicode_array(list(value)) elif isinstance(value, list): new_dict[key] = fix_unicode_array(value) elif isinstance(value, (str, unicode)): new_dict[key] = value.decode('utf-8', 'ignore') else: new_dict[key] = value return new_dict
null
null
null
What does the code build ?
def buildSimpleBorderSwipingNet(size=3, dim=3, hsize=1, predefined={}): dims = tuple(([size] * dim)) hdims = tuple((list(dims) + [(2 ** dim)])) inmod = LinearLayer((size ** dim), name='input') inmesh = ModuleMesh.viewOnFlatLayer(inmod, dims, 'inmesh') outmod = LinearLayer((size ** dim), name='output') outmesh = ModuleMesh.viewOnFlatLayer(outmod, dims, 'outmesh') hiddenmesh = ModuleMesh.constructWithLayers(TanhLayer, hsize, hdims, 'hidden') return BorderSwipingNetwork(inmesh, hiddenmesh, outmesh, predefined=predefined)
null
null
null
a simple swiping network
codeqa
def build Simple Border Swiping Net size 3 dim 3 hsize 1 predefined {} dims tuple [size] * dim hdims tuple list dims + [ 2 ** dim ] inmod Linear Layer size ** dim name 'input' inmesh Module Mesh view On Flat Layer inmod dims 'inmesh' outmod Linear Layer size ** dim name 'output' outmesh Module Mesh view On Flat Layer outmod dims 'outmesh' hiddenmesh Module Mesh construct With Layers Tanh Layer hsize hdims 'hidden' return Border Swiping Network inmesh hiddenmesh outmesh predefined predefined
null
null
null
null
Question: What does the code build ? Code: def buildSimpleBorderSwipingNet(size=3, dim=3, hsize=1, predefined={}): dims = tuple(([size] * dim)) hdims = tuple((list(dims) + [(2 ** dim)])) inmod = LinearLayer((size ** dim), name='input') inmesh = ModuleMesh.viewOnFlatLayer(inmod, dims, 'inmesh') outmod = LinearLayer((size ** dim), name='output') outmesh = ModuleMesh.viewOnFlatLayer(outmod, dims, 'outmesh') hiddenmesh = ModuleMesh.constructWithLayers(TanhLayer, hsize, hdims, 'hidden') return BorderSwipingNetwork(inmesh, hiddenmesh, outmesh, predefined=predefined)
null
null
null
What does the code get ?
def getNS(s, count=1): ns = [] c = 0 for i in range(count): (l,) = struct.unpack('!L', s[c:(c + 4)]) ns.append(s[(c + 4):((4 + l) + c)]) c += (4 + l) return (tuple(ns) + (s[c:],))
null
null
null
net string
codeqa
def get NS s count 1 ns []c 0for i in range count l struct unpack ' L' s[c c + 4 ] ns append s[ c + 4 4 + l + c ] c + 4 + l return tuple ns + s[c ]
null
null
null
null
Question: What does the code get ? Code: def getNS(s, count=1): ns = [] c = 0 for i in range(count): (l,) = struct.unpack('!L', s[c:(c + 4)]) ns.append(s[(c + 4):((4 + l) + c)]) c += (4 + l) return (tuple(ns) + (s[c:],))
null
null
null
Where does data strip ?
def strip_quoted_strings(string): return re.sub('\\"(.*)\\"', '', string)
null
null
null
in between double quotes
codeqa
def strip quoted strings string return re sub '\\" * \\"' '' string
null
null
null
null
Question: Where does data strip ? Code: def strip_quoted_strings(string): return re.sub('\\"(.*)\\"', '', string)
null
null
null
What strips in between double quotes ?
def strip_quoted_strings(string): return re.sub('\\"(.*)\\"', '', string)
null
null
null
data
codeqa
def strip quoted strings string return re sub '\\" * \\"' '' string
null
null
null
null
Question: What strips in between double quotes ? Code: def strip_quoted_strings(string): return re.sub('\\"(.*)\\"', '', string)
null
null
null
Where do all valid course_ids fall alphabetically ?
def course_ids_between(start_word, end_word): valid_courses = [] for course in modulestore().get_courses(): course_id = course.id.to_deprecated_string() if (start_word.lower() <= course_id.lower() <= end_word.lower()): valid_courses.append(course.id) return valid_courses
null
null
null
between start_word and end_word
codeqa
def course ids between start word end word valid courses []for course in modulestore get courses course id course id to deprecated string if start word lower < course id lower < end word lower valid courses append course id return valid courses
null
null
null
null
Question: Where do all valid course_ids fall alphabetically ? Code: def course_ids_between(start_word, end_word): valid_courses = [] for course in modulestore().get_courses(): course_id = course.id.to_deprecated_string() if (start_word.lower() <= course_id.lower() <= end_word.lower()): valid_courses.append(course.id) return valid_courses
null
null
null
How do all valid course_ids fall between start_word and end_word ?
def course_ids_between(start_word, end_word): valid_courses = [] for course in modulestore().get_courses(): course_id = course.id.to_deprecated_string() if (start_word.lower() <= course_id.lower() <= end_word.lower()): valid_courses.append(course.id) return valid_courses
null
null
null
alphabetically
codeqa
def course ids between start word end word valid courses []for course in modulestore get courses course id course id to deprecated string if start word lower < course id lower < end word lower valid courses append course id return valid courses
null
null
null
null
Question: How do all valid course_ids fall between start_word and end_word ? Code: def course_ids_between(start_word, end_word): valid_courses = [] for course in modulestore().get_courses(): course_id = course.id.to_deprecated_string() if (start_word.lower() <= course_id.lower() <= end_word.lower()): valid_courses.append(course.id) return valid_courses
null
null
null
What does the code reevaluate ?
def trg_write(uid, res_type, res_id, cr): return WorkflowService.new(cr, uid, res_type, res_id).write()
null
null
null
the specified workflow instance
codeqa
def trg write uid res type res id cr return Workflow Service new cr uid res type res id write
null
null
null
null
Question: What does the code reevaluate ? Code: def trg_write(uid, res_type, res_id, cr): return WorkflowService.new(cr, uid, res_type, res_id).write()
null
null
null
What does this method get ?
def get_command_from_state(state): command = None if (state == 'present'): command = 'vrouter-interface-add' if (state == 'absent'): command = 'vrouter-interface-remove' if (state == 'update'): command = 'vrouter-interface-modify' return command
null
null
null
appropriate command name for the state specified
codeqa
def get command from state state command Noneif state 'present' command 'vrouter-interface-add'if state 'absent' command 'vrouter-interface-remove'if state 'update' command 'vrouter-interface-modify'return command
null
null
null
null
Question: What does this method get ? Code: def get_command_from_state(state): command = None if (state == 'present'): command = 'vrouter-interface-add' if (state == 'absent'): command = 'vrouter-interface-remove' if (state == 'update'): command = 'vrouter-interface-modify' return command
null
null
null
In which direction do default parameters read ?
def load_qiime_config(): qiime_config_filepaths = [] qiime_project_dir = get_qiime_project_dir() qiime_config_filepaths.append((qiime_project_dir + '/qiime/support_files/qiime_config')) qiime_config_env_filepath = getenv('QIIME_CONFIG_FP') if qiime_config_env_filepath: qiime_config_filepaths.append(qiime_config_env_filepath) home_dir = getenv('HOME') if home_dir: qiime_config_home_filepath = (home_dir + '/.qiime_config') qiime_config_filepaths.append(qiime_config_home_filepath) qiime_config_files = [] for qiime_config_filepath in qiime_config_filepaths: if exists(qiime_config_filepath): qiime_config_files.append(open(qiime_config_filepath)) qiime_config = parse_qiime_config_files(qiime_config_files) qiime_config['pick_otus_reference_seqs_fp'] = (qiime_config['pick_otus_reference_seqs_fp'] or get_reference_sequences()) qiime_config['pynast_template_alignment_fp'] = (qiime_config['pynast_template_alignment_fp'] or get_template_alignment()) qiime_config['assign_taxonomy_reference_seqs_fp'] = (qiime_config['assign_taxonomy_reference_seqs_fp'] or get_reference_sequences()) qiime_config['assign_taxonomy_id_to_taxonomy_fp'] = (qiime_config['assign_taxonomy_id_to_taxonomy_fp'] or get_reference_taxonomy()) temp_dir = (qiime_config['temp_dir'] or tempfile.gettempdir()) if (not temp_dir.endswith(os.sep)): temp_dir += os.sep qiime_config['temp_dir'] = temp_dir return qiime_config
null
null
null
in
codeqa
def load qiime config qiime config filepaths []qiime project dir get qiime project dir qiime config filepaths append qiime project dir + '/qiime/support files/qiime config' qiime config env filepath getenv 'QIIME CONFIG FP' if qiime config env filepath qiime config filepaths append qiime config env filepath home dir getenv 'HOME' if home dir qiime config home filepath home dir + '/ qiime config' qiime config filepaths append qiime config home filepath qiime config files []for qiime config filepath in qiime config filepaths if exists qiime config filepath qiime config files append open qiime config filepath qiime config parse qiime config files qiime config files qiime config['pick otus reference seqs fp'] qiime config['pick otus reference seqs fp'] or get reference sequences qiime config['pynast template alignment fp'] qiime config['pynast template alignment fp'] or get template alignment qiime config['assign taxonomy reference seqs fp'] qiime config['assign taxonomy reference seqs fp'] or get reference sequences qiime config['assign taxonomy id to taxonomy fp'] qiime config['assign taxonomy id to taxonomy fp'] or get reference taxonomy temp dir qiime config['temp dir'] or tempfile gettempdir if not temp dir endswith os sep temp dir + os sepqiime config['temp dir'] temp dirreturn qiime config
null
null
null
null
Question: In which direction do default parameters read ? Code: def load_qiime_config(): qiime_config_filepaths = [] qiime_project_dir = get_qiime_project_dir() qiime_config_filepaths.append((qiime_project_dir + '/qiime/support_files/qiime_config')) qiime_config_env_filepath = getenv('QIIME_CONFIG_FP') if qiime_config_env_filepath: qiime_config_filepaths.append(qiime_config_env_filepath) home_dir = getenv('HOME') if home_dir: qiime_config_home_filepath = (home_dir + '/.qiime_config') qiime_config_filepaths.append(qiime_config_home_filepath) qiime_config_files = [] for qiime_config_filepath in qiime_config_filepaths: if exists(qiime_config_filepath): qiime_config_files.append(open(qiime_config_filepath)) qiime_config = parse_qiime_config_files(qiime_config_files) qiime_config['pick_otus_reference_seqs_fp'] = (qiime_config['pick_otus_reference_seqs_fp'] or get_reference_sequences()) qiime_config['pynast_template_alignment_fp'] = (qiime_config['pynast_template_alignment_fp'] or get_template_alignment()) qiime_config['assign_taxonomy_reference_seqs_fp'] = (qiime_config['assign_taxonomy_reference_seqs_fp'] or get_reference_sequences()) qiime_config['assign_taxonomy_id_to_taxonomy_fp'] = (qiime_config['assign_taxonomy_id_to_taxonomy_fp'] or get_reference_taxonomy()) temp_dir = (qiime_config['temp_dir'] or tempfile.gettempdir()) if (not temp_dir.endswith(os.sep)): temp_dir += os.sep qiime_config['temp_dir'] = temp_dir return qiime_config
null
null
null
What does the code perform ?
def _do_mb_post(path, body): return _mb_request(path, 'POST', AUTH_YES, True, body=body)
null
null
null
a single post call for an endpoint with a specified request body
codeqa
def do mb post path body return mb request path 'POST' AUTH YES True body body
null
null
null
null
Question: What does the code perform ? Code: def _do_mb_post(path, body): return _mb_request(path, 'POST', AUTH_YES, True, body=body)
null
null
null
What does the code extract from a document ?
@require_GET @allow_CORS_GET @xframe_options_exempt @process_document_path def code_sample(request, document_slug, document_locale, sample_name): if (not re.search(config.KUMA_WIKI_IFRAME_ALLOWED_HOSTS, request.build_absolute_uri())): raise PermissionDenied document = get_object_or_404(Document, slug=document_slug, locale=document_locale) job = DocumentCodeSampleJob(generation_args=[document.pk]) data = job.get(document.pk, sample_name) data['document'] = document return render(request, 'wiki/code_sample.html', data)
null
null
null
a code sample
codeqa
@require GET@allow CORS GET@xframe options exempt@process document pathdef code sample request document slug document locale sample name if not re search config KUMA WIKI IFRAME ALLOWED HOSTS request build absolute uri raise Permission Denieddocument get object or 404 Document slug document slug locale document locale job Document Code Sample Job generation args [document pk] data job get document pk sample name data['document'] documentreturn render request 'wiki/code sample html' data
null
null
null
null
Question: What does the code extract from a document ? Code: @require_GET @allow_CORS_GET @xframe_options_exempt @process_document_path def code_sample(request, document_slug, document_locale, sample_name): if (not re.search(config.KUMA_WIKI_IFRAME_ALLOWED_HOSTS, request.build_absolute_uri())): raise PermissionDenied document = get_object_or_404(Document, slug=document_slug, locale=document_locale) job = DocumentCodeSampleJob(generation_args=[document.pk]) data = job.get(document.pk, sample_name) data['document'] = document return render(request, 'wiki/code_sample.html', data)
null
null
null
What does the code remove ?
def remove_file(fid, attached_to_doctype=None, attached_to_name=None, from_delete=False): file_name = None if (not (attached_to_doctype and attached_to_name)): attached = frappe.db.get_value(u'File', fid, [u'attached_to_doctype', u'attached_to_name', u'file_name']) if attached: (attached_to_doctype, attached_to_name, file_name) = attached (ignore_permissions, comment) = (False, None) if (attached_to_doctype and attached_to_name and (not from_delete)): doc = frappe.get_doc(attached_to_doctype, attached_to_name) ignore_permissions = (doc.has_permission(u'write') or False) if frappe.flags.in_web_form: ignore_permissions = True if (not file_name): file_name = frappe.db.get_value(u'File', fid, u'file_name') comment = doc.add_comment(u'Attachment Removed', _(u'Removed {0}').format(file_name)) frappe.delete_doc(u'File', fid, ignore_permissions=ignore_permissions) return comment
null
null
null
file and file entry
codeqa
def remove file fid attached to doctype None attached to name None from delete False file name Noneif not attached to doctype and attached to name attached frappe db get value u' File' fid [u'attached to doctype' u'attached to name' u'file name'] if attached attached to doctype attached to name file name attached ignore permissions comment False None if attached to doctype and attached to name and not from delete doc frappe get doc attached to doctype attached to name ignore permissions doc has permission u'write' or False if frappe flags in web form ignore permissions Trueif not file name file name frappe db get value u' File' fid u'file name' comment doc add comment u' Attachment Removed' u' Removed{ 0 }' format file name frappe delete doc u' File' fid ignore permissions ignore permissions return comment
null
null
null
null
Question: What does the code remove ? Code: def remove_file(fid, attached_to_doctype=None, attached_to_name=None, from_delete=False): file_name = None if (not (attached_to_doctype and attached_to_name)): attached = frappe.db.get_value(u'File', fid, [u'attached_to_doctype', u'attached_to_name', u'file_name']) if attached: (attached_to_doctype, attached_to_name, file_name) = attached (ignore_permissions, comment) = (False, None) if (attached_to_doctype and attached_to_name and (not from_delete)): doc = frappe.get_doc(attached_to_doctype, attached_to_name) ignore_permissions = (doc.has_permission(u'write') or False) if frappe.flags.in_web_form: ignore_permissions = True if (not file_name): file_name = frappe.db.get_value(u'File', fid, u'file_name') comment = doc.add_comment(u'Attachment Removed', _(u'Removed {0}').format(file_name)) frappe.delete_doc(u'File', fid, ignore_permissions=ignore_permissions) return comment
null
null
null
What does the code show ?
def diff_expression(parent, expr, create_widget=False, hide_expr=False, focus_tree=False): dlg = FileDiffDialog(parent, expr=expr, hide_expr=hide_expr, focus_tree=focus_tree) if create_widget: return dlg dlg.show() dlg.raise_() return (dlg.exec_() == QtWidgets.QDialog.Accepted)
null
null
null
a diff dialog for diff expressions
codeqa
def diff expression parent expr create widget False hide expr False focus tree False dlg File Diff Dialog parent expr expr hide expr hide expr focus tree focus tree if create widget return dlgdlg show dlg raise return dlg exec Qt Widgets Q Dialog Accepted
null
null
null
null
Question: What does the code show ? Code: def diff_expression(parent, expr, create_widget=False, hide_expr=False, focus_tree=False): dlg = FileDiffDialog(parent, expr=expr, hide_expr=hide_expr, focus_tree=focus_tree) if create_widget: return dlg dlg.show() dlg.raise_() return (dlg.exec_() == QtWidgets.QDialog.Accepted)
null
null
null
What does the code get ?
def getWidenedLoops(loop, loopList, outsetLoop, radius): intersectingWithinLoops = getIntersectingWithinLoops(loop, loopList, outsetLoop) if (len(intersectingWithinLoops) < 1): return [loop] loopsUnified = boolean_solid.getLoopsUnion(radius, [[loop], intersectingWithinLoops]) if (len(loopsUnified) < 1): return [loop] return loopsUnified
null
null
null
the widened loop
codeqa
def get Widened Loops loop loop List outset Loop radius intersecting Within Loops get Intersecting Within Loops loop loop List outset Loop if len intersecting Within Loops < 1 return [loop]loops Unified boolean solid get Loops Union radius [[loop] intersecting Within Loops] if len loops Unified < 1 return [loop]return loops Unified
null
null
null
null
Question: What does the code get ? Code: def getWidenedLoops(loop, loopList, outsetLoop, radius): intersectingWithinLoops = getIntersectingWithinLoops(loop, loopList, outsetLoop) if (len(intersectingWithinLoops) < 1): return [loop] loopsUnified = boolean_solid.getLoopsUnion(radius, [[loop], intersectingWithinLoops]) if (len(loopsUnified) < 1): return [loop] return loopsUnified
null
null
null
What does the code remove ?
@pytest.fixture(scope=u'function') def remove_cheese_file(request): def fin_remove_cheese_file(): if os.path.exists(u'tests/files/cheese.txt'): os.remove(u'tests/files/cheese.txt') request.addfinalizer(fin_remove_cheese_file)
null
null
null
the cheese text file which is created by the tests
codeqa
@pytest fixture scope u'function' def remove cheese file request def fin remove cheese file if os path exists u'tests/files/cheese txt' os remove u'tests/files/cheese txt' request addfinalizer fin remove cheese file
null
null
null
null
Question: What does the code remove ? Code: @pytest.fixture(scope=u'function') def remove_cheese_file(request): def fin_remove_cheese_file(): if os.path.exists(u'tests/files/cheese.txt'): os.remove(u'tests/files/cheese.txt') request.addfinalizer(fin_remove_cheese_file)
null
null
null
What used to give back a list of all possible primitive data sample types ?
def get_all_primitive_params(key): params = [key] for datatype in PRIMITIVE_DATATYPES: if ((key == 1) and (datatype == 'ascii')): params.append('') else: params.append(get_sample(datatype)) return params
null
null
null
simple utility method
codeqa
def get all primitive params key params [key]for datatype in PRIMITIVE DATATYPES if key 1 and datatype 'ascii' params append '' else params append get sample datatype return params
null
null
null
null
Question: What used to give back a list of all possible primitive data sample types ? Code: def get_all_primitive_params(key): params = [key] for datatype in PRIMITIVE_DATATYPES: if ((key == 1) and (datatype == 'ascii')): params.append('') else: params.append(get_sample(datatype)) return params
null
null
null
What gives a list of all possible primitive data sample types ?
def get_all_primitive_params(key): params = [key] for datatype in PRIMITIVE_DATATYPES: if ((key == 1) and (datatype == 'ascii')): params.append('') else: params.append(get_sample(datatype)) return params
null
null
null
simple
codeqa
def get all primitive params key params [key]for datatype in PRIMITIVE DATATYPES if key 1 and datatype 'ascii' params append '' else params append get sample datatype return params
null
null
null
null
Question: What gives a list of all possible primitive data sample types ? Code: def get_all_primitive_params(key): params = [key] for datatype in PRIMITIVE_DATATYPES: if ((key == 1) and (datatype == 'ascii')): params.append('') else: params.append(get_sample(datatype)) return params
null
null
null
What did simple give ?
def get_all_primitive_params(key): params = [key] for datatype in PRIMITIVE_DATATYPES: if ((key == 1) and (datatype == 'ascii')): params.append('') else: params.append(get_sample(datatype)) return params
null
null
null
a list of all possible primitive data sample types
codeqa
def get all primitive params key params [key]for datatype in PRIMITIVE DATATYPES if key 1 and datatype 'ascii' params append '' else params append get sample datatype return params
null
null
null
null
Question: What did simple give ? Code: def get_all_primitive_params(key): params = [key] for datatype in PRIMITIVE_DATATYPES: if ((key == 1) and (datatype == 'ascii')): params.append('') else: params.append(get_sample(datatype)) return params
null
null
null
What did simple utility method use ?
def get_all_primitive_params(key): params = [key] for datatype in PRIMITIVE_DATATYPES: if ((key == 1) and (datatype == 'ascii')): params.append('') else: params.append(get_sample(datatype)) return params
null
null
null
to give back a list of all possible primitive data sample types
codeqa
def get all primitive params key params [key]for datatype in PRIMITIVE DATATYPES if key 1 and datatype 'ascii' params append '' else params append get sample datatype return params
null
null
null
null
Question: What did simple utility method use ? Code: def get_all_primitive_params(key): params = [key] for datatype in PRIMITIVE_DATATYPES: if ((key == 1) and (datatype == 'ascii')): params.append('') else: params.append(get_sample(datatype)) return params
null
null
null
What converts into a positive index ?
def wrap_neg_index(index, dim): if ((index is not None) and (index < 0)): index %= dim return index
null
null
null
a negative index
codeqa
def wrap neg index index dim if index is not None and index < 0 index % dimreturn index
null
null
null
null
Question: What converts into a positive index ? Code: def wrap_neg_index(index, dim): if ((index is not None) and (index < 0)): index %= dim return index
null
null
null
What does a negative index convert ?
def wrap_neg_index(index, dim): if ((index is not None) and (index < 0)): index %= dim return index
null
null
null
into a positive index
codeqa
def wrap neg index index dim if index is not None and index < 0 index % dimreturn index
null
null
null
null
Question: What does a negative index convert ? Code: def wrap_neg_index(index, dim): if ((index is not None) and (index < 0)): index %= dim return index
null
null
null
What does the code indicate ?
@loader_option() def defaultload(loadopt, attr): return loadopt.set_relationship_strategy(attr, None)
null
null
null
an attribute should load using its default loader style
codeqa
@loader option def defaultload loadopt attr return loadopt set relationship strategy attr None
null
null
null
null
Question: What does the code indicate ? Code: @loader_option() def defaultload(loadopt, attr): return loadopt.set_relationship_strategy(attr, None)
null
null
null
How should an attribute load ?
@loader_option() def defaultload(loadopt, attr): return loadopt.set_relationship_strategy(attr, None)
null
null
null
using its default loader style
codeqa
@loader option def defaultload loadopt attr return loadopt set relationship strategy attr None
null
null
null
null
Question: How should an attribute load ? Code: @loader_option() def defaultload(loadopt, attr): return loadopt.set_relationship_strategy(attr, None)
null
null
null
What do them raise ?
def killall(greenlets, exception=GreenletExit, block=True, timeout=None): greenlets = list(greenlets) if (not greenlets): return loop = greenlets[0].loop if block: waiter = Waiter() loop.run_callback(_killall3, greenlets, exception, waiter) t = Timeout._start_new_or_dummy(timeout) try: alive = waiter.get() if alive: joinall(alive, raise_error=False) finally: t.cancel() else: loop.run_callback(_killall, greenlets, exception)
null
null
null
exception
codeqa
def killall greenlets exception Greenlet Exit block True timeout None greenlets list greenlets if not greenlets returnloop greenlets[ 0 ] loopif block waiter Waiter loop run callback killall 3 greenlets exception waiter t Timeout start new or dummy timeout try alive waiter get if alive joinall alive raise error False finally t cancel else loop run callback killall greenlets exception
null
null
null
null
Question: What do them raise ? Code: def killall(greenlets, exception=GreenletExit, block=True, timeout=None): greenlets = list(greenlets) if (not greenlets): return loop = greenlets[0].loop if block: waiter = Waiter() loop.run_callback(_killall3, greenlets, exception, waiter) t = Timeout._start_new_or_dummy(timeout) try: alive = waiter.get() if alive: joinall(alive, raise_error=False) finally: t.cancel() else: loop.run_callback(_killall, greenlets, exception)
null
null
null
How do targets ping ?
def startpings(host, targetips): targetips = ' '.join(targetips) cmd = ((('while true; do for ip in %s; do ' % targetips) + (' echo -n %s "->" $ip ' % host.IP())) + ' `ping -c1 -w 1 $ip | grep packets` ; sleep 1; done; done &') info(('*** Host %s (%s) will be pinging ips: %s\n' % (host.name, host.IP(), targetips))) host.cmd(cmd)
null
null
null
repeatedly
codeqa
def startpings host targetips targetips '' join targetips cmd 'whiletrue doforipin%s do' % targetips + 'echo-n%s"->"$ip' % host IP + '`ping-c 1 -w 1 $ip greppackets` sleep 1 done done&' info '*** Host%s %s willbepingingips %s\n' % host name host IP targetips host cmd cmd
null
null
null
null
Question: How do targets ping ? Code: def startpings(host, targetips): targetips = ' '.join(targetips) cmd = ((('while true; do for ip in %s; do ' % targetips) + (' echo -n %s "->" $ip ' % host.IP())) + ' `ping -c1 -w 1 $ip | grep packets` ; sleep 1; done; done &') info(('*** Host %s (%s) will be pinging ips: %s\n' % (host.name, host.IP(), targetips))) host.cmd(cmd)
null
null
null
What tells host ?
def startpings(host, targetips): targetips = ' '.join(targetips) cmd = ((('while true; do for ip in %s; do ' % targetips) + (' echo -n %s "->" $ip ' % host.IP())) + ' `ping -c1 -w 1 $ip | grep packets` ; sleep 1; done; done &') info(('*** Host %s (%s) will be pinging ips: %s\n' % (host.name, host.IP(), targetips))) host.cmd(cmd)
null
null
null
to repeatedly ping targets
codeqa
def startpings host targetips targetips '' join targetips cmd 'whiletrue doforipin%s do' % targetips + 'echo-n%s"->"$ip' % host IP + '`ping-c 1 -w 1 $ip greppackets` sleep 1 done done&' info '*** Host%s %s willbepingingips %s\n' % host name host IP targetips host cmd cmd
null
null
null
null
Question: What tells host ? Code: def startpings(host, targetips): targetips = ' '.join(targetips) cmd = ((('while true; do for ip in %s; do ' % targetips) + (' echo -n %s "->" $ip ' % host.IP())) + ' `ping -c1 -w 1 $ip | grep packets` ; sleep 1; done; done &') info(('*** Host %s (%s) will be pinging ips: %s\n' % (host.name, host.IP(), targetips))) host.cmd(cmd)
null
null
null
When does decorator turn signal handlers ?
def disable_signal_for_loaddata(signal_handler): @wraps(signal_handler) def wrapper(*args, **kwargs): if kwargs.get(u'raw', False): return return signal_handler(*args, **kwargs) return wrapper
null
null
null
when loading fixture data
codeqa
def disable signal for loaddata signal handler @wraps signal handler def wrapper *args **kwargs if kwargs get u'raw' False returnreturn signal handler *args **kwargs return wrapper
null
null
null
null
Question: When does decorator turn signal handlers ? Code: def disable_signal_for_loaddata(signal_handler): @wraps(signal_handler) def wrapper(*args, **kwargs): if kwargs.get(u'raw', False): return return signal_handler(*args, **kwargs) return wrapper
null
null
null
What does decorator turn when loading fixture data ?
def disable_signal_for_loaddata(signal_handler): @wraps(signal_handler) def wrapper(*args, **kwargs): if kwargs.get(u'raw', False): return return signal_handler(*args, **kwargs) return wrapper
null
null
null
signal handlers
codeqa
def disable signal for loaddata signal handler @wraps signal handler def wrapper *args **kwargs if kwargs get u'raw' False returnreturn signal handler *args **kwargs return wrapper
null
null
null
null
Question: What does decorator turn when loading fixture data ? Code: def disable_signal_for_loaddata(signal_handler): @wraps(signal_handler) def wrapper(*args, **kwargs): if kwargs.get(u'raw', False): return return signal_handler(*args, **kwargs) return wrapper
null
null
null
What turns signal handlers when loading fixture data ?
def disable_signal_for_loaddata(signal_handler): @wraps(signal_handler) def wrapper(*args, **kwargs): if kwargs.get(u'raw', False): return return signal_handler(*args, **kwargs) return wrapper
null
null
null
decorator
codeqa
def disable signal for loaddata signal handler @wraps signal handler def wrapper *args **kwargs if kwargs get u'raw' False returnreturn signal handler *args **kwargs return wrapper
null
null
null
null
Question: What turns signal handlers when loading fixture data ? Code: def disable_signal_for_loaddata(signal_handler): @wraps(signal_handler) def wrapper(*args, **kwargs): if kwargs.get(u'raw', False): return return signal_handler(*args, **kwargs) return wrapper
null
null
null
What do a simple decorator enable ?
def cors_enabled(origin, methods=['GET']): def decorator(f): @wraps(f) def decorated_func(request, *args, **kwargs): if (request.method == 'OPTIONS'): if (('HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META) and ('HTTP_ACCESS_CONTROL_REQUEST_HEADERS' in request.META)): response = http.HttpResponse() response['Access-Control-Allow-Methods'] = ', '.join(methods) response['Access-Control-Allow-Headers'] = request.META['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'] else: return http.HttpResponseBadRequest() elif (request.method in methods): response = f(request, *args, **kwargs) else: return http.HttpResponseBadRequest() response['Access-Control-Allow-Origin'] = origin return response return decorated_func return decorator
null
null
null
cors
codeqa
def cors enabled origin methods ['GET'] def decorator f @wraps f def decorated func request *args **kwargs if request method 'OPTIONS' if 'HTTP ACCESS CONTROL REQUEST METHOD' in request META and 'HTTP ACCESS CONTROL REQUEST HEADERS' in request META response http Http Response response[' Access- Control- Allow- Methods'] ' ' join methods response[' Access- Control- Allow- Headers'] request META['HTTP ACCESS CONTROL REQUEST HEADERS']else return http Http Response Bad Request elif request method in methods response f request *args **kwargs else return http Http Response Bad Request response[' Access- Control- Allow- Origin'] originreturn responsereturn decorated funcreturn decorator
null
null
null
null
Question: What do a simple decorator enable ? Code: def cors_enabled(origin, methods=['GET']): def decorator(f): @wraps(f) def decorated_func(request, *args, **kwargs): if (request.method == 'OPTIONS'): if (('HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META) and ('HTTP_ACCESS_CONTROL_REQUEST_HEADERS' in request.META)): response = http.HttpResponse() response['Access-Control-Allow-Methods'] = ', '.join(methods) response['Access-Control-Allow-Headers'] = request.META['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'] else: return http.HttpResponseBadRequest() elif (request.method in methods): response = f(request, *args, **kwargs) else: return http.HttpResponseBadRequest() response['Access-Control-Allow-Origin'] = origin return response return decorated_func return decorator
null
null
null
Where does the code get the file extension ?
def s3_get_extension(request=None): if (request is None): request = current.request extension = request.extension if ((request.function == 'ticket') and (request.controller == 'admin')): extension = 'html' elif ('format' in request.get_vars): ext = request.get_vars.format if isinstance(ext, list): ext = ext[(-1)] extension = (ext.lower() or extension) else: ext = None for arg in request.args[::(-1)]: if ('.' in arg): ext = arg.rsplit('.', 1)[1].lower() break if ext: extension = ext return extension
null
null
null
in the path of the request
codeqa
def s3 get extension request None if request is None request current requestextension request extensionif request function 'ticket' and request controller 'admin' extension 'html'elif 'format' in request get vars ext request get vars formatif isinstance ext list ext ext[ -1 ]extension ext lower or extension else ext Nonefor arg in request args[ -1 ] if ' ' in arg ext arg rsplit ' ' 1 [1 ] lower breakif ext extension extreturn extension
null
null
null
null
Question: Where does the code get the file extension ? Code: def s3_get_extension(request=None): if (request is None): request = current.request extension = request.extension if ((request.function == 'ticket') and (request.controller == 'admin')): extension = 'html' elif ('format' in request.get_vars): ext = request.get_vars.format if isinstance(ext, list): ext = ext[(-1)] extension = (ext.lower() or extension) else: ext = None for arg in request.args[::(-1)]: if ('.' in arg): ext = arg.rsplit('.', 1)[1].lower() break if ext: extension = ext return extension
null
null
null
What does the code get in the path of the request ?
def s3_get_extension(request=None): if (request is None): request = current.request extension = request.extension if ((request.function == 'ticket') and (request.controller == 'admin')): extension = 'html' elif ('format' in request.get_vars): ext = request.get_vars.format if isinstance(ext, list): ext = ext[(-1)] extension = (ext.lower() or extension) else: ext = None for arg in request.args[::(-1)]: if ('.' in arg): ext = arg.rsplit('.', 1)[1].lower() break if ext: extension = ext return extension
null
null
null
the file extension
codeqa
def s3 get extension request None if request is None request current requestextension request extensionif request function 'ticket' and request controller 'admin' extension 'html'elif 'format' in request get vars ext request get vars formatif isinstance ext list ext ext[ -1 ]extension ext lower or extension else ext Nonefor arg in request args[ -1 ] if ' ' in arg ext arg rsplit ' ' 1 [1 ] lower breakif ext extension extreturn extension
null
null
null
null
Question: What does the code get in the path of the request ? Code: def s3_get_extension(request=None): if (request is None): request = current.request extension = request.extension if ((request.function == 'ticket') and (request.controller == 'admin')): extension = 'html' elif ('format' in request.get_vars): ext = request.get_vars.format if isinstance(ext, list): ext = ext[(-1)] extension = (ext.lower() or extension) else: ext = None for arg in request.args[::(-1)]: if ('.' in arg): ext = arg.rsplit('.', 1)[1].lower() break if ext: extension = ext return extension
null
null
null
What did the code set back from the state system ?
def _set_retcode(ret): __context__['retcode'] = 0 if isinstance(ret, list): __context__['retcode'] = 1 return if (not salt.utils.check_state_result(ret)): __context__['retcode'] = 2
null
null
null
the return code based on the data
codeqa
def set retcode ret context ['retcode'] 0if isinstance ret list context ['retcode'] 1returnif not salt utils check state result ret context ['retcode'] 2
null
null
null
null
Question: What did the code set back from the state system ? Code: def _set_retcode(ret): __context__['retcode'] = 0 if isinstance(ret, list): __context__['retcode'] = 1 return if (not salt.utils.check_state_result(ret)): __context__['retcode'] = 2
null
null
null
What do we have ?
def _ensure_decoded(s): if isinstance(s, np.bytes_): s = s.decode('UTF-8') return s
null
null
null
bytes
codeqa
def ensure decoded s if isinstance s np bytes s s decode 'UTF- 8 ' return s
null
null
null
null
Question: What do we have ? Code: def _ensure_decoded(s): if isinstance(s, np.bytes_): s = s.decode('UTF-8') return s
null
null
null
What does the code get ?
def national_significant_number(numobj): national_number = U_EMPTY_STRING if numobj.italian_leading_zero: num_zeros = numobj.number_of_leading_zeros if (num_zeros is None): num_zeros = 1 national_number = (U_ZERO * num_zeros) national_number += str(numobj.national_number) return national_number
null
null
null
the national significant number of a phone number
codeqa
def national significant number numobj national number U EMPTY STRIN Gif numobj italian leading zero num zeros numobj number of leading zerosif num zeros is None num zeros 1national number U ZERO * num zeros national number + str numobj national number return national number
null
null
null
null
Question: What does the code get ? Code: def national_significant_number(numobj): national_number = U_EMPTY_STRING if numobj.italian_leading_zero: num_zeros = numobj.number_of_leading_zeros if (num_zeros is None): num_zeros = 1 national_number = (U_ZERO * num_zeros) national_number += str(numobj.national_number) return national_number
null
null
null
What does not have unit ?
def test_quantity_representation(): t = QTable([([1, 2] * u.m)]) assert (t.pformat() == ['col0', ' m ', '----', ' 1.0', ' 2.0'])
null
null
null
table representation of quantities
codeqa
def test quantity representation t Q Table [ [1 2] * u m ] assert t pformat ['col 0 ' 'm' '----' '1 0' '2 0']
null
null
null
null
Question: What does not have unit ? Code: def test_quantity_representation(): t = QTable([([1, 2] * u.m)]) assert (t.pformat() == ['col0', ' m ', '----', ' 1.0', ' 2.0'])
null
null
null
What does table representation of quantities not have ?
def test_quantity_representation(): t = QTable([([1, 2] * u.m)]) assert (t.pformat() == ['col0', ' m ', '----', ' 1.0', ' 2.0'])
null
null
null
unit
codeqa
def test quantity representation t Q Table [ [1 2] * u m ] assert t pformat ['col 0 ' 'm' '----' '1 0' '2 0']
null
null
null
null
Question: What does table representation of quantities not have ? Code: def test_quantity_representation(): t = QTable([([1, 2] * u.m)]) assert (t.pformat() == ['col0', ' m ', '----', ' 1.0', ' 2.0'])
null
null
null
Does table representation of quantities have unit ?
def test_quantity_representation(): t = QTable([([1, 2] * u.m)]) assert (t.pformat() == ['col0', ' m ', '----', ' 1.0', ' 2.0'])
null
null
null
No
codeqa
def test quantity representation t Q Table [ [1 2] * u m ] assert t pformat ['col 0 ' 'm' '----' '1 0' '2 0']
null
null
null
null
Question: Does table representation of quantities have unit ? Code: def test_quantity_representation(): t = QTable([([1, 2] * u.m)]) assert (t.pformat() == ['col0', ' m ', '----', ' 1.0', ' 2.0'])
null
null
null
What does the code get ?
def table_dictize(obj, context, **kw): result_dict = {} model = context['model'] session = model.Session if isinstance(obj, RowProxy): fields = obj.keys() else: ModelClass = obj.__class__ table = class_mapper(ModelClass).mapped_table fields = [field.name for field in table.c] for field in fields: name = field if (name in ('current', 'expired_timestamp', 'expired_id')): continue if (name == 'continuity_id'): continue value = getattr(obj, name) if (value is None): result_dict[name] = value elif isinstance(value, dict): result_dict[name] = value elif isinstance(value, int): result_dict[name] = value elif isinstance(value, long): result_dict[name] = value elif isinstance(value, datetime.datetime): result_dict[name] = value.isoformat() elif isinstance(value, list): result_dict[name] = value else: result_dict[name] = unicode(value) result_dict.update(kw) context['metadata_modified'] = max(result_dict.get('revision_timestamp', ''), context.get('metadata_modified', '')) return result_dict
null
null
null
any model object
codeqa
def table dictize obj context **kw result dict {}model context['model']session model Sessionif isinstance obj Row Proxy fields obj keys else Model Class obj class table class mapper Model Class mapped tablefields [field name for field in table c]for field in fields name fieldif name in 'current' 'expired timestamp' 'expired id' continueif name 'continuity id' continuevalue getattr obj name if value is None result dict[name] valueelif isinstance value dict result dict[name] valueelif isinstance value int result dict[name] valueelif isinstance value long result dict[name] valueelif isinstance value datetime datetime result dict[name] value isoformat elif isinstance value list result dict[name] valueelse result dict[name] unicode value result dict update kw context['metadata modified'] max result dict get 'revision timestamp' '' context get 'metadata modified' '' return result dict
null
null
null
null
Question: What does the code get ? Code: def table_dictize(obj, context, **kw): result_dict = {} model = context['model'] session = model.Session if isinstance(obj, RowProxy): fields = obj.keys() else: ModelClass = obj.__class__ table = class_mapper(ModelClass).mapped_table fields = [field.name for field in table.c] for field in fields: name = field if (name in ('current', 'expired_timestamp', 'expired_id')): continue if (name == 'continuity_id'): continue value = getattr(obj, name) if (value is None): result_dict[name] = value elif isinstance(value, dict): result_dict[name] = value elif isinstance(value, int): result_dict[name] = value elif isinstance(value, long): result_dict[name] = value elif isinstance(value, datetime.datetime): result_dict[name] = value.isoformat() elif isinstance(value, list): result_dict[name] = value else: result_dict[name] = unicode(value) result_dict.update(kw) context['metadata_modified'] = max(result_dict.get('revision_timestamp', ''), context.get('metadata_modified', '')) return result_dict
null
null
null
For what purpose did the validation message show ?
def get_empty_preference_message(preference_key): return "Preference '{preference_key}' cannot be set to an empty value.".format(preference_key=preference_key)
null
null
null
for an empty preference
codeqa
def get empty preference message preference key return " Preference'{preference key}'cannotbesettoanemptyvalue " format preference key preference key
null
null
null
null
Question: For what purpose did the validation message show ? Code: def get_empty_preference_message(preference_key): return "Preference '{preference_key}' cannot be set to an empty value.".format(preference_key=preference_key)
null
null
null
What did the code set ?
def setClockFormat(clockFormat, **kwargs): if ((clockFormat != '12h') and (clockFormat != '24h')): return False _gsession = _GSettings(user=kwargs.get('user'), schema='org.gnome.desktop.interface', key='clock-format') return _gsession._set(clockFormat)
null
null
null
the clock format
codeqa
def set Clock Format clock Format **kwargs if clock Format '12 h' and clock Format '24 h' return False gsession G Settings user kwargs get 'user' schema 'org gnome desktop interface' key 'clock-format' return gsession set clock Format
null
null
null
null
Question: What did the code set ? Code: def setClockFormat(clockFormat, **kwargs): if ((clockFormat != '12h') and (clockFormat != '24h')): return False _gsession = _GSettings(user=kwargs.get('user'), schema='org.gnome.desktop.interface', key='clock-format') return _gsession._set(clockFormat)
null
null
null
How do git pull ?
def remote_args(remote, local_branch=u'', remote_branch=u'', ff_only=False, force=False, no_ff=False, tags=False, rebase=False, pull=False, push=False, set_upstream=False): args = [remote] what = refspec_arg(local_branch, remote_branch, pull, push) if what: args.append(what) kwargs = {u'verbose': True} if pull: if rebase: kwargs[u'rebase'] = True elif ff_only: kwargs[u'ff_only'] = True elif no_ff: kwargs[u'no_ff'] = True elif force: kwargs[u'force'] = True if (push and set_upstream): kwargs[u'set_upstream'] = True if tags: kwargs[u'tags'] = True return (args, kwargs)
null
null
null
fetch
codeqa
def remote args remote local branch u'' remote branch u'' ff only False force False no ff False tags False rebase False pull False push False set upstream False args [remote]what refspec arg local branch remote branch pull push if what args append what kwargs {u'verbose' True}if pull if rebase kwargs[u'rebase'] Trueelif ff only kwargs[u'ff only'] Trueelif no ff kwargs[u'no ff'] Trueelif force kwargs[u'force'] Trueif push and set upstream kwargs[u'set upstream'] Trueif tags kwargs[u'tags'] Truereturn args kwargs
null
null
null
null
Question: How do git pull ? Code: def remote_args(remote, local_branch=u'', remote_branch=u'', ff_only=False, force=False, no_ff=False, tags=False, rebase=False, pull=False, push=False, set_upstream=False): args = [remote] what = refspec_arg(local_branch, remote_branch, pull, push) if what: args.append(what) kwargs = {u'verbose': True} if pull: if rebase: kwargs[u'rebase'] = True elif ff_only: kwargs[u'ff_only'] = True elif no_ff: kwargs[u'no_ff'] = True elif force: kwargs[u'force'] = True if (push and set_upstream): kwargs[u'set_upstream'] = True if tags: kwargs[u'tags'] = True return (args, kwargs)
null
null
null
What does the code create ?
def _createFilesDir(): if (not conf.rFile): return conf.filePath = (paths.SQLMAP_FILES_PATH % conf.hostname) if (not os.path.isdir(conf.filePath)): try: os.makedirs(conf.filePath, 493) except OSError as ex: tempDir = tempfile.mkdtemp(prefix='sqlmapfiles') warnMsg = 'unable to create files directory ' warnMsg += ("'%s' (%s). " % (conf.filePath, getUnicode(ex))) warnMsg += ("Using temporary directory '%s' instead" % tempDir) logger.warn(warnMsg) conf.filePath = tempDir
null
null
null
the file directory
codeqa
def create Files Dir if not conf r File returnconf file Path paths SQLMAP FILES PATH % conf hostname if not os path isdir conf file Path try os makedirs conf file Path 493 except OS Error as ex temp Dir tempfile mkdtemp prefix 'sqlmapfiles' warn Msg 'unabletocreatefilesdirectory'warn Msg + "'%s' %s " % conf file Path get Unicode ex warn Msg + " Usingtemporarydirectory'%s'instead" % temp Dir logger warn warn Msg conf file Path temp Dir
null
null
null
null
Question: What does the code create ? Code: def _createFilesDir(): if (not conf.rFile): return conf.filePath = (paths.SQLMAP_FILES_PATH % conf.hostname) if (not os.path.isdir(conf.filePath)): try: os.makedirs(conf.filePath, 493) except OSError as ex: tempDir = tempfile.mkdtemp(prefix='sqlmapfiles') warnMsg = 'unable to create files directory ' warnMsg += ("'%s' (%s). " % (conf.filePath, getUnicode(ex))) warnMsg += ("Using temporary directory '%s' instead" % tempDir) logger.warn(warnMsg) conf.filePath = tempDir
null
null
null
What does the code generate ?
def generate_login_token(user): return _security.login_serializer.dumps([str(user.id)])
null
null
null
a unique login token for the specified user
codeqa
def generate login token user return security login serializer dumps [str user id ]
null
null
null
null
Question: What does the code generate ? Code: def generate_login_token(user): return _security.login_serializer.dumps([str(user.id)])
null
null
null
What do user - callable function create ?
def mkstemp(suffix='', prefix=template, dir=None, text=False): if (dir is None): dir = gettempdir() if text: flags = _text_openflags else: flags = _bin_openflags return _mkstemp_inner(dir, prefix, suffix, flags)
null
null
null
a unique temporary file
codeqa
def mkstemp suffix '' prefix template dir None text False if dir is None dir gettempdir if text flags text openflagselse flags bin openflagsreturn mkstemp inner dir prefix suffix flags
null
null
null
null
Question: What do user - callable function create ? Code: def mkstemp(suffix='', prefix=template, dir=None, text=False): if (dir is None): dir = gettempdir() if text: flags = _text_openflags else: flags = _bin_openflags return _mkstemp_inner(dir, prefix, suffix, flags)
null
null
null
What creates a unique temporary file ?
def mkstemp(suffix='', prefix=template, dir=None, text=False): if (dir is None): dir = gettempdir() if text: flags = _text_openflags else: flags = _bin_openflags return _mkstemp_inner(dir, prefix, suffix, flags)
null
null
null
user - callable function
codeqa
def mkstemp suffix '' prefix template dir None text False if dir is None dir gettempdir if text flags text openflagselse flags bin openflagsreturn mkstemp inner dir prefix suffix flags
null
null
null
null
Question: What creates a unique temporary file ? Code: def mkstemp(suffix='', prefix=template, dir=None, text=False): if (dir is None): dir = gettempdir() if text: flags = _text_openflags else: flags = _bin_openflags return _mkstemp_inner(dir, prefix, suffix, flags)
null
null
null
How do a test run ?
@contextlib.contextmanager def with_comprehensive_theme_context(theme=None): if theme: domain = '{theme}.org'.format(theme=re.sub('\\.org$', '', theme)) (site, __) = Site.objects.get_or_create(domain=domain, name=theme) (site_theme, __) = SiteTheme.objects.get_or_create(site=site, theme_dir_name=theme) with patch('openedx.core.djangoapps.theming.helpers.get_current_site_theme', return_value=site_theme): with patch('openedx.core.djangoapps.theming.helpers.get_current_site', return_value=site): (yield) else: (yield)
null
null
null
as if request was made to the given theme
codeqa
@contextlib contextmanagerdef with comprehensive theme context theme None if theme domain '{theme} org' format theme re sub '\\ org$' '' theme site Site objects get or create domain domain name theme site theme Site Theme objects get or create site site theme dir name theme with patch 'openedx core djangoapps theming helpers get current site theme' return value site theme with patch 'openedx core djangoapps theming helpers get current site' return value site yield else yield
null
null
null
null
Question: How do a test run ? Code: @contextlib.contextmanager def with_comprehensive_theme_context(theme=None): if theme: domain = '{theme}.org'.format(theme=re.sub('\\.org$', '', theme)) (site, __) = Site.objects.get_or_create(domain=domain, name=theme) (site_theme, __) = SiteTheme.objects.get_or_create(site=site, theme_dir_name=theme) with patch('openedx.core.djangoapps.theming.helpers.get_current_site_theme', return_value=site_theme): with patch('openedx.core.djangoapps.theming.helpers.get_current_site', return_value=site): (yield) else: (yield)
null
null
null
What does the code ensure ?
def mkdir(path, owner=None, grant_perms=None, deny_perms=None, inheritance=True): drive = os.path.splitdrive(path)[0] if (not os.path.isdir(drive)): raise CommandExecutionError('Drive {0} is not mapped'.format(drive)) path = os.path.expanduser(path) path = os.path.expandvars(path) if (not os.path.isdir(path)): os.mkdir(path) if owner: salt.utils.win_dacl.set_owner(path, owner) set_perms(path, grant_perms, deny_perms, inheritance) return True
null
null
null
that the directory is available and permissions are set
codeqa
def mkdir path owner None grant perms None deny perms None inheritance True drive os path splitdrive path [0 ]if not os path isdir drive raise Command Execution Error ' Drive{ 0 }isnotmapped' format drive path os path expanduser path path os path expandvars path if not os path isdir path os mkdir path if owner salt utils win dacl set owner path owner set perms path grant perms deny perms inheritance return True
null
null
null
null
Question: What does the code ensure ? Code: def mkdir(path, owner=None, grant_perms=None, deny_perms=None, inheritance=True): drive = os.path.splitdrive(path)[0] if (not os.path.isdir(drive)): raise CommandExecutionError('Drive {0} is not mapped'.format(drive)) path = os.path.expanduser(path) path = os.path.expandvars(path) if (not os.path.isdir(path)): os.mkdir(path) if owner: salt.utils.win_dacl.set_owner(path, owner) set_perms(path, grant_perms, deny_perms, inheritance) return True
null
null
null
What match any of the installed versions ?
def _fulfills_version_spec(versions, oper, desired_version, ignore_epoch=False): cmp_func = __salt__.get('pkg.version_cmp') if salt.utils.is_freebsd(): if (isinstance(versions, dict) and ('version' in versions)): versions = versions['version'] for ver in versions: if salt.utils.compare_versions(ver1=ver, oper=oper, ver2=desired_version, cmp_func=cmp_func, ignore_epoch=ignore_epoch): return True return False
null
null
null
the specified version
codeqa
def fulfills version spec versions oper desired version ignore epoch False cmp func salt get 'pkg version cmp' if salt utils is freebsd if isinstance versions dict and 'version' in versions versions versions['version']for ver in versions if salt utils compare versions ver 1 ver oper oper ver 2 desired version cmp func cmp func ignore epoch ignore epoch return Truereturn False
null
null
null
null
Question: What match any of the installed versions ? Code: def _fulfills_version_spec(versions, oper, desired_version, ignore_epoch=False): cmp_func = __salt__.get('pkg.version_cmp') if salt.utils.is_freebsd(): if (isinstance(versions, dict) and ('version' in versions)): versions = versions['version'] for ver in versions: if salt.utils.compare_versions(ver1=ver, oper=oper, ver2=desired_version, cmp_func=cmp_func, ignore_epoch=ignore_epoch): return True return False
null
null
null
What does the specified version match ?
def _fulfills_version_spec(versions, oper, desired_version, ignore_epoch=False): cmp_func = __salt__.get('pkg.version_cmp') if salt.utils.is_freebsd(): if (isinstance(versions, dict) and ('version' in versions)): versions = versions['version'] for ver in versions: if salt.utils.compare_versions(ver1=ver, oper=oper, ver2=desired_version, cmp_func=cmp_func, ignore_epoch=ignore_epoch): return True return False
null
null
null
any of the installed versions
codeqa
def fulfills version spec versions oper desired version ignore epoch False cmp func salt get 'pkg version cmp' if salt utils is freebsd if isinstance versions dict and 'version' in versions versions versions['version']for ver in versions if salt utils compare versions ver 1 ver oper oper ver 2 desired version cmp func cmp func ignore epoch ignore epoch return Truereturn False
null
null
null
null
Question: What does the specified version match ? Code: def _fulfills_version_spec(versions, oper, desired_version, ignore_epoch=False): cmp_func = __salt__.get('pkg.version_cmp') if salt.utils.is_freebsd(): if (isinstance(versions, dict) and ('version' in versions)): versions = versions['version'] for ver in versions: if salt.utils.compare_versions(ver1=ver, oper=oper, ver2=desired_version, cmp_func=cmp_func, ignore_epoch=ignore_epoch): return True return False
null
null
null
What does the code make ?
def make_query(qname, rdtype, rdclass=dns.rdataclass.IN, use_edns=None, want_dnssec=False, ednsflags=0, payload=1280, request_payload=None, options=None): if isinstance(qname, (str, unicode)): qname = dns.name.from_text(qname) if isinstance(rdtype, (str, unicode)): rdtype = dns.rdatatype.from_text(rdtype) if isinstance(rdclass, (str, unicode)): rdclass = dns.rdataclass.from_text(rdclass) m = Message() m.flags |= dns.flags.RD m.find_rrset(m.question, qname, rdclass, rdtype, create=True, force_unique=True) m.use_edns(use_edns, ednsflags, payload, request_payload, options) m.want_dnssec(want_dnssec) return m
null
null
null
a query message
codeqa
def make query qname rdtype rdclass dns rdataclass IN use edns None want dnssec False ednsflags 0 payload 1280 request payload None options None if isinstance qname str unicode qname dns name from text qname if isinstance rdtype str unicode rdtype dns rdatatype from text rdtype if isinstance rdclass str unicode rdclass dns rdataclass from text rdclass m Message m flags dns flags R Dm find rrset m question qname rdclass rdtype create True force unique True m use edns use edns ednsflags payload request payload options m want dnssec want dnssec return m
null
null
null
null
Question: What does the code make ? Code: def make_query(qname, rdtype, rdclass=dns.rdataclass.IN, use_edns=None, want_dnssec=False, ednsflags=0, payload=1280, request_payload=None, options=None): if isinstance(qname, (str, unicode)): qname = dns.name.from_text(qname) if isinstance(rdtype, (str, unicode)): rdtype = dns.rdatatype.from_text(rdtype) if isinstance(rdclass, (str, unicode)): rdclass = dns.rdataclass.from_text(rdclass) m = Message() m.flags |= dns.flags.RD m.find_rrset(m.question, qname, rdclass, rdtype, create=True, force_unique=True) m.use_edns(use_edns, ednsflags, payload, request_payload, options) m.want_dnssec(want_dnssec) return m
null
null
null
For what purpose does the feed items return ?
def GetFeedItems(client, feed): feed_item_service = client.GetService('FeedItemService', 'v201609') feed_items = [] more_pages = True selector = {'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], 'predicates': [{'field': 'Status', 'operator': 'EQUALS', 'values': ['ENABLED']}, {'field': 'FeedId', 'operator': 'EQUALS', 'values': [feed['id']]}], 'paging': {'startIndex': 0, 'numberResults': PAGE_SIZE}} while more_pages: page = feed_item_service.get(selector) if ('entries' in page): feed_items.extend(page['entries']) selector['paging']['startIndex'] += PAGE_SIZE more_pages = (selector['paging']['startIndex'] < int(page['totalNumEntries'])) return feed_items
null
null
null
for a given feed
codeqa
def Get Feed Items client feed feed item service client Get Service ' Feed Item Service' 'v 201609 ' feed items []more pages Trueselector {'fields' [' Feed Item Id' ' Attribute Values' ' Scheduling'] 'predicates' [{'field' ' Status' 'operator' 'EQUALS' 'values' ['ENABLED']} {'field' ' Feed Id' 'operator' 'EQUALS' 'values' [feed['id']]}] 'paging' {'start Index' 0 'number Results' PAGE SIZE}}while more pages page feed item service get selector if 'entries' in page feed items extend page['entries'] selector['paging']['start Index'] + PAGE SIZ Emore pages selector['paging']['start Index'] < int page['total Num Entries'] return feed items
null
null
null
null
Question: For what purpose does the feed items return ? Code: def GetFeedItems(client, feed): feed_item_service = client.GetService('FeedItemService', 'v201609') feed_items = [] more_pages = True selector = {'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], 'predicates': [{'field': 'Status', 'operator': 'EQUALS', 'values': ['ENABLED']}, {'field': 'FeedId', 'operator': 'EQUALS', 'values': [feed['id']]}], 'paging': {'startIndex': 0, 'numberResults': PAGE_SIZE}} while more_pages: page = feed_item_service.get(selector) if ('entries' in page): feed_items.extend(page['entries']) selector['paging']['startIndex'] += PAGE_SIZE more_pages = (selector['paging']['startIndex'] < int(page['totalNumEntries'])) return feed_items
null
null
null
What does a dummy error tracker ignore just ?
def null_error_tracker(msg): pass
null
null
null
the messages
codeqa
def null error tracker msg pass
null
null
null
null
Question: What does a dummy error tracker ignore just ? Code: def null_error_tracker(msg): pass
null
null
null
What ignores the messages just ?
def null_error_tracker(msg): pass
null
null
null
a dummy error tracker
codeqa
def null error tracker msg pass
null
null
null
null
Question: What ignores the messages just ? Code: def null_error_tracker(msg): pass
null
null
null
How did octal values specify ?
def safe_octal(octal_value): try: return oct(octal_value) except TypeError: return str(octal_value)
null
null
null
as a string or as a numeric
codeqa
def safe octal octal value try return oct octal value except Type Error return str octal value
null
null
null
null
Question: How did octal values specify ? Code: def safe_octal(octal_value): try: return oct(octal_value) except TypeError: return str(octal_value)
null
null
null
What computes in a weighted graph ?
def all_pairs_dijkstra_path(G, cutoff=None, weight='weight'): path = single_source_dijkstra_path return {n: path(G, n, cutoff=cutoff, weight=weight) for n in G}
null
null
null
shortest paths between all nodes
codeqa
def all pairs dijkstra path G cutoff None weight 'weight' path single source dijkstra pathreturn {n path G n cutoff cutoff weight weight for n in G}
null
null
null
null
Question: What computes in a weighted graph ? Code: def all_pairs_dijkstra_path(G, cutoff=None, weight='weight'): path = single_source_dijkstra_path return {n: path(G, n, cutoff=cutoff, weight=weight) for n in G}
null
null
null
What did the code read ?
def loadPreferences(filename): global settingsList profileParser = ConfigParser.ConfigParser() try: profileParser.read(filename) except ConfigParser.ParsingError: return for set in settingsList: if set.isPreference(): if profileParser.has_option('preference', set.getName()): set.setValue(unicode(profileParser.get('preference', set.getName()), 'utf-8', 'replace')) n = 0 while profileParser.has_section(('machine_%d' % n)): for set in settingsList: if set.isMachineSetting(): if profileParser.has_option(('machine_%d' % n), set.getName()): set.setValue(unicode(profileParser.get(('machine_%d' % n), set.getName()), 'utf-8', 'replace'), n) n += 1 setActiveMachine(int(getPreferenceFloat('active_machine')))
null
null
null
a configuration file
codeqa
def load Preferences filename global settings Listprofile Parser Config Parser Config Parser try profile Parser read filename except Config Parser Parsing Error returnfor set in settings List if set is Preference if profile Parser has option 'preference' set get Name set set Value unicode profile Parser get 'preference' set get Name 'utf- 8 ' 'replace' n 0while profile Parser has section 'machine %d' % n for set in settings List if set is Machine Setting if profile Parser has option 'machine %d' % n set get Name set set Value unicode profile Parser get 'machine %d' % n set get Name 'utf- 8 ' 'replace' n n + 1set Active Machine int get Preference Float 'active machine'
null
null
null
null
Question: What did the code read ? Code: def loadPreferences(filename): global settingsList profileParser = ConfigParser.ConfigParser() try: profileParser.read(filename) except ConfigParser.ParsingError: return for set in settingsList: if set.isPreference(): if profileParser.has_option('preference', set.getName()): set.setValue(unicode(profileParser.get('preference', set.getName()), 'utf-8', 'replace')) n = 0 while profileParser.has_section(('machine_%d' % n)): for set in settingsList: if set.isMachineSetting(): if profileParser.has_option(('machine_%d' % n), set.getName()): set.setValue(unicode(profileParser.get(('machine_%d' % n), set.getName()), 'utf-8', 'replace'), n) n += 1 setActiveMachine(int(getPreferenceFloat('active_machine')))
null
null
null
How do static analyzer build ?
def scan_build(registry, xml_parent, data): p = XML.SubElement(xml_parent, 'jenkins.plugins.clangscanbuild.publisher.ClangScanBuildPublisher') p.set('plugin', 'clang-scanbuild') mappings = [('mark-unstable', 'markBuildUnstableWhenThresholdIsExceeded', False), ('threshold', 'bugThreshold', 0), ('exclude-paths', 'clangexcludedpaths', ''), ('report-folder', 'reportFolderName', 'clangScanBuildReports')] helpers.convert_mapping_to_xml(p, data, mappings, fail_required=True)
null
null
null
clang
codeqa
def scan build registry xml parent data p XML Sub Element xml parent 'jenkins plugins clangscanbuild publisher Clang Scan Build Publisher' p set 'plugin' 'clang-scanbuild' mappings [ 'mark-unstable' 'mark Build Unstable When Threshold Is Exceeded' False 'threshold' 'bug Threshold' 0 'exclude-paths' 'clangexcludedpaths' '' 'report-folder' 'report Folder Name' 'clang Scan Build Reports' ]helpers convert mapping to xml p data mappings fail required True
null
null
null
null
Question: How do static analyzer build ? Code: def scan_build(registry, xml_parent, data): p = XML.SubElement(xml_parent, 'jenkins.plugins.clangscanbuild.publisher.ClangScanBuildPublisher') p.set('plugin', 'clang-scanbuild') mappings = [('mark-unstable', 'markBuildUnstableWhenThresholdIsExceeded', False), ('threshold', 'bugThreshold', 0), ('exclude-paths', 'clangexcludedpaths', ''), ('report-folder', 'reportFolderName', 'clangScanBuildReports')] helpers.convert_mapping_to_xml(p, data, mappings, fail_required=True)
null
null
null
What does the code classify using the string classifier ?
def classify(state, answer): assert feconf.ENABLE_STRING_CLASSIFIER interaction_instance = interaction_registry.Registry.get_interaction_by_id(state.interaction.id) normalized_answer = interaction_instance.normalize_answer(answer) response = None if interaction_instance.is_string_classifier_trainable: response = classify_string_classifier_rule(state, normalized_answer) else: raise Exception('No classifier found for interaction.') if (response is not None): return response elif (state.interaction.default_outcome is not None): return {'outcome': state.interaction.default_outcome.to_dict(), 'answer_group_index': len(state.interaction.answer_groups), 'classification_certainty': 0.0, 'rule_spec_index': 0} raise Exception('Something has seriously gone wrong with the exploration. Oppia does not know what to do with this answer. Please contact the exploration owner.')
null
null
null
the answer
codeqa
def classify state answer assert feconf ENABLE STRING CLASSIFIE Rinteraction instance interaction registry Registry get interaction by id state interaction id normalized answer interaction instance normalize answer answer response Noneif interaction instance is string classifier trainable response classify string classifier rule state normalized answer else raise Exception ' Noclassifierfoundforinteraction ' if response is not None return responseelif state interaction default outcome is not None return {'outcome' state interaction default outcome to dict 'answer group index' len state interaction answer groups 'classification certainty' 0 0 'rule spec index' 0}raise Exception ' Somethinghasseriouslygonewrongwiththeexploration Oppiadoesnotknowwhattodowiththisanswer Pleasecontacttheexplorationowner '
null
null
null
null
Question: What does the code classify using the string classifier ? Code: def classify(state, answer): assert feconf.ENABLE_STRING_CLASSIFIER interaction_instance = interaction_registry.Registry.get_interaction_by_id(state.interaction.id) normalized_answer = interaction_instance.normalize_answer(answer) response = None if interaction_instance.is_string_classifier_trainable: response = classify_string_classifier_rule(state, normalized_answer) else: raise Exception('No classifier found for interaction.') if (response is not None): return response elif (state.interaction.default_outcome is not None): return {'outcome': state.interaction.default_outcome.to_dict(), 'answer_group_index': len(state.interaction.answer_groups), 'classification_certainty': 0.0, 'rule_spec_index': 0} raise Exception('Something has seriously gone wrong with the exploration. Oppia does not know what to do with this answer. Please contact the exploration owner.')
null
null
null
What is using the string classifier ?
def classify(state, answer): assert feconf.ENABLE_STRING_CLASSIFIER interaction_instance = interaction_registry.Registry.get_interaction_by_id(state.interaction.id) normalized_answer = interaction_instance.normalize_answer(answer) response = None if interaction_instance.is_string_classifier_trainable: response = classify_string_classifier_rule(state, normalized_answer) else: raise Exception('No classifier found for interaction.') if (response is not None): return response elif (state.interaction.default_outcome is not None): return {'outcome': state.interaction.default_outcome.to_dict(), 'answer_group_index': len(state.interaction.answer_groups), 'classification_certainty': 0.0, 'rule_spec_index': 0} raise Exception('Something has seriously gone wrong with the exploration. Oppia does not know what to do with this answer. Please contact the exploration owner.')
null
null
null
the answer
codeqa
def classify state answer assert feconf ENABLE STRING CLASSIFIE Rinteraction instance interaction registry Registry get interaction by id state interaction id normalized answer interaction instance normalize answer answer response Noneif interaction instance is string classifier trainable response classify string classifier rule state normalized answer else raise Exception ' Noclassifierfoundforinteraction ' if response is not None return responseelif state interaction default outcome is not None return {'outcome' state interaction default outcome to dict 'answer group index' len state interaction answer groups 'classification certainty' 0 0 'rule spec index' 0}raise Exception ' Somethinghasseriouslygonewrongwiththeexploration Oppiadoesnotknowwhattodowiththisanswer Pleasecontacttheexplorationowner '
null
null
null
null
Question: What is using the string classifier ? Code: def classify(state, answer): assert feconf.ENABLE_STRING_CLASSIFIER interaction_instance = interaction_registry.Registry.get_interaction_by_id(state.interaction.id) normalized_answer = interaction_instance.normalize_answer(answer) response = None if interaction_instance.is_string_classifier_trainable: response = classify_string_classifier_rule(state, normalized_answer) else: raise Exception('No classifier found for interaction.') if (response is not None): return response elif (state.interaction.default_outcome is not None): return {'outcome': state.interaction.default_outcome.to_dict(), 'answer_group_index': len(state.interaction.answer_groups), 'classification_certainty': 0.0, 'rule_spec_index': 0} raise Exception('Something has seriously gone wrong with the exploration. Oppia does not know what to do with this answer. Please contact the exploration owner.')
null
null
null
How does the code classify the answer ?
def classify(state, answer): assert feconf.ENABLE_STRING_CLASSIFIER interaction_instance = interaction_registry.Registry.get_interaction_by_id(state.interaction.id) normalized_answer = interaction_instance.normalize_answer(answer) response = None if interaction_instance.is_string_classifier_trainable: response = classify_string_classifier_rule(state, normalized_answer) else: raise Exception('No classifier found for interaction.') if (response is not None): return response elif (state.interaction.default_outcome is not None): return {'outcome': state.interaction.default_outcome.to_dict(), 'answer_group_index': len(state.interaction.answer_groups), 'classification_certainty': 0.0, 'rule_spec_index': 0} raise Exception('Something has seriously gone wrong with the exploration. Oppia does not know what to do with this answer. Please contact the exploration owner.')
null
null
null
using the string classifier
codeqa
def classify state answer assert feconf ENABLE STRING CLASSIFIE Rinteraction instance interaction registry Registry get interaction by id state interaction id normalized answer interaction instance normalize answer answer response Noneif interaction instance is string classifier trainable response classify string classifier rule state normalized answer else raise Exception ' Noclassifierfoundforinteraction ' if response is not None return responseelif state interaction default outcome is not None return {'outcome' state interaction default outcome to dict 'answer group index' len state interaction answer groups 'classification certainty' 0 0 'rule spec index' 0}raise Exception ' Somethinghasseriouslygonewrongwiththeexploration Oppiadoesnotknowwhattodowiththisanswer Pleasecontacttheexplorationowner '
null
null
null
null
Question: How does the code classify the answer ? Code: def classify(state, answer): assert feconf.ENABLE_STRING_CLASSIFIER interaction_instance = interaction_registry.Registry.get_interaction_by_id(state.interaction.id) normalized_answer = interaction_instance.normalize_answer(answer) response = None if interaction_instance.is_string_classifier_trainable: response = classify_string_classifier_rule(state, normalized_answer) else: raise Exception('No classifier found for interaction.') if (response is not None): return response elif (state.interaction.default_outcome is not None): return {'outcome': state.interaction.default_outcome.to_dict(), 'answer_group_index': len(state.interaction.answer_groups), 'classification_certainty': 0.0, 'rule_spec_index': 0} raise Exception('Something has seriously gone wrong with the exploration. Oppia does not know what to do with this answer. Please contact the exploration owner.')
null
null
null
What does the code ensure ?
def present(name, database, duration='7d', replication=1, default=False, **client_args): ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'retention policy {0} is already present'.format(name)} if (not __salt__['influxdb.retention_policy_exists'](name=name, database=database, **client_args)): if __opts__['test']: ret['result'] = None ret['comment'] = ' {0} is absent and will be created'.format(name) return ret if __salt__['influxdb.create_retention_policy'](database, name, duration, replication, default, **client_args): ret['comment'] = 'retention policy {0} has been created'.format(name) ret['changes'][name] = 'Present' return ret else: ret['comment'] = 'Failed to create retention policy {0}'.format(name) ret['result'] = False return ret return ret
null
null
null
that given retention policy is present
codeqa
def present name database duration '7 d' replication 1 default False **client args ret {'name' name 'changes' {} 'result' True 'comment' 'retentionpolicy{ 0 }isalreadypresent' format name }if not salt ['influxdb retention policy exists'] name name database database **client args if opts ['test'] ret['result'] Noneret['comment'] '{ 0 }isabsentandwillbecreated' format name return retif salt ['influxdb create retention policy'] database name duration replication default **client args ret['comment'] 'retentionpolicy{ 0 }hasbeencreated' format name ret['changes'][name] ' Present'return retelse ret['comment'] ' Failedtocreateretentionpolicy{ 0 }' format name ret['result'] Falsereturn retreturn ret
null
null
null
null
Question: What does the code ensure ? Code: def present(name, database, duration='7d', replication=1, default=False, **client_args): ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'retention policy {0} is already present'.format(name)} if (not __salt__['influxdb.retention_policy_exists'](name=name, database=database, **client_args)): if __opts__['test']: ret['result'] = None ret['comment'] = ' {0} is absent and will be created'.format(name) return ret if __salt__['influxdb.create_retention_policy'](database, name, duration, replication, default, **client_args): ret['comment'] = 'retention policy {0} has been created'.format(name) ret['changes'][name] = 'Present' return ret else: ret['comment'] = 'Failed to create retention policy {0}'.format(name) ret['result'] = False return ret return ret
null
null
null
What does the code delete ?
def delete_record(table, sys_id): client = _get_client() client.table = table response = client.delete(sys_id) return response
null
null
null
an existing record
codeqa
def delete record table sys id client get client client table tableresponse client delete sys id return response
null
null
null
null
Question: What does the code delete ? Code: def delete_record(table, sys_id): client = _get_client() client.table = table response = client.delete(sys_id) return response
null
null
null
What does all the rules from the environment compile ?
def compile_rules(environment): e = re.escape rules = [(len(environment.comment_start_string), 'comment', e(environment.comment_start_string)), (len(environment.block_start_string), 'block', e(environment.block_start_string)), (len(environment.variable_start_string), 'variable', e(environment.variable_start_string))] if (environment.line_statement_prefix is not None): rules.append((len(environment.line_statement_prefix), 'linestatement', ('^[ \\t\\v]*' + e(environment.line_statement_prefix)))) if (environment.line_comment_prefix is not None): rules.append((len(environment.line_comment_prefix), 'linecomment', ('(?:^|(?<=\\S))[^\\S\\r\\n]*' + e(environment.line_comment_prefix)))) return [x[1:] for x in sorted(rules, reverse=True)]
null
null
null
into a list of rules
codeqa
def compile rules environment e re escaperules [ len environment comment start string 'comment' e environment comment start string len environment block start string 'block' e environment block start string len environment variable start string 'variable' e environment variable start string ]if environment line statement prefix is not None rules append len environment line statement prefix 'linestatement' '^[\\t\\v]*' + e environment line statement prefix if environment line comment prefix is not None rules append len environment line comment prefix 'linecomment' ' ? ^ ?< \\S [^\\S\\r\\n]*' + e environment line comment prefix return [x[ 1 ] for x in sorted rules reverse True ]
null
null
null
null
Question: What does all the rules from the environment compile ? Code: def compile_rules(environment): e = re.escape rules = [(len(environment.comment_start_string), 'comment', e(environment.comment_start_string)), (len(environment.block_start_string), 'block', e(environment.block_start_string)), (len(environment.variable_start_string), 'variable', e(environment.variable_start_string))] if (environment.line_statement_prefix is not None): rules.append((len(environment.line_statement_prefix), 'linestatement', ('^[ \\t\\v]*' + e(environment.line_statement_prefix)))) if (environment.line_comment_prefix is not None): rules.append((len(environment.line_comment_prefix), 'linecomment', ('(?:^|(?<=\\S))[^\\S\\r\\n]*' + e(environment.line_comment_prefix)))) return [x[1:] for x in sorted(rules, reverse=True)]
null
null
null
What compiles into a list of rules ?
def compile_rules(environment): e = re.escape rules = [(len(environment.comment_start_string), 'comment', e(environment.comment_start_string)), (len(environment.block_start_string), 'block', e(environment.block_start_string)), (len(environment.variable_start_string), 'variable', e(environment.variable_start_string))] if (environment.line_statement_prefix is not None): rules.append((len(environment.line_statement_prefix), 'linestatement', ('^[ \\t\\v]*' + e(environment.line_statement_prefix)))) if (environment.line_comment_prefix is not None): rules.append((len(environment.line_comment_prefix), 'linecomment', ('(?:^|(?<=\\S))[^\\S\\r\\n]*' + e(environment.line_comment_prefix)))) return [x[1:] for x in sorted(rules, reverse=True)]
null
null
null
all the rules from the environment
codeqa
def compile rules environment e re escaperules [ len environment comment start string 'comment' e environment comment start string len environment block start string 'block' e environment block start string len environment variable start string 'variable' e environment variable start string ]if environment line statement prefix is not None rules append len environment line statement prefix 'linestatement' '^[\\t\\v]*' + e environment line statement prefix if environment line comment prefix is not None rules append len environment line comment prefix 'linecomment' ' ? ^ ?< \\S [^\\S\\r\\n]*' + e environment line comment prefix return [x[ 1 ] for x in sorted rules reverse True ]
null
null
null
null
Question: What compiles into a list of rules ? Code: def compile_rules(environment): e = re.escape rules = [(len(environment.comment_start_string), 'comment', e(environment.comment_start_string)), (len(environment.block_start_string), 'block', e(environment.block_start_string)), (len(environment.variable_start_string), 'variable', e(environment.variable_start_string))] if (environment.line_statement_prefix is not None): rules.append((len(environment.line_statement_prefix), 'linestatement', ('^[ \\t\\v]*' + e(environment.line_statement_prefix)))) if (environment.line_comment_prefix is not None): rules.append((len(environment.line_comment_prefix), 'linecomment', ('(?:^|(?<=\\S))[^\\S\\r\\n]*' + e(environment.line_comment_prefix)))) return [x[1:] for x in sorted(rules, reverse=True)]
null
null
null
What do an equivalent expression satisfy ?
def riemann_cyclic(t2): if isinstance(t2, (TensMul, Tensor)): args = [t2] else: args = t2.args a1 = [x.split() for x in args] a2 = [[riemann_cyclic_replace(tx) for tx in y] for y in a1] a3 = [tensor_mul(*v) for v in a2] t3 = TensAdd(*a3) if (not t3): return t3 else: return canon_bp(t3)
null
null
null
the cyclic identity
codeqa
def riemann cyclic t2 if isinstance t2 Tens Mul Tensor args [t 2 ]else args t2 argsa 1 [x split for x in args]a 2 [[riemann cyclic replace tx for tx in y] for y in a1 ]a 3 [tensor mul *v for v in a2 ]t 3 Tens Add *a 3 if not t3 return t3 else return canon bp t3
null
null
null
null
Question: What do an equivalent expression satisfy ? Code: def riemann_cyclic(t2): if isinstance(t2, (TensMul, Tensor)): args = [t2] else: args = t2.args a1 = [x.split() for x in args] a2 = [[riemann_cyclic_replace(tx) for tx in y] for y in a1] a3 = [tensor_mul(*v) for v in a2] t3 = TensAdd(*a3) if (not t3): return t3 else: return canon_bp(t3)
null
null
null
What is satisfying the cyclic identity ?
def riemann_cyclic(t2): if isinstance(t2, (TensMul, Tensor)): args = [t2] else: args = t2.args a1 = [x.split() for x in args] a2 = [[riemann_cyclic_replace(tx) for tx in y] for y in a1] a3 = [tensor_mul(*v) for v in a2] t3 = TensAdd(*a3) if (not t3): return t3 else: return canon_bp(t3)
null
null
null
an equivalent expression
codeqa
def riemann cyclic t2 if isinstance t2 Tens Mul Tensor args [t 2 ]else args t2 argsa 1 [x split for x in args]a 2 [[riemann cyclic replace tx for tx in y] for y in a1 ]a 3 [tensor mul *v for v in a2 ]t 3 Tens Add *a 3 if not t3 return t3 else return canon bp t3
null
null
null
null
Question: What is satisfying the cyclic identity ? Code: def riemann_cyclic(t2): if isinstance(t2, (TensMul, Tensor)): args = [t2] else: args = t2.args a1 = [x.split() for x in args] a2 = [[riemann_cyclic_replace(tx) for tx in y] for y in a1] a3 = [tensor_mul(*v) for v in a2] t3 = TensAdd(*a3) if (not t3): return t3 else: return canon_bp(t3)
null
null
null
What does the code take ?
def split_input(val): if isinstance(val, list): return val try: return [x.strip() for x in val.split(',')] except AttributeError: return [x.strip() for x in str(val).split(',')]
null
null
null
an input value
codeqa
def split input val if isinstance val list return valtry return [x strip for x in val split ' ' ]except Attribute Error return [x strip for x in str val split ' ' ]
null
null
null
null
Question: What does the code take ? Code: def split_input(val): if isinstance(val, list): return val try: return [x.strip() for x in val.split(',')] except AttributeError: return [x.strip() for x in str(val).split(',')]
null
null
null
What did the code set ?
def setup_test_db(): db.upgradeDatabase(db.DBConnection(), mainDB.InitialSchema) db.sanityCheckDatabase(db.DBConnection(), mainDB.MainSanityCheck) db.upgradeDatabase(db.DBConnection('cache.db'), cache_db.InitialSchema) db.upgradeDatabase(db.DBConnection('failed.db'), failed_db.InitialSchema)
null
null
null
the test databases
codeqa
def setup test db db upgrade Database db DB Connection main DB Initial Schema db sanity Check Database db DB Connection main DB Main Sanity Check db upgrade Database db DB Connection 'cache db' cache db Initial Schema db upgrade Database db DB Connection 'failed db' failed db Initial Schema
null
null
null
null
Question: What did the code set ? Code: def setup_test_db(): db.upgradeDatabase(db.DBConnection(), mainDB.InitialSchema) db.sanityCheckDatabase(db.DBConnection(), mainDB.MainSanityCheck) db.upgradeDatabase(db.DBConnection('cache.db'), cache_db.InitialSchema) db.upgradeDatabase(db.DBConnection('failed.db'), failed_db.InitialSchema)
null
null
null
How do each row of a sparse matrix scale ?
def row_scale(x, s): return col_scale(x.T, s).T
null
null
null
by the corresponding element of a dense vector
codeqa
def row scale x s return col scale x T s T
null
null
null
null
Question: How do each row of a sparse matrix scale ? Code: def row_scale(x, s): return col_scale(x.T, s).T
null
null
null
What does the code add to the given trace ?
def _add_billed_op_to_trace(trace, num_ops, op): if num_ops: billed_op = trace.add_billed_ops() billed_op.set_num_ops(num_ops) billed_op.set_op(op)
null
null
null
a billed op
codeqa
def add billed op to trace trace num ops op if num ops billed op trace add billed ops billed op set num ops num ops billed op set op op
null
null
null
null
Question: What does the code add to the given trace ? Code: def _add_billed_op_to_trace(trace, num_ops, op): if num_ops: billed_op = trace.add_billed_ops() billed_op.set_num_ops(num_ops) billed_op.set_op(op)
null
null
null
How does the code get metric from list in this module ?
def get_cup_metric(name): for metric in cup_metrics: if (metric.__name__.lower() == name.lower()): return metric raise AttributeError
null
null
null
by name
codeqa
def get cup metric name for metric in cup metrics if metric name lower name lower return metricraise Attribute Error
null
null
null
null
Question: How does the code get metric from list in this module ? Code: def get_cup_metric(name): for metric in cup_metrics: if (metric.__name__.lower() == name.lower()): return metric raise AttributeError
null
null
null
Where does this function find the date ?
def _closest_date(target_dt, date_list, before_target=None): fb = (lambda d: ((d - target_dt) if (d >= target_dt) else datetime.timedelta.max)) fa = (lambda d: ((d - target_dt) if (d <= target_dt) else datetime.timedelta.min)) fnone = (lambda d: ((target_dt - d) if (d < target_dt) else (d - target_dt))) if (before_target is None): return min(date_list, key=fnone).date() if before_target: return min(date_list, key=fb).date() else: return min(date_list, key=fa).date()
null
null
null
in a list closest to the target date
codeqa
def closest date target dt date list before target None fb lambda d d - target dt if d > target dt else datetime timedelta max fa lambda d d - target dt if d < target dt else datetime timedelta min fnone lambda d target dt - d if d < target dt else d - target dt if before target is None return min date list key fnone date if before target return min date list key fb date else return min date list key fa date
null
null
null
null
Question: Where does this function find the date ? Code: def _closest_date(target_dt, date_list, before_target=None): fb = (lambda d: ((d - target_dt) if (d >= target_dt) else datetime.timedelta.max)) fa = (lambda d: ((d - target_dt) if (d <= target_dt) else datetime.timedelta.min)) fnone = (lambda d: ((target_dt - d) if (d < target_dt) else (d - target_dt))) if (before_target is None): return min(date_list, key=fnone).date() if before_target: return min(date_list, key=fb).date() else: return min(date_list, key=fa).date()
null
null
null
What does this function find in a list closest to the target date ?
def _closest_date(target_dt, date_list, before_target=None): fb = (lambda d: ((d - target_dt) if (d >= target_dt) else datetime.timedelta.max)) fa = (lambda d: ((d - target_dt) if (d <= target_dt) else datetime.timedelta.min)) fnone = (lambda d: ((target_dt - d) if (d < target_dt) else (d - target_dt))) if (before_target is None): return min(date_list, key=fnone).date() if before_target: return min(date_list, key=fb).date() else: return min(date_list, key=fa).date()
null
null
null
the date
codeqa
def closest date target dt date list before target None fb lambda d d - target dt if d > target dt else datetime timedelta max fa lambda d d - target dt if d < target dt else datetime timedelta min fnone lambda d target dt - d if d < target dt else d - target dt if before target is None return min date list key fnone date if before target return min date list key fb date else return min date list key fa date
null
null
null
null
Question: What does this function find in a list closest to the target date ? Code: def _closest_date(target_dt, date_list, before_target=None): fb = (lambda d: ((d - target_dt) if (d >= target_dt) else datetime.timedelta.max)) fa = (lambda d: ((d - target_dt) if (d <= target_dt) else datetime.timedelta.min)) fnone = (lambda d: ((target_dt - d) if (d < target_dt) else (d - target_dt))) if (before_target is None): return min(date_list, key=fnone).date() if before_target: return min(date_list, key=fb).date() else: return min(date_list, key=fa).date()
null
null
null
What does the code create ?
def host_create(host, groups, interfaces, **connection_args): conn_args = _login(**connection_args) try: if conn_args: method = 'host.create' params = {'host': host} if (not isinstance(groups, list)): groups = [groups] grps = [] for group in groups: grps.append({'groupid': group}) params['groups'] = grps if (not isinstance(interfaces, list)): interfaces = [interfaces] params['interfaces'] = interfaces params = _params_extend(params, _ignore_name=True, **connection_args) ret = _query(method, params, conn_args['url'], conn_args['auth']) return ret['result']['hostids'] else: raise KeyError except KeyError: return ret
null
null
null
new host
codeqa
def host create host groups interfaces **connection args conn args login **connection args try if conn args method 'host create'params {'host' host}if not isinstance groups list groups [groups]grps []for group in groups grps append {'groupid' group} params['groups'] grpsif not isinstance interfaces list interfaces [interfaces]params['interfaces'] interfacesparams params extend params ignore name True **connection args ret query method params conn args['url'] conn args['auth'] return ret['result']['hostids']else raise Key Errorexcept Key Error return ret
null
null
null
null
Question: What does the code create ? Code: def host_create(host, groups, interfaces, **connection_args): conn_args = _login(**connection_args) try: if conn_args: method = 'host.create' params = {'host': host} if (not isinstance(groups, list)): groups = [groups] grps = [] for group in groups: grps.append({'groupid': group}) params['groups'] = grps if (not isinstance(interfaces, list)): interfaces = [interfaces] params['interfaces'] = interfaces params = _params_extend(params, _ignore_name=True, **connection_args) ret = _query(method, params, conn_args['url'], conn_args['auth']) return ret['result']['hostids'] else: raise KeyError except KeyError: return ret
null
null
null
What did the code avoid ?
def safewrite(filename, content): f = file((filename + '.tmp'), 'w') f.write(content) f.close() os.rename(f.name, filename)
null
null
null
overwriting the existing file in case of errors
codeqa
def safewrite filename content f file filename + ' tmp' 'w' f write content f close os rename f name filename
null
null
null
null
Question: What did the code avoid ? Code: def safewrite(filename, content): f = file((filename + '.tmp'), 'w') f.write(content) f.close() os.rename(f.name, filename)
null
null
null
What does the code write to a temp file ?
def safewrite(filename, content): f = file((filename + '.tmp'), 'w') f.write(content) f.close() os.rename(f.name, filename)
null
null
null
the content
codeqa
def safewrite filename content f file filename + ' tmp' 'w' f write content f close os rename f name filename
null
null
null
null
Question: What does the code write to a temp file ? Code: def safewrite(filename, content): f = file((filename + '.tmp'), 'w') f.write(content) f.close() os.rename(f.name, filename)
null
null
null
What does the code overwrite in case of errors ?
def safewrite(filename, content): f = file((filename + '.tmp'), 'w') f.write(content) f.close() os.rename(f.name, filename)
null
null
null
the existing file
codeqa
def safewrite filename content f file filename + ' tmp' 'w' f write content f close os rename f name filename
null
null
null
null
Question: What does the code overwrite in case of errors ? Code: def safewrite(filename, content): f = file((filename + '.tmp'), 'w') f.write(content) f.close() os.rename(f.name, filename)
null
null
null
What does the code create ?
def buildSequencePool(numSequences=10, seqLen=[2, 3, 4], numPatterns=5, numOnBitsPerPattern=3, patternOverlap=0, **kwargs): patterns = getSimplePatterns(numOnBitsPerPattern, numPatterns, patternOverlap) numCols = len(patterns[0]) trainingSequences = [] for _ in xrange(numSequences): sequence = [] length = random.choice(seqLen) for _ in xrange(length): patIdx = random.choice(xrange(numPatterns)) sequence.append(patterns[patIdx]) trainingSequences.append(sequence) if (VERBOSITY >= 3): print '\nTraining sequences' printAllTrainingSequences(trainingSequences) return (numCols, trainingSequences)
null
null
null
a bunch of sequences of various lengths
codeqa
def build Sequence Pool num Sequences 10 seq Len [2 3 4] num Patterns 5 num On Bits Per Pattern 3 pattern Overlap 0 **kwargs patterns get Simple Patterns num On Bits Per Pattern num Patterns pattern Overlap num Cols len patterns[ 0 ] training Sequences []for in xrange num Sequences sequence []length random choice seq Len for in xrange length pat Idx random choice xrange num Patterns sequence append patterns[pat Idx] training Sequences append sequence if VERBOSITY > 3 print '\n Trainingsequences'print All Training Sequences training Sequences return num Cols training Sequences
null
null
null
null
Question: What does the code create ? Code: def buildSequencePool(numSequences=10, seqLen=[2, 3, 4], numPatterns=5, numOnBitsPerPattern=3, patternOverlap=0, **kwargs): patterns = getSimplePatterns(numOnBitsPerPattern, numPatterns, patternOverlap) numCols = len(patterns[0]) trainingSequences = [] for _ in xrange(numSequences): sequence = [] length = random.choice(seqLen) for _ in xrange(length): patIdx = random.choice(xrange(numPatterns)) sequence.append(patterns[patIdx]) trainingSequences.append(sequence) if (VERBOSITY >= 3): print '\nTraining sequences' printAllTrainingSequences(trainingSequences) return (numCols, trainingSequences)
null
null
null
What does the code perform ?
def wiener(im, mysize=None, noise=None): im = asarray(im) if (mysize is None): mysize = ([3] * im.ndim) mysize = asarray(mysize) if (mysize.shape == ()): mysize = np.repeat(mysize.item(), im.ndim) lMean = (correlate(im, ones(mysize), 'same') / product(mysize, axis=0)) lVar = ((correlate((im ** 2), ones(mysize), 'same') / product(mysize, axis=0)) - (lMean ** 2)) if (noise is None): noise = mean(ravel(lVar), axis=0) res = (im - lMean) res *= (1 - (noise / lVar)) res += lMean out = where((lVar < noise), lMean, res) return out
null
null
null
a wiener filter on an n - dimensional array
codeqa
def wiener im mysize None noise None im asarray im if mysize is None mysize [3 ] * im ndim mysize asarray mysize if mysize shape mysize np repeat mysize item im ndim l Mean correlate im ones mysize 'same' / product mysize axis 0 l Var correlate im ** 2 ones mysize 'same' / product mysize axis 0 - l Mean ** 2 if noise is None noise mean ravel l Var axis 0 res im - l Mean res * 1 - noise / l Var res + l Meanout where l Var < noise l Mean res return out
null
null
null
null
Question: What does the code perform ? Code: def wiener(im, mysize=None, noise=None): im = asarray(im) if (mysize is None): mysize = ([3] * im.ndim) mysize = asarray(mysize) if (mysize.shape == ()): mysize = np.repeat(mysize.item(), im.ndim) lMean = (correlate(im, ones(mysize), 'same') / product(mysize, axis=0)) lVar = ((correlate((im ** 2), ones(mysize), 'same') / product(mysize, axis=0)) - (lMean ** 2)) if (noise is None): noise = mean(ravel(lVar), axis=0) res = (im - lMean) res *= (1 - (noise / lVar)) res += lMean out = where((lVar < noise), lMean, res) return out
null
null
null
What does the code get from the registry ?
def _get_string(path, base=win32con.HKEY_CLASSES_ROOT): try: return win32api.RegQueryValue(base, path) except win32api.error: return None
null
null
null
a string value
codeqa
def get string path base win 32 con HKEY CLASSES ROOT try return win 32 api Reg Query Value base path except win 32 api error return None
null
null
null
null
Question: What does the code get from the registry ? Code: def _get_string(path, base=win32con.HKEY_CLASSES_ROOT): try: return win32api.RegQueryValue(base, path) except win32api.error: return None
null
null
null
What does the code get from multiplier ?
def getVector3ByMultiplierPrefix(elementNode, multiplier, prefix, vector3): if (multiplier == 0.0): return vector3 oldMultipliedValueVector3 = (vector3 * multiplier) vector3ByPrefix = getVector3ByPrefix(oldMultipliedValueVector3.copy(), elementNode, prefix) if (vector3ByPrefix == oldMultipliedValueVector3): return vector3 return (vector3ByPrefix / multiplier)
null
null
null
vector3
codeqa
def get Vector 3 By Multiplier Prefix element Node multiplier prefix vector 3 if multiplier 0 0 return vector 3 old Multiplied Value Vector 3 vector 3 * multiplier vector 3 By Prefix get Vector 3 By Prefix old Multiplied Value Vector 3 copy element Node prefix if vector 3 By Prefix old Multiplied Value Vector 3 return vector 3 return vector 3 By Prefix / multiplier
null
null
null
null
Question: What does the code get from multiplier ? Code: def getVector3ByMultiplierPrefix(elementNode, multiplier, prefix, vector3): if (multiplier == 0.0): return vector3 oldMultipliedValueVector3 = (vector3 * multiplier) vector3ByPrefix = getVector3ByPrefix(oldMultipliedValueVector3.copy(), elementNode, prefix) if (vector3ByPrefix == oldMultipliedValueVector3): return vector3 return (vector3ByPrefix / multiplier)
null
null
null
What does the code resize ?
def imresize(arr, size, interp='bilinear', mode=None): im = toimage(arr, mode=mode) ts = type(size) if issubdtype(ts, int): percent = (size / 100.0) size = tuple((array(im.size) * percent).astype(int)) elif issubdtype(type(size), float): size = tuple((array(im.size) * size).astype(int)) else: size = (size[1], size[0]) func = {'nearest': 0, 'lanczos': 1, 'bilinear': 2, 'bicubic': 3, 'cubic': 3} imnew = im.resize(size, resample=func[interp]) return fromimage(imnew)
null
null
null
an image
codeqa
def imresize arr size interp 'bilinear' mode None im toimage arr mode mode ts type size if issubdtype ts int percent size / 100 0 size tuple array im size * percent astype int elif issubdtype type size float size tuple array im size * size astype int else size size[ 1 ] size[ 0 ] func {'nearest' 0 'lanczos' 1 'bilinear' 2 'bicubic' 3 'cubic' 3}imnew im resize size resample func[interp] return fromimage imnew
null
null
null
null
Question: What does the code resize ? Code: def imresize(arr, size, interp='bilinear', mode=None): im = toimage(arr, mode=mode) ts = type(size) if issubdtype(ts, int): percent = (size / 100.0) size = tuple((array(im.size) * percent).astype(int)) elif issubdtype(type(size), float): size = tuple((array(im.size) * size).astype(int)) else: size = (size[1], size[0]) func = {'nearest': 0, 'lanczos': 1, 'bilinear': 2, 'bicubic': 3, 'cubic': 3} imnew = im.resize(size, resample=func[interp]) return fromimage(imnew)
null
null
null
What does this function encode ?
def encode_block(payload, requester, responder): assert (len(requester[1].public_key) == PK_LENGTH) assert (len(responder[1].public_key) == PK_LENGTH) return pack(crawl_response_format, *(payload.up, payload.down, payload.total_up_requester, payload.total_down_requester, payload.sequence_number_requester, payload.previous_hash_requester, payload.total_up_responder, payload.total_down_responder, payload.sequence_number_responder, payload.previous_hash_responder, requester[1].public_key, requester[0], responder[1].public_key, responder[0]))
null
null
null
a block
codeqa
def encode block payload requester responder assert len requester[ 1 ] public key PK LENGTH assert len responder[ 1 ] public key PK LENGTH return pack crawl response format * payload up payload down payload total up requester payload total down requester payload sequence number requester payload previous hash requester payload total up responder payload total down responder payload sequence number responder payload previous hash responder requester[ 1 ] public key requester[ 0 ] responder[ 1 ] public key responder[ 0 ]
null
null
null
null
Question: What does this function encode ? Code: def encode_block(payload, requester, responder): assert (len(requester[1].public_key) == PK_LENGTH) assert (len(responder[1].public_key) == PK_LENGTH) return pack(crawl_response_format, *(payload.up, payload.down, payload.total_up_requester, payload.total_down_requester, payload.sequence_number_requester, payload.previous_hash_requester, payload.total_up_responder, payload.total_down_responder, payload.sequence_number_responder, payload.previous_hash_responder, requester[1].public_key, requester[0], responder[1].public_key, responder[0]))
null
null
null
When can it retry ?
def wrap_aws_conn(raw_conn): def retry_if(ex): 'Retry if we get a server error indicating throttling. Also\n handle spurious 505s that are thought to be part of a load\n balancer issue inside AWS.' return ((isinstance(ex, boto.exception.BotoServerError) and (('Throttling' in ex.body) or ('RequestExpired' in ex.body) or (ex.status == 505))) or (isinstance(ex, socket.error) and (ex.args in ((104, 'Connection reset by peer'), (110, 'Connection timed out'))))) return RetryWrapper(raw_conn, retry_if=retry_if, backoff=_EMR_BACKOFF, multiplier=_EMR_BACKOFF_MULTIPLIER, max_tries=_EMR_MAX_TRIES)
null
null
null
when throttled
codeqa
def wrap aws conn raw conn def retry if ex ' Retryifwegetaservererrorindicatingthrottling Also\nhandlespurious 505 sthatarethoughttobepartofaload\nbalancerissueinside AWS 'return isinstance ex boto exception Boto Server Error and ' Throttling' in ex body or ' Request Expired' in ex body or ex status 505 or isinstance ex socket error and ex args in 104 ' Connectionresetbypeer' 110 ' Connectiontimedout' return Retry Wrapper raw conn retry if retry if backoff EMR BACKOFF multiplier EMR BACKOFF MULTIPLIER max tries EMR MAX TRIES
null
null
null
null
Question: When can it retry ? Code: def wrap_aws_conn(raw_conn): def retry_if(ex): 'Retry if we get a server error indicating throttling. Also\n handle spurious 505s that are thought to be part of a load\n balancer issue inside AWS.' return ((isinstance(ex, boto.exception.BotoServerError) and (('Throttling' in ex.body) or ('RequestExpired' in ex.body) or (ex.status == 505))) or (isinstance(ex, socket.error) and (ex.args in ((104, 'Connection reset by peer'), (110, 'Connection timed out'))))) return RetryWrapper(raw_conn, retry_if=retry_if, backoff=_EMR_BACKOFF, multiplier=_EMR_BACKOFF_MULTIPLIER, max_tries=_EMR_MAX_TRIES)
null
null
null
What does the code create ?
def create_hash_map(): hashmap = {} from base64 import encodestring as base64 import pwd login_name = pwd.getpwuid(os.geteuid())[0] conn = http.client.HTTPSConnection(u'api.github.com') conn.request(u'GET', u'/repos/nipy/nipype', headers={u'Authorization': (u'Basic %s' % base64(login_name))}) try: conn.request(u'GET', u'/repos/nipy/nipype/git/trees/master?recursive=1') except: pass else: r1 = conn.getresponse() if (r1.reason != u'OK'): raise Exception((u'HTTP Response %s:%s' % (r1.status, r1.reason))) payload = simplejson.loads(r1.read()) for infodict in payload[u'tree']: if (infodict[u'type'] == u'blob'): hashmap[infodict[u'sha']] = infodict[u'path'] return hashmap
null
null
null
a hash map for all objects
codeqa
def create hash map hashmap {}from base 64 import encodestring as base 64 import pwdlogin name pwd getpwuid os geteuid [0 ]conn http client HTTPS Connection u'api github com' conn request u'GET' u'/repos/nipy/nipype' headers {u' Authorization' u' Basic%s' % base 64 login name } try conn request u'GET' u'/repos/nipy/nipype/git/trees/master?recursive 1' except passelse r1 conn getresponse if r1 reason u'OK' raise Exception u'HTTP Response%s %s' % r1 status r1 reason payload simplejson loads r1 read for infodict in payload[u'tree'] if infodict[u'type'] u'blob' hashmap[infodict[u'sha']] infodict[u'path']return hashmap
null
null
null
null
Question: What does the code create ? Code: def create_hash_map(): hashmap = {} from base64 import encodestring as base64 import pwd login_name = pwd.getpwuid(os.geteuid())[0] conn = http.client.HTTPSConnection(u'api.github.com') conn.request(u'GET', u'/repos/nipy/nipype', headers={u'Authorization': (u'Basic %s' % base64(login_name))}) try: conn.request(u'GET', u'/repos/nipy/nipype/git/trees/master?recursive=1') except: pass else: r1 = conn.getresponse() if (r1.reason != u'OK'): raise Exception((u'HTTP Response %s:%s' % (r1.status, r1.reason))) payload = simplejson.loads(r1.read()) for infodict in payload[u'tree']: if (infodict[u'type'] == u'blob'): hashmap[infodict[u'sha']] = infodict[u'path'] return hashmap
null
null
null
How do an attribute add into the instance dictionary ?
def _set(obj, attribute, value): obj.__dict__[attribute] = value
null
null
null
directly
codeqa
def set obj attribute value obj dict [attribute] value
null
null
null
null
Question: How do an attribute add into the instance dictionary ? Code: def _set(obj, attribute, value): obj.__dict__[attribute] = value