id_within_dataset
int64
1
55.5k
snippet
stringlengths
19
14.2k
tokens
listlengths
6
1.63k
nl
stringlengths
6
352
split_within_dataset
stringclasses
1 value
is_duplicated
bool
2 classes
20,505
def SpaceSeparatedTokenizer(): return RegexTokenizer('[^ \\t\\r\\n]+')
[ "def", "SpaceSeparatedTokenizer", "(", ")", ":", "return", "RegexTokenizer", "(", "'[^ \\\\t\\\\r\\\\n]+'", ")" ]
returns a regextokenizer that splits tokens by whitespace .
train
false
20,506
def concat_xml(file_list): checksum = hashlib.new('sha1') if (not file_list): return ('', checksum.hexdigest()) root = None for fname in file_list: with open(fname, 'rb') as fp: contents = fp.read() checksum.update(contents) fp.seek(0) xml = ElementTree.parse(fp).getroot() if (root is None): root = ElementTree.Element(xml.tag) for child in xml.getchildren(): root.append(child) return (ElementTree.tostring(root, 'utf-8'), checksum.hexdigest())
[ "def", "concat_xml", "(", "file_list", ")", ":", "checksum", "=", "hashlib", ".", "new", "(", "'sha1'", ")", "if", "(", "not", "file_list", ")", ":", "return", "(", "''", ",", "checksum", ".", "hexdigest", "(", ")", ")", "root", "=", "None", "for", "fname", "in", "file_list", ":", "with", "open", "(", "fname", ",", "'rb'", ")", "as", "fp", ":", "contents", "=", "fp", ".", "read", "(", ")", "checksum", ".", "update", "(", "contents", ")", "fp", ".", "seek", "(", "0", ")", "xml", "=", "ElementTree", ".", "parse", "(", "fp", ")", ".", "getroot", "(", ")", "if", "(", "root", "is", "None", ")", ":", "root", "=", "ElementTree", ".", "Element", "(", "xml", ".", "tag", ")", "for", "child", "in", "xml", ".", "getchildren", "(", ")", ":", "root", ".", "append", "(", "child", ")", "return", "(", "ElementTree", ".", "tostring", "(", "root", ",", "'utf-8'", ")", ",", "checksum", ".", "hexdigest", "(", ")", ")" ]
concatenate xml files .
train
false
20,508
def find_executable_in_dir(dirname=None): if (platform.system() == 'Windows'): exe_name = 'caffe.exe' else: exe_name = 'caffe' if (dirname is None): dirnames = [path.strip('"\' ') for path in os.environ['PATH'].split(os.pathsep)] else: dirnames = [dirname] for dirname in dirnames: path = os.path.join(dirname, exe_name) if (os.path.isfile(path) and os.access(path, os.X_OK)): return path return None
[ "def", "find_executable_in_dir", "(", "dirname", "=", "None", ")", ":", "if", "(", "platform", ".", "system", "(", ")", "==", "'Windows'", ")", ":", "exe_name", "=", "'caffe.exe'", "else", ":", "exe_name", "=", "'caffe'", "if", "(", "dirname", "is", "None", ")", ":", "dirnames", "=", "[", "path", ".", "strip", "(", "'\"\\' '", ")", "for", "path", "in", "os", ".", "environ", "[", "'PATH'", "]", ".", "split", "(", "os", ".", "pathsep", ")", "]", "else", ":", "dirnames", "=", "[", "dirname", "]", "for", "dirname", "in", "dirnames", ":", "path", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "exe_name", ")", "if", "(", "os", ".", "path", ".", "isfile", "(", "path", ")", "and", "os", ".", "access", "(", "path", ",", "os", ".", "X_OK", ")", ")", ":", "return", "path", "return", "None" ]
returns the path to the caffe executable at dirname if dirname is none .
train
false
20,509
def get_exploration_titles_and_categories(exp_ids): explorations = [(get_exploration_from_model(e) if e else None) for e in exp_models.ExplorationModel.get_multi(exp_ids)] result = {} for exploration in explorations: if (exploration is None): logging.error('Could not find exploration corresponding to id') else: result[exploration.id] = {'title': exploration.title, 'category': exploration.category} return result
[ "def", "get_exploration_titles_and_categories", "(", "exp_ids", ")", ":", "explorations", "=", "[", "(", "get_exploration_from_model", "(", "e", ")", "if", "e", "else", "None", ")", "for", "e", "in", "exp_models", ".", "ExplorationModel", ".", "get_multi", "(", "exp_ids", ")", "]", "result", "=", "{", "}", "for", "exploration", "in", "explorations", ":", "if", "(", "exploration", "is", "None", ")", ":", "logging", ".", "error", "(", "'Could not find exploration corresponding to id'", ")", "else", ":", "result", "[", "exploration", ".", "id", "]", "=", "{", "'title'", ":", "exploration", ".", "title", ",", "'category'", ":", "exploration", ".", "category", "}", "return", "result" ]
returns exploration titles and categories for the given ids .
train
false
20,510
def c12_mapping(char): return (u' ' if stringprep.in_table_c12(char) else None)
[ "def", "c12_mapping", "(", "char", ")", ":", "return", "(", "u' '", "if", "stringprep", ".", "in_table_c12", "(", "char", ")", "else", "None", ")" ]
map non-ascii whitespace to spaces .
train
false
20,512
@LocalContext def get_qemu_user(): arch = get_qemu_arch() normal = ('qemu-' + arch) static = (normal + '-static') if misc.which(static): return static if misc.which(normal): return normal log.warn_once(('Neither %r nor %r are available' % (normal, static)))
[ "@", "LocalContext", "def", "get_qemu_user", "(", ")", ":", "arch", "=", "get_qemu_arch", "(", ")", "normal", "=", "(", "'qemu-'", "+", "arch", ")", "static", "=", "(", "normal", "+", "'-static'", ")", "if", "misc", ".", "which", "(", "static", ")", ":", "return", "static", "if", "misc", ".", "which", "(", "normal", ")", ":", "return", "normal", "log", ".", "warn_once", "(", "(", "'Neither %r nor %r are available'", "%", "(", "normal", ",", "static", ")", ")", ")" ]
returns the path to the qemu-user binary for the currently selected architecture .
train
false
20,513
def read_uint64(fid): return _unpack_simple(fid, '>u8', np.uint64)
[ "def", "read_uint64", "(", "fid", ")", ":", "return", "_unpack_simple", "(", "fid", ",", "'>u8'", ",", "np", ".", "uint64", ")" ]
read unsigned 64bit integer from bti file .
train
false
20,514
def get_path_parts(path): if (not path): return [] parent = os.path.split(path)[0] parent_parts = parent.split(u'/') if ((len(parent_parts) == 1) and (parent_parts[0] == u'')): parts = [] else: parts = [u'/'.join((parent_parts[:(parent_parts.index(part) + 1)] + [''])) for part in parent_parts] if (path not in parts): parts.append(path) parts.insert(0, u'') return parts
[ "def", "get_path_parts", "(", "path", ")", ":", "if", "(", "not", "path", ")", ":", "return", "[", "]", "parent", "=", "os", ".", "path", ".", "split", "(", "path", ")", "[", "0", "]", "parent_parts", "=", "parent", ".", "split", "(", "u'/'", ")", "if", "(", "(", "len", "(", "parent_parts", ")", "==", "1", ")", "and", "(", "parent_parts", "[", "0", "]", "==", "u''", ")", ")", ":", "parts", "=", "[", "]", "else", ":", "parts", "=", "[", "u'/'", ".", "join", "(", "(", "parent_parts", "[", ":", "(", "parent_parts", ".", "index", "(", "part", ")", "+", "1", ")", "]", "+", "[", "''", "]", ")", ")", "for", "part", "in", "parent_parts", "]", "if", "(", "path", "not", "in", "parts", ")", ":", "parts", ".", "append", "(", "path", ")", "parts", ".", "insert", "(", "0", ",", "u''", ")", "return", "parts" ]
returns a list of paths parent paths plus path .
train
false
20,515
def p_command_for_bad_final(p): p[0] = 'BAD FINAL VALUE IN FOR STATEMENT'
[ "def", "p_command_for_bad_final", "(", "p", ")", ":", "p", "[", "0", "]", "=", "'BAD FINAL VALUE IN FOR STATEMENT'" ]
command : for id equals expr to error optstep .
train
false
20,516
def fields_to_dict(lines, delim=' DCTB ', strip_f=strip): result = {} for line in lines: if strip_f: fields = map(strip_f, line.split(delim)) else: fields = line.split(delim) if (not fields[0]): continue result[fields[0]] = fields[1:] return result
[ "def", "fields_to_dict", "(", "lines", ",", "delim", "=", "' DCTB '", ",", "strip_f", "=", "strip", ")", ":", "result", "=", "{", "}", "for", "line", "in", "lines", ":", "if", "strip_f", ":", "fields", "=", "map", "(", "strip_f", ",", "line", ".", "split", "(", "delim", ")", ")", "else", ":", "fields", "=", "line", ".", "split", "(", "delim", ")", "if", "(", "not", "fields", "[", "0", "]", ")", ":", "continue", "result", "[", "fields", "[", "0", "]", "]", "=", "fields", "[", "1", ":", "]", "return", "result" ]
makes a dict where first field is key .
train
false
20,517
def sprint(text, *colors): return ('\x1b[{}m{content}\x1b[{}m'.format(';'.join([str(color) for color in colors]), RESET, content=text) if (IS_ANSI_TERMINAL and colors) else text)
[ "def", "sprint", "(", "text", ",", "*", "colors", ")", ":", "return", "(", "'\\x1b[{}m{content}\\x1b[{}m'", ".", "format", "(", "';'", ".", "join", "(", "[", "str", "(", "color", ")", "for", "color", "in", "colors", "]", ")", ",", "RESET", ",", "content", "=", "text", ")", "if", "(", "IS_ANSI_TERMINAL", "and", "colors", ")", "else", "text", ")" ]
format text with color or other effects into ansi escaped string .
train
true
20,520
def _create_hierarchies(metadata, levels, template): levels = object_dict(levels) hierarchies = [] for md in metadata: if isinstance(md, compat.string_type): if (not template): raise ModelError('Can not specify just a hierarchy name ({}) if there is no template'.format(md)) hier = template.hierarchy(md) else: md = dict(md) level_names = md.pop('levels') hier_levels = [levels[level] for level in level_names] hier = Hierarchy(levels=hier_levels, **md) hierarchies.append(hier) return hierarchies
[ "def", "_create_hierarchies", "(", "metadata", ",", "levels", ",", "template", ")", ":", "levels", "=", "object_dict", "(", "levels", ")", "hierarchies", "=", "[", "]", "for", "md", "in", "metadata", ":", "if", "isinstance", "(", "md", ",", "compat", ".", "string_type", ")", ":", "if", "(", "not", "template", ")", ":", "raise", "ModelError", "(", "'Can not specify just a hierarchy name ({}) if there is no template'", ".", "format", "(", "md", ")", ")", "hier", "=", "template", ".", "hierarchy", "(", "md", ")", "else", ":", "md", "=", "dict", "(", "md", ")", "level_names", "=", "md", ".", "pop", "(", "'levels'", ")", "hier_levels", "=", "[", "levels", "[", "level", "]", "for", "level", "in", "level_names", "]", "hier", "=", "Hierarchy", "(", "levels", "=", "hier_levels", ",", "**", "md", ")", "hierarchies", ".", "append", "(", "hier", ")", "return", "hierarchies" ]
create dimension hierarchies from metadata and possibly inherit from template dimension .
train
false
20,521
def to_naive_utc_dt(dt): if (not isinstance(dt, datetime)): raise TypeError('Arg must be type datetime') if (dt.tzinfo is None): return dt return dt.astimezone(pytz.utc).replace(tzinfo=None)
[ "def", "to_naive_utc_dt", "(", "dt", ")", ":", "if", "(", "not", "isinstance", "(", "dt", ",", "datetime", ")", ")", ":", "raise", "TypeError", "(", "'Arg must be type datetime'", ")", "if", "(", "dt", ".", "tzinfo", "is", "None", ")", ":", "return", "dt", "return", "dt", ".", "astimezone", "(", "pytz", ".", "utc", ")", ".", "replace", "(", "tzinfo", "=", "None", ")" ]
converts a datetime to a naive datetime as follows: if inbound dt is already naive .
train
false
20,523
def test_ast_bad_with(): cant_compile(u'(with*)') cant_compile(u'(with* [])') cant_compile(u'(with* [] (pass))')
[ "def", "test_ast_bad_with", "(", ")", ":", "cant_compile", "(", "u'(with*)'", ")", "cant_compile", "(", "u'(with* [])'", ")", "cant_compile", "(", "u'(with* [] (pass))'", ")" ]
make sure ast cant compile invalid with .
train
false
20,524
def print_error(string): sys.stderr.write((string + '\n'))
[ "def", "print_error", "(", "string", ")", ":", "sys", ".", "stderr", ".", "write", "(", "(", "string", "+", "'\\n'", ")", ")" ]
print error messages .
train
false
20,525
def _MakeStartNewThread(base_start_new_thread): def StartNewThread(target, args, kw=None): 'A replacement for thread.start_new_thread.\n\n A replacement for thread.start_new_thread that inherits RequestEnvironment\n state from its creator and cleans up that state when it terminates.\n\n Args:\n See thread.start_new_thread.\n\n Returns:\n See thread.start_new_thread.\n ' if (kw is None): kw = {} cloner = request_environment.current_request.CloneRequestEnvironment() def Run(): try: cloner() target(*args, **kw) finally: request_environment.current_request.Clear() return base_start_new_thread(Run, ()) return StartNewThread
[ "def", "_MakeStartNewThread", "(", "base_start_new_thread", ")", ":", "def", "StartNewThread", "(", "target", ",", "args", ",", "kw", "=", "None", ")", ":", "if", "(", "kw", "is", "None", ")", ":", "kw", "=", "{", "}", "cloner", "=", "request_environment", ".", "current_request", ".", "CloneRequestEnvironment", "(", ")", "def", "Run", "(", ")", ":", "try", ":", "cloner", "(", ")", "target", "(", "*", "args", ",", "**", "kw", ")", "finally", ":", "request_environment", ".", "current_request", ".", "Clear", "(", ")", "return", "base_start_new_thread", "(", "Run", ",", "(", ")", ")", "return", "StartNewThread" ]
returns a replacement for start_new_thread that inherits environment .
train
false
20,526
@pytest.mark.parametrize(u'mode', [u'partial', u'trim', u'strict']) def test_extract_array_easy(mode): large_test_array = np.zeros((11, 11)) small_test_array = np.ones((5, 5)) large_test_array[3:8, 3:8] = small_test_array extracted_array = extract_array(large_test_array, (5, 5), (5, 5), mode=mode) assert np.all((extracted_array == small_test_array))
[ "@", "pytest", ".", "mark", ".", "parametrize", "(", "u'mode'", ",", "[", "u'partial'", ",", "u'trim'", ",", "u'strict'", "]", ")", "def", "test_extract_array_easy", "(", "mode", ")", ":", "large_test_array", "=", "np", ".", "zeros", "(", "(", "11", ",", "11", ")", ")", "small_test_array", "=", "np", ".", "ones", "(", "(", "5", ",", "5", ")", ")", "large_test_array", "[", "3", ":", "8", ",", "3", ":", "8", "]", "=", "small_test_array", "extracted_array", "=", "extract_array", "(", "large_test_array", ",", "(", "5", ",", "5", ")", ",", "(", "5", ",", "5", ")", ",", "mode", "=", "mode", ")", "assert", "np", ".", "all", "(", "(", "extracted_array", "==", "small_test_array", ")", ")" ]
test extract_array utility function .
train
false
20,528
def embedded_document(reference, data_relation, field_name): if (('version' in data_relation) and (data_relation['version'] is True)): embedded_doc = get_data_version_relation_document(data_relation, reference) latest_embedded_doc = get_data_version_relation_document(data_relation, reference, latest=True) if ((embedded_doc is None) or (latest_embedded_doc is None)): abort(404, description=debug_error_message(("Unable to locate embedded documents for '%s'" % field_name))) build_response_document(embedded_doc, data_relation['resource'], [], latest_embedded_doc) else: subresource = (reference.collection if isinstance(reference, DBRef) else data_relation['resource']) id_field = config.DOMAIN[subresource]['id_field'] embedded_doc = app.data.find_one(subresource, None, **{id_field: (reference.id if isinstance(reference, DBRef) else reference)}) if embedded_doc: resolve_media_files(embedded_doc, subresource) return embedded_doc
[ "def", "embedded_document", "(", "reference", ",", "data_relation", ",", "field_name", ")", ":", "if", "(", "(", "'version'", "in", "data_relation", ")", "and", "(", "data_relation", "[", "'version'", "]", "is", "True", ")", ")", ":", "embedded_doc", "=", "get_data_version_relation_document", "(", "data_relation", ",", "reference", ")", "latest_embedded_doc", "=", "get_data_version_relation_document", "(", "data_relation", ",", "reference", ",", "latest", "=", "True", ")", "if", "(", "(", "embedded_doc", "is", "None", ")", "or", "(", "latest_embedded_doc", "is", "None", ")", ")", ":", "abort", "(", "404", ",", "description", "=", "debug_error_message", "(", "(", "\"Unable to locate embedded documents for '%s'\"", "%", "field_name", ")", ")", ")", "build_response_document", "(", "embedded_doc", ",", "data_relation", "[", "'resource'", "]", ",", "[", "]", ",", "latest_embedded_doc", ")", "else", ":", "subresource", "=", "(", "reference", ".", "collection", "if", "isinstance", "(", "reference", ",", "DBRef", ")", "else", "data_relation", "[", "'resource'", "]", ")", "id_field", "=", "config", ".", "DOMAIN", "[", "subresource", "]", "[", "'id_field'", "]", "embedded_doc", "=", "app", ".", "data", ".", "find_one", "(", "subresource", ",", "None", ",", "**", "{", "id_field", ":", "(", "reference", ".", "id", "if", "isinstance", "(", "reference", ",", "DBRef", ")", "else", "reference", ")", "}", ")", "if", "embedded_doc", ":", "resolve_media_files", "(", "embedded_doc", ",", "subresource", ")", "return", "embedded_doc" ]
returns a document to be embedded by reference using data_relation taking into account document versions .
train
false
20,529
def getNewMouseTool(): return ViewpointRotate()
[ "def", "getNewMouseTool", "(", ")", ":", "return", "ViewpointRotate", "(", ")" ]
get a new mouse tool .
train
false
20,530
def binary_accuracy(y, t): return BinaryAccuracy()(y, t)
[ "def", "binary_accuracy", "(", "y", ",", "t", ")", ":", "return", "BinaryAccuracy", "(", ")", "(", "y", ",", "t", ")" ]
computes the binary accuracy between predictions and targets .
train
false
20,532
def str_to_bool(string): if (string is not None): if (string.lower() in ['true', 'yes', '1', 'on']): return True elif (string.lower() in ['false', 'no', '0', 'off']): return False return None
[ "def", "str_to_bool", "(", "string", ")", ":", "if", "(", "string", "is", "not", "None", ")", ":", "if", "(", "string", ".", "lower", "(", ")", "in", "[", "'true'", ",", "'yes'", ",", "'1'", ",", "'on'", "]", ")", ":", "return", "True", "elif", "(", "string", ".", "lower", "(", ")", "in", "[", "'false'", ",", "'no'", ",", "'0'", ",", "'off'", "]", ")", ":", "return", "False", "return", "None" ]
given a string .
train
false
20,533
def ManageBinaries(config=None, token=None): print '\nStep 4: Installing template package and repackaging clients with new configuration.' pack_templates = False download_templates = False if flags.FLAGS.noprompt: if (not flags.FLAGS.no_templates_download): download_templates = pack_templates = True else: if ((raw_input('Download client templates? You can skip this if templates are already installed.[Yn]: ').upper() or 'Y') == 'Y'): download_templates = True if ((raw_input('Repack client templates?[Yn]: ').upper() or 'Y') == 'Y'): pack_templates = True if download_templates: InstallTemplatePackage() if pack_templates: repacking.TemplateRepacker().RepackAllTemplates(upload=True, token=token) print '\nStep 5: Signing and uploading client components.' maintenance_utils.SignAllComponents(token=token) print '\nInitialization complete, writing configuration.' config.Write() print 'Please restart the service for it to take effect.\n\n'
[ "def", "ManageBinaries", "(", "config", "=", "None", ",", "token", "=", "None", ")", ":", "print", "'\\nStep 4: Installing template package and repackaging clients with new configuration.'", "pack_templates", "=", "False", "download_templates", "=", "False", "if", "flags", ".", "FLAGS", ".", "noprompt", ":", "if", "(", "not", "flags", ".", "FLAGS", ".", "no_templates_download", ")", ":", "download_templates", "=", "pack_templates", "=", "True", "else", ":", "if", "(", "(", "raw_input", "(", "'Download client templates? You can skip this if templates are already installed.[Yn]: '", ")", ".", "upper", "(", ")", "or", "'Y'", ")", "==", "'Y'", ")", ":", "download_templates", "=", "True", "if", "(", "(", "raw_input", "(", "'Repack client templates?[Yn]: '", ")", ".", "upper", "(", ")", "or", "'Y'", ")", "==", "'Y'", ")", ":", "pack_templates", "=", "True", "if", "download_templates", ":", "InstallTemplatePackage", "(", ")", "if", "pack_templates", ":", "repacking", ".", "TemplateRepacker", "(", ")", ".", "RepackAllTemplates", "(", "upload", "=", "True", ",", "token", "=", "token", ")", "print", "'\\nStep 5: Signing and uploading client components.'", "maintenance_utils", ".", "SignAllComponents", "(", "token", "=", "token", ")", "print", "'\\nInitialization complete, writing configuration.'", "config", ".", "Write", "(", ")", "print", "'Please restart the service for it to take effect.\\n\\n'" ]
repack templates into installers .
train
false
20,534
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None): _ensure_running(name, no_start=True, path=path) return __salt__['container_resource.copy_to'](name, source, dest, container_type=__virtualname__, path=path, exec_driver=EXEC_DRIVER, overwrite=overwrite, makedirs=makedirs)
[ "def", "copy_to", "(", "name", ",", "source", ",", "dest", ",", "overwrite", "=", "False", ",", "makedirs", "=", "False", ",", "path", "=", "None", ")", ":", "_ensure_running", "(", "name", ",", "no_start", "=", "True", ",", "path", "=", "path", ")", "return", "__salt__", "[", "'container_resource.copy_to'", "]", "(", "name", ",", "source", ",", "dest", ",", "container_type", "=", "__virtualname__", ",", "path", "=", "path", ",", "exec_driver", "=", "EXEC_DRIVER", ",", "overwrite", "=", "overwrite", ",", "makedirs", "=", "makedirs", ")" ]
copy a file from the host into a container name container name source file to be copied to the container .
train
true
20,535
def encode_base64_dict(array): return {'__ndarray__': base64.b64encode(array.data).decode('utf-8'), 'shape': array.shape, 'dtype': array.dtype.name}
[ "def", "encode_base64_dict", "(", "array", ")", ":", "return", "{", "'__ndarray__'", ":", "base64", ".", "b64encode", "(", "array", ".", "data", ")", ".", "decode", "(", "'utf-8'", ")", ",", "'shape'", ":", "array", ".", "shape", ",", "'dtype'", ":", "array", ".", "dtype", ".", "name", "}" ]
encode a numpy array using base64: the encoded format is a dict with the following structure: .
train
true
20,536
def join_logical_line(logical_line): indentation = _get_indentation(logical_line) return ((indentation + untokenize_without_newlines(generate_tokens(logical_line.lstrip()))) + u'\n')
[ "def", "join_logical_line", "(", "logical_line", ")", ":", "indentation", "=", "_get_indentation", "(", "logical_line", ")", "return", "(", "(", "indentation", "+", "untokenize_without_newlines", "(", "generate_tokens", "(", "logical_line", ".", "lstrip", "(", ")", ")", ")", ")", "+", "u'\\n'", ")" ]
return single line based on logical line input .
train
true
20,537
@require_admin_context def consistencygroup_get_all(context, filters=None, marker=None, limit=None, offset=None, sort_keys=None, sort_dirs=None): return _consistencygroup_get_all(context, filters, marker, limit, offset, sort_keys, sort_dirs)
[ "@", "require_admin_context", "def", "consistencygroup_get_all", "(", "context", ",", "filters", "=", "None", ",", "marker", "=", "None", ",", "limit", "=", "None", ",", "offset", "=", "None", ",", "sort_keys", "=", "None", ",", "sort_dirs", "=", "None", ")", ":", "return", "_consistencygroup_get_all", "(", "context", ",", "filters", ",", "marker", ",", "limit", ",", "offset", ",", "sort_keys", ",", "sort_dirs", ")" ]
get all consistencygroups .
train
false
20,538
def get_amalgamation(): if os.path.exists(AMALGAMATION_ROOT): return os.mkdir(AMALGAMATION_ROOT) print 'Downloading amalgation.' download_page = urllib.urlopen('http://sqlite.org/download.html').read() pattern = re.compile('(sqlite-amalgamation.*?\\.zip)') download_file = pattern.findall(download_page)[0] amalgamation_url = ('http://sqlite.org/' + download_file) urllib.urlretrieve(amalgamation_url, 'tmp.zip') zf = zipfile.ZipFile('tmp.zip') files = ['sqlite3.c', 'sqlite3.h'] for fn in files: print 'Extracting', fn outf = open(((AMALGAMATION_ROOT + os.sep) + fn), 'wb') outf.write(zf.read(fn)) outf.close() zf.close() os.unlink('tmp.zip')
[ "def", "get_amalgamation", "(", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "AMALGAMATION_ROOT", ")", ":", "return", "os", ".", "mkdir", "(", "AMALGAMATION_ROOT", ")", "print", "'Downloading amalgation.'", "download_page", "=", "urllib", ".", "urlopen", "(", "'http://sqlite.org/download.html'", ")", ".", "read", "(", ")", "pattern", "=", "re", ".", "compile", "(", "'(sqlite-amalgamation.*?\\\\.zip)'", ")", "download_file", "=", "pattern", ".", "findall", "(", "download_page", ")", "[", "0", "]", "amalgamation_url", "=", "(", "'http://sqlite.org/'", "+", "download_file", ")", "urllib", ".", "urlretrieve", "(", "amalgamation_url", ",", "'tmp.zip'", ")", "zf", "=", "zipfile", ".", "ZipFile", "(", "'tmp.zip'", ")", "files", "=", "[", "'sqlite3.c'", ",", "'sqlite3.h'", "]", "for", "fn", "in", "files", ":", "print", "'Extracting'", ",", "fn", "outf", "=", "open", "(", "(", "(", "AMALGAMATION_ROOT", "+", "os", ".", "sep", ")", "+", "fn", ")", ",", "'wb'", ")", "outf", ".", "write", "(", "zf", ".", "read", "(", "fn", ")", ")", "outf", ".", "close", "(", ")", "zf", ".", "close", "(", ")", "os", ".", "unlink", "(", "'tmp.zip'", ")" ]
download the sqlite amalgamation if it isnt there .
train
false
20,540
def b16decode(s, casefold=False): if casefold: s = s.upper() if re.search('[^0-9A-F]', s): raise TypeError('Non-base16 digit found') return binascii.unhexlify(s)
[ "def", "b16decode", "(", "s", ",", "casefold", "=", "False", ")", ":", "if", "casefold", ":", "s", "=", "s", ".", "upper", "(", ")", "if", "re", ".", "search", "(", "'[^0-9A-F]'", ",", "s", ")", ":", "raise", "TypeError", "(", "'Non-base16 digit found'", ")", "return", "binascii", ".", "unhexlify", "(", "s", ")" ]
decode a base16 encoded string .
train
true
20,542
def token_create_scoped(request, tenant, token): if hasattr(request, '_keystone'): del request._keystone c = keystoneclient(request) raw_token = c.tokens.authenticate(tenant_id=tenant, token=token, return_raw=True) c.service_catalog = service_catalog.ServiceCatalog(raw_token) if request.user.is_superuser: c.management_url = c.service_catalog.url_for(service_type='identity', endpoint_type='adminURL') else: endpoint_type = getattr(settings, 'OPENSTACK_ENDPOINT_TYPE', 'internalURL') c.management_url = c.service_catalog.url_for(service_type='identity', endpoint_type=endpoint_type) scoped_token = tokens.Token(tokens.TokenManager, raw_token) return scoped_token
[ "def", "token_create_scoped", "(", "request", ",", "tenant", ",", "token", ")", ":", "if", "hasattr", "(", "request", ",", "'_keystone'", ")", ":", "del", "request", ".", "_keystone", "c", "=", "keystoneclient", "(", "request", ")", "raw_token", "=", "c", ".", "tokens", ".", "authenticate", "(", "tenant_id", "=", "tenant", ",", "token", "=", "token", ",", "return_raw", "=", "True", ")", "c", ".", "service_catalog", "=", "service_catalog", ".", "ServiceCatalog", "(", "raw_token", ")", "if", "request", ".", "user", ".", "is_superuser", ":", "c", ".", "management_url", "=", "c", ".", "service_catalog", ".", "url_for", "(", "service_type", "=", "'identity'", ",", "endpoint_type", "=", "'adminURL'", ")", "else", ":", "endpoint_type", "=", "getattr", "(", "settings", ",", "'OPENSTACK_ENDPOINT_TYPE'", ",", "'internalURL'", ")", "c", ".", "management_url", "=", "c", ".", "service_catalog", ".", "url_for", "(", "service_type", "=", "'identity'", ",", "endpoint_type", "=", "endpoint_type", ")", "scoped_token", "=", "tokens", ".", "Token", "(", "tokens", ".", "TokenManager", ",", "raw_token", ")", "return", "scoped_token" ]
creates a scoped token using the tenant id and unscoped token; retrieves the service catalog for the given tenant .
train
false
20,543
def apart_full_decomposition(P, Q): return assemble_partfrac_list(apart_list((P / Q), P.gens[0]))
[ "def", "apart_full_decomposition", "(", "P", ",", "Q", ")", ":", "return", "assemble_partfrac_list", "(", "apart_list", "(", "(", "P", "/", "Q", ")", ",", "P", ".", "gens", "[", "0", "]", ")", ")" ]
bronsteins full partial fraction decomposition algorithm .
train
false
20,544
def set_current_user(user): _thread_locals.user = user
[ "def", "set_current_user", "(", "user", ")", ":", "_thread_locals", ".", "user", "=", "user" ]
assigns current user from request to thread_locals .
train
false
20,547
def http_now(): return dt_to_http(utcnow())
[ "def", "http_now", "(", ")", ":", "return", "dt_to_http", "(", "utcnow", "(", ")", ")" ]
returns the current utc time as an imf-fixdate .
train
false
20,548
def start_remote_debugger(rpcclt, pyshell): global idb_adap_oid idb_adap_oid = rpcclt.remotecall('exec', 'start_the_debugger', (gui_adap_oid,), {}) idb_proxy = IdbProxy(rpcclt, pyshell, idb_adap_oid) gui = debugger.Debugger(pyshell, idb_proxy) gui_adap = GUIAdapter(rpcclt, gui) rpcclt.register(gui_adap_oid, gui_adap) return gui
[ "def", "start_remote_debugger", "(", "rpcclt", ",", "pyshell", ")", ":", "global", "idb_adap_oid", "idb_adap_oid", "=", "rpcclt", ".", "remotecall", "(", "'exec'", ",", "'start_the_debugger'", ",", "(", "gui_adap_oid", ",", ")", ",", "{", "}", ")", "idb_proxy", "=", "IdbProxy", "(", "rpcclt", ",", "pyshell", ",", "idb_adap_oid", ")", "gui", "=", "debugger", ".", "Debugger", "(", "pyshell", ",", "idb_proxy", ")", "gui_adap", "=", "GUIAdapter", "(", "rpcclt", ",", "gui", ")", "rpcclt", ".", "register", "(", "gui_adap_oid", ",", "gui_adap", ")", "return", "gui" ]
start the subprocess debugger .
train
false
20,549
def iter_all_children(obj, skipContainers=False): if (hasattr(obj, 'get_children') and (len(obj.get_children()) > 0)): for child in obj.get_children(): if (not skipContainers): (yield child) for grandchild in iter_all_children(child, skipContainers): (yield grandchild) else: (yield obj)
[ "def", "iter_all_children", "(", "obj", ",", "skipContainers", "=", "False", ")", ":", "if", "(", "hasattr", "(", "obj", ",", "'get_children'", ")", "and", "(", "len", "(", "obj", ".", "get_children", "(", ")", ")", ">", "0", ")", ")", ":", "for", "child", "in", "obj", ".", "get_children", "(", ")", ":", "if", "(", "not", "skipContainers", ")", ":", "(", "yield", "child", ")", "for", "grandchild", "in", "iter_all_children", "(", "child", ",", "skipContainers", ")", ":", "(", "yield", "grandchild", ")", "else", ":", "(", "yield", "obj", ")" ]
returns an iterator over all children and nested children using objs get_children() method if skipcontainers is true .
train
true
20,550
def profiler(app): def profile_internal(e, o): (out, result) = profile(app)(e, o) return (out + [(('<pre>' + result) + '</pre>')]) return profile_internal
[ "def", "profiler", "(", "app", ")", ":", "def", "profile_internal", "(", "e", ",", "o", ")", ":", "(", "out", ",", "result", ")", "=", "profile", "(", "app", ")", "(", "e", ",", "o", ")", "return", "(", "out", "+", "[", "(", "(", "'<pre>'", "+", "result", ")", "+", "'</pre>'", ")", "]", ")", "return", "profile_internal" ]
to use the profiler start web2py with -f profiler .
train
false
20,551
def _gather_clone_loss(clone, num_clones, regularization_losses): sum_loss = None clone_loss = None regularization_loss = None with tf.device(clone.device): all_losses = [] clone_losses = tf.get_collection(tf.GraphKeys.LOSSES, clone.scope) if clone_losses: clone_loss = tf.add_n(clone_losses, name='clone_loss') if (num_clones > 1): clone_loss = tf.div(clone_loss, (1.0 * num_clones), name='scaled_clone_loss') all_losses.append(clone_loss) if regularization_losses: regularization_loss = tf.add_n(regularization_losses, name='regularization_loss') all_losses.append(regularization_loss) if all_losses: sum_loss = tf.add_n(all_losses) if (clone_loss is not None): tf.scalar_summary((clone.scope + '/clone_loss'), clone_loss, name='clone_loss') if (regularization_loss is not None): tf.scalar_summary('regularization_loss', regularization_loss, name='regularization_loss') return sum_loss
[ "def", "_gather_clone_loss", "(", "clone", ",", "num_clones", ",", "regularization_losses", ")", ":", "sum_loss", "=", "None", "clone_loss", "=", "None", "regularization_loss", "=", "None", "with", "tf", ".", "device", "(", "clone", ".", "device", ")", ":", "all_losses", "=", "[", "]", "clone_losses", "=", "tf", ".", "get_collection", "(", "tf", ".", "GraphKeys", ".", "LOSSES", ",", "clone", ".", "scope", ")", "if", "clone_losses", ":", "clone_loss", "=", "tf", ".", "add_n", "(", "clone_losses", ",", "name", "=", "'clone_loss'", ")", "if", "(", "num_clones", ">", "1", ")", ":", "clone_loss", "=", "tf", ".", "div", "(", "clone_loss", ",", "(", "1.0", "*", "num_clones", ")", ",", "name", "=", "'scaled_clone_loss'", ")", "all_losses", ".", "append", "(", "clone_loss", ")", "if", "regularization_losses", ":", "regularization_loss", "=", "tf", ".", "add_n", "(", "regularization_losses", ",", "name", "=", "'regularization_loss'", ")", "all_losses", ".", "append", "(", "regularization_loss", ")", "if", "all_losses", ":", "sum_loss", "=", "tf", ".", "add_n", "(", "all_losses", ")", "if", "(", "clone_loss", "is", "not", "None", ")", ":", "tf", ".", "scalar_summary", "(", "(", "clone", ".", "scope", "+", "'/clone_loss'", ")", ",", "clone_loss", ",", "name", "=", "'clone_loss'", ")", "if", "(", "regularization_loss", "is", "not", "None", ")", ":", "tf", ".", "scalar_summary", "(", "'regularization_loss'", ",", "regularization_loss", ",", "name", "=", "'regularization_loss'", ")", "return", "sum_loss" ]
gather the loss for a single clone .
train
false
20,552
def uuid_str_to_bin(uuid): matches = re.match('([\\dA-Fa-f]{8})-([\\dA-Fa-f]{4})-([\\dA-Fa-f]{4})-([\\dA-Fa-f]{4})-([\\dA-Fa-f]{4})([\\dA-Fa-f]{8})', uuid) (uuid1, uuid2, uuid3, uuid4, uuid5, uuid6) = map((lambda x: long(x, 16)), matches.groups()) uuid = struct.pack('<LHH', uuid1, uuid2, uuid3) uuid += struct.pack('>HHL', uuid4, uuid5, uuid6) return uuid
[ "def", "uuid_str_to_bin", "(", "uuid", ")", ":", "matches", "=", "re", ".", "match", "(", "'([\\\\dA-Fa-f]{8})-([\\\\dA-Fa-f]{4})-([\\\\dA-Fa-f]{4})-([\\\\dA-Fa-f]{4})-([\\\\dA-Fa-f]{4})([\\\\dA-Fa-f]{8})'", ",", "uuid", ")", "(", "uuid1", ",", "uuid2", ",", "uuid3", ",", "uuid4", ",", "uuid5", ",", "uuid6", ")", "=", "map", "(", "(", "lambda", "x", ":", "long", "(", "x", ",", "16", ")", ")", ",", "matches", ".", "groups", "(", ")", ")", "uuid", "=", "struct", ".", "pack", "(", "'<LHH'", ",", "uuid1", ",", "uuid2", ",", "uuid3", ")", "uuid", "+=", "struct", ".", "pack", "(", "'>HHL'", ",", "uuid4", ",", "uuid5", ",", "uuid6", ")", "return", "uuid" ]
ripped from core impacket .
train
false
20,554
def humanFilesize(size): if (size < 10000): return (ngettext('%u byte', '%u bytes', size) % size) units = [_('KB'), _('MB'), _('GB'), _('TB')] size = float(size) divisor = 1024 for unit in units: size = (size / divisor) if (size < divisor): return ('%.1f %s' % (size, unit)) return ('%u %s' % (size, unit))
[ "def", "humanFilesize", "(", "size", ")", ":", "if", "(", "size", "<", "10000", ")", ":", "return", "(", "ngettext", "(", "'%u byte'", ",", "'%u bytes'", ",", "size", ")", "%", "size", ")", "units", "=", "[", "_", "(", "'KB'", ")", ",", "_", "(", "'MB'", ")", ",", "_", "(", "'GB'", ")", ",", "_", "(", "'TB'", ")", "]", "size", "=", "float", "(", "size", ")", "divisor", "=", "1024", "for", "unit", "in", "units", ":", "size", "=", "(", "size", "/", "divisor", ")", "if", "(", "size", "<", "divisor", ")", ":", "return", "(", "'%.1f %s'", "%", "(", "size", ",", "unit", ")", ")", "return", "(", "'%u %s'", "%", "(", "size", ",", "unit", ")", ")" ]
convert a file size in byte to human natural representation .
train
false
20,555
def afunc(): pass
[ "def", "afunc", "(", ")", ":", "pass" ]
this is a doctest .
train
false
20,556
@utils.arg('--reservation-id', dest='reservation_id', metavar='<reservation-id>', default=None, help=_('Only return servers that match reservation-id.')) @utils.arg('--ip', dest='ip', metavar='<ip-regexp>', default=None, help=_('Search with regular expression match by IP address.')) @utils.arg('--ip6', dest='ip6', metavar='<ip6-regexp>', default=None, help=_('Search with regular expression match by IPv6 address.')) @utils.arg('--name', dest='name', metavar='<name-regexp>', default=None, help=_('Search with regular expression match by name.')) @utils.arg('--instance-name', dest='instance_name', metavar='<name-regexp>', default=None, help=_('Search with regular expression match by server name.')) @utils.arg('--status', dest='status', metavar='<status>', default=None, help=_('Search by server status.')) @utils.arg('--flavor', dest='flavor', metavar='<flavor>', default=None, help=_('Search by flavor name or ID.')) @utils.arg('--image', dest='image', metavar='<image>', default=None, help=_('Search by image name or ID.')) @utils.arg('--host', dest='host', metavar='<hostname>', default=None, help=_('Search servers by hostname to which they are assigned (Admin only).')) @utils.arg('--all-tenants', dest='all_tenants', metavar='<0|1>', nargs='?', type=int, const=1, default=int(strutils.bool_from_string(os.environ.get('ALL_TENANTS', 'false'), True)), help=_('Display information from all tenants (Admin only).')) @utils.arg('--tenant', dest='tenant', metavar='<tenant>', nargs='?', help=_('Display information from single tenant (Admin only).')) @utils.arg('--user', dest='user', metavar='<user>', nargs='?', help=_('Display information from single user (Admin only).')) @utils.arg('--deleted', dest='deleted', action='store_true', default=False, help=_('Only display deleted servers (Admin only).')) @utils.arg('--fields', default=None, metavar='<fields>', help=_('Comma-separated list of fields to display. Use the show command to see which fields are available.')) @utils.arg('--minimal', dest='minimal', action='store_true', default=False, help=_('Get only UUID and name.')) @utils.arg('--sort', dest='sort', metavar='<key>[:<direction>]', help=_('Comma-separated list of sort keys and directions in the form of <key>[:<asc|desc>]. The direction defaults to descending if not specified.')) @utils.arg('--marker', dest='marker', metavar='<marker>', default=None, help=_('The last server UUID of the previous page; displays list of servers after "marker".')) @utils.arg('--limit', dest='limit', metavar='<limit>', type=int, default=None, help=_("Maximum number of servers to display. If limit == -1, all servers will be displayed. If limit is bigger than 'CONF.api.max_limit' option of Nova API, limit 'CONF.api.max_limit' will be used instead.")) @utils.arg('--changes-since', dest='changes_since', metavar='<changes_since>', default=None, help=_('List only servers changed after a certain point of time.The provided time should be an ISO 8061 formatted time.ex 2016-03-04T06:27:59Z .')) @utils.arg('--tags', dest='tags', metavar='<tags>', default=None, help=_("The given tags must all be present for a server to be included in the list result. Boolean expression in this case is 't1 AND t2'. Tags must be separated by commas: --tags <tag1,tag2>"), start_version='2.26') @utils.arg('--tags-any', dest='tags-any', metavar='<tags-any>', default=None, help=_("If one of the given tags is present the server will be included in the list result. Boolean expression in this case is 't1 OR t2'. Tags must be separated by commas: --tags-any <tag1,tag2>"), start_version='2.26') @utils.arg('--not-tags', dest='not-tags', metavar='<not-tags>', default=None, help=_("Only the servers that do not have any of the given tags will be included in the list results. Boolean expression in this case is 'NOT(t1 AND t2)'. Tags must be separated by commas: --not-tags <tag1,tag2>"), start_version='2.26') @utils.arg('--not-tags-any', dest='not-tags-any', metavar='<not-tags-any>', default=None, help=_("Only the servers that do not have at least one of the given tags will be included in the list result. Boolean expression in this case is 'NOT(t1 OR t2)'. Tags must be separated by commas: --not-tags-any <tag1,tag2>"), start_version='2.26') def do_list(cs, args): imageid = None flavorid = None if args.image: imageid = _find_image(cs, args.image).id if args.flavor: flavorid = _find_flavor(cs, args.flavor).id if (args.tenant or args.user): args.all_tenants = 1 search_opts = {'all_tenants': args.all_tenants, 'reservation_id': args.reservation_id, 'ip': args.ip, 'ip6': args.ip6, 'name': args.name, 'image': imageid, 'flavor': flavorid, 'status': args.status, 'tenant_id': args.tenant, 'user_id': args.user, 'host': args.host, 'deleted': args.deleted, 'instance_name': args.instance_name, 'changes-since': args.changes_since} for arg in ('tags', 'tags-any', 'not-tags', 'not-tags-any'): if (arg in args): search_opts[arg] = getattr(args, arg) filters = {'flavor': (lambda f: f['id']), 'security_groups': utils.format_security_groups} id_col = 'ID' detailed = (not args.minimal) sort_keys = [] sort_dirs = [] if args.sort: for sort in args.sort.split(','): (sort_key, _sep, sort_dir) = sort.partition(':') if (not sort_dir): sort_dir = 'desc' elif (sort_dir not in ('asc', 'desc')): raise exceptions.CommandError((_('Unknown sort direction: %s') % sort_dir)) sort_keys.append(sort_key) sort_dirs.append(sort_dir) if search_opts['changes-since']: try: timeutils.parse_isotime(search_opts['changes-since']) except ValueError: raise exceptions.CommandError((_('Invalid changes-since value: %s') % search_opts['changes-since'])) servers = cs.servers.list(detailed=detailed, search_opts=search_opts, sort_keys=sort_keys, sort_dirs=sort_dirs, marker=args.marker, limit=args.limit) convert = [('OS-EXT-SRV-ATTR:host', 'host'), ('OS-EXT-STS:task_state', 'task_state'), ('OS-EXT-SRV-ATTR:instance_name', 'instance_name'), ('OS-EXT-STS:power_state', 'power_state'), ('hostId', 'host_id')] _translate_keys(servers, convert) _translate_extended_states(servers) formatters = {} (cols, fmts) = _get_list_table_columns_and_formatters(args.fields, servers, exclude_fields=('id',), filters=filters) if args.minimal: columns = [id_col, 'Name'] elif cols: columns = ([id_col] + cols) formatters.update(fmts) else: columns = [id_col, 'Name', 'Status', 'Task State', 'Power State', 'Networks'] if search_opts['all_tenants']: columns.insert(2, 'Tenant ID') if search_opts['changes-since']: columns.append('Updated') formatters['Networks'] = utils.format_servers_list_networks sortby_index = 1 if args.sort: sortby_index = None utils.print_list(servers, columns, formatters, sortby_index=sortby_index)
[ "@", "utils", ".", "arg", "(", "'--reservation-id'", ",", "dest", "=", "'reservation_id'", ",", "metavar", "=", "'<reservation-id>'", ",", "default", "=", "None", ",", "help", "=", "_", "(", "'Only return servers that match reservation-id.'", ")", ")", "@", "utils", ".", "arg", "(", "'--ip'", ",", "dest", "=", "'ip'", ",", "metavar", "=", "'<ip-regexp>'", ",", "default", "=", "None", ",", "help", "=", "_", "(", "'Search with regular expression match by IP address.'", ")", ")", "@", "utils", ".", "arg", "(", "'--ip6'", ",", "dest", "=", "'ip6'", ",", "metavar", "=", "'<ip6-regexp>'", ",", "default", "=", "None", ",", "help", "=", "_", "(", "'Search with regular expression match by IPv6 address.'", ")", ")", "@", "utils", ".", "arg", "(", "'--name'", ",", "dest", "=", "'name'", ",", "metavar", "=", "'<name-regexp>'", ",", "default", "=", "None", ",", "help", "=", "_", "(", "'Search with regular expression match by name.'", ")", ")", "@", "utils", ".", "arg", "(", "'--instance-name'", ",", "dest", "=", "'instance_name'", ",", "metavar", "=", "'<name-regexp>'", ",", "default", "=", "None", ",", "help", "=", "_", "(", "'Search with regular expression match by server name.'", ")", ")", "@", "utils", ".", "arg", "(", "'--status'", ",", "dest", "=", "'status'", ",", "metavar", "=", "'<status>'", ",", "default", "=", "None", ",", "help", "=", "_", "(", "'Search by server status.'", ")", ")", "@", "utils", ".", "arg", "(", "'--flavor'", ",", "dest", "=", "'flavor'", ",", "metavar", "=", "'<flavor>'", ",", "default", "=", "None", ",", "help", "=", "_", "(", "'Search by flavor name or ID.'", ")", ")", "@", "utils", ".", "arg", "(", "'--image'", ",", "dest", "=", "'image'", ",", "metavar", "=", "'<image>'", ",", "default", "=", "None", ",", "help", "=", "_", "(", "'Search by image name or ID.'", ")", ")", "@", "utils", ".", "arg", "(", "'--host'", ",", "dest", "=", "'host'", ",", "metavar", "=", "'<hostname>'", ",", "default", "=", "None", ",", "help", "=", "_", "(", "'Search servers by hostname to which they are assigned (Admin only).'", ")", ")", "@", "utils", ".", "arg", "(", "'--all-tenants'", ",", "dest", "=", "'all_tenants'", ",", "metavar", "=", "'<0|1>'", ",", "nargs", "=", "'?'", ",", "type", "=", "int", ",", "const", "=", "1", ",", "default", "=", "int", "(", "strutils", ".", "bool_from_string", "(", "os", ".", "environ", ".", "get", "(", "'ALL_TENANTS'", ",", "'false'", ")", ",", "True", ")", ")", ",", "help", "=", "_", "(", "'Display information from all tenants (Admin only).'", ")", ")", "@", "utils", ".", "arg", "(", "'--tenant'", ",", "dest", "=", "'tenant'", ",", "metavar", "=", "'<tenant>'", ",", "nargs", "=", "'?'", ",", "help", "=", "_", "(", "'Display information from single tenant (Admin only).'", ")", ")", "@", "utils", ".", "arg", "(", "'--user'", ",", "dest", "=", "'user'", ",", "metavar", "=", "'<user>'", ",", "nargs", "=", "'?'", ",", "help", "=", "_", "(", "'Display information from single user (Admin only).'", ")", ")", "@", "utils", ".", "arg", "(", "'--deleted'", ",", "dest", "=", "'deleted'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "_", "(", "'Only display deleted servers (Admin only).'", ")", ")", "@", "utils", ".", "arg", "(", "'--fields'", ",", "default", "=", "None", ",", "metavar", "=", "'<fields>'", ",", "help", "=", "_", "(", "'Comma-separated list of fields to display. Use the show command to see which fields are available.'", ")", ")", "@", "utils", ".", "arg", "(", "'--minimal'", ",", "dest", "=", "'minimal'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "_", "(", "'Get only UUID and name.'", ")", ")", "@", "utils", ".", "arg", "(", "'--sort'", ",", "dest", "=", "'sort'", ",", "metavar", "=", "'<key>[:<direction>]'", ",", "help", "=", "_", "(", "'Comma-separated list of sort keys and directions in the form of <key>[:<asc|desc>]. The direction defaults to descending if not specified.'", ")", ")", "@", "utils", ".", "arg", "(", "'--marker'", ",", "dest", "=", "'marker'", ",", "metavar", "=", "'<marker>'", ",", "default", "=", "None", ",", "help", "=", "_", "(", "'The last server UUID of the previous page; displays list of servers after \"marker\".'", ")", ")", "@", "utils", ".", "arg", "(", "'--limit'", ",", "dest", "=", "'limit'", ",", "metavar", "=", "'<limit>'", ",", "type", "=", "int", ",", "default", "=", "None", ",", "help", "=", "_", "(", "\"Maximum number of servers to display. If limit == -1, all servers will be displayed. If limit is bigger than 'CONF.api.max_limit' option of Nova API, limit 'CONF.api.max_limit' will be used instead.\"", ")", ")", "@", "utils", ".", "arg", "(", "'--changes-since'", ",", "dest", "=", "'changes_since'", ",", "metavar", "=", "'<changes_since>'", ",", "default", "=", "None", ",", "help", "=", "_", "(", "'List only servers changed after a certain point of time.The provided time should be an ISO 8061 formatted time.ex 2016-03-04T06:27:59Z .'", ")", ")", "@", "utils", ".", "arg", "(", "'--tags'", ",", "dest", "=", "'tags'", ",", "metavar", "=", "'<tags>'", ",", "default", "=", "None", ",", "help", "=", "_", "(", "\"The given tags must all be present for a server to be included in the list result. Boolean expression in this case is 't1 AND t2'. Tags must be separated by commas: --tags <tag1,tag2>\"", ")", ",", "start_version", "=", "'2.26'", ")", "@", "utils", ".", "arg", "(", "'--tags-any'", ",", "dest", "=", "'tags-any'", ",", "metavar", "=", "'<tags-any>'", ",", "default", "=", "None", ",", "help", "=", "_", "(", "\"If one of the given tags is present the server will be included in the list result. Boolean expression in this case is 't1 OR t2'. Tags must be separated by commas: --tags-any <tag1,tag2>\"", ")", ",", "start_version", "=", "'2.26'", ")", "@", "utils", ".", "arg", "(", "'--not-tags'", ",", "dest", "=", "'not-tags'", ",", "metavar", "=", "'<not-tags>'", ",", "default", "=", "None", ",", "help", "=", "_", "(", "\"Only the servers that do not have any of the given tags will be included in the list results. Boolean expression in this case is 'NOT(t1 AND t2)'. Tags must be separated by commas: --not-tags <tag1,tag2>\"", ")", ",", "start_version", "=", "'2.26'", ")", "@", "utils", ".", "arg", "(", "'--not-tags-any'", ",", "dest", "=", "'not-tags-any'", ",", "metavar", "=", "'<not-tags-any>'", ",", "default", "=", "None", ",", "help", "=", "_", "(", "\"Only the servers that do not have at least one of the given tags will be included in the list result. Boolean expression in this case is 'NOT(t1 OR t2)'. Tags must be separated by commas: --not-tags-any <tag1,tag2>\"", ")", ",", "start_version", "=", "'2.26'", ")", "def", "do_list", "(", "cs", ",", "args", ")", ":", "imageid", "=", "None", "flavorid", "=", "None", "if", "args", ".", "image", ":", "imageid", "=", "_find_image", "(", "cs", ",", "args", ".", "image", ")", ".", "id", "if", "args", ".", "flavor", ":", "flavorid", "=", "_find_flavor", "(", "cs", ",", "args", ".", "flavor", ")", ".", "id", "if", "(", "args", ".", "tenant", "or", "args", ".", "user", ")", ":", "args", ".", "all_tenants", "=", "1", "search_opts", "=", "{", "'all_tenants'", ":", "args", ".", "all_tenants", ",", "'reservation_id'", ":", "args", ".", "reservation_id", ",", "'ip'", ":", "args", ".", "ip", ",", "'ip6'", ":", "args", ".", "ip6", ",", "'name'", ":", "args", ".", "name", ",", "'image'", ":", "imageid", ",", "'flavor'", ":", "flavorid", ",", "'status'", ":", "args", ".", "status", ",", "'tenant_id'", ":", "args", ".", "tenant", ",", "'user_id'", ":", "args", ".", "user", ",", "'host'", ":", "args", ".", "host", ",", "'deleted'", ":", "args", ".", "deleted", ",", "'instance_name'", ":", "args", ".", "instance_name", ",", "'changes-since'", ":", "args", ".", "changes_since", "}", "for", "arg", "in", "(", "'tags'", ",", "'tags-any'", ",", "'not-tags'", ",", "'not-tags-any'", ")", ":", "if", "(", "arg", "in", "args", ")", ":", "search_opts", "[", "arg", "]", "=", "getattr", "(", "args", ",", "arg", ")", "filters", "=", "{", "'flavor'", ":", "(", "lambda", "f", ":", "f", "[", "'id'", "]", ")", ",", "'security_groups'", ":", "utils", ".", "format_security_groups", "}", "id_col", "=", "'ID'", "detailed", "=", "(", "not", "args", ".", "minimal", ")", "sort_keys", "=", "[", "]", "sort_dirs", "=", "[", "]", "if", "args", ".", "sort", ":", "for", "sort", "in", "args", ".", "sort", ".", "split", "(", "','", ")", ":", "(", "sort_key", ",", "_sep", ",", "sort_dir", ")", "=", "sort", ".", "partition", "(", "':'", ")", "if", "(", "not", "sort_dir", ")", ":", "sort_dir", "=", "'desc'", "elif", "(", "sort_dir", "not", "in", "(", "'asc'", ",", "'desc'", ")", ")", ":", "raise", "exceptions", ".", "CommandError", "(", "(", "_", "(", "'Unknown sort direction: %s'", ")", "%", "sort_dir", ")", ")", "sort_keys", ".", "append", "(", "sort_key", ")", "sort_dirs", ".", "append", "(", "sort_dir", ")", "if", "search_opts", "[", "'changes-since'", "]", ":", "try", ":", "timeutils", ".", "parse_isotime", "(", "search_opts", "[", "'changes-since'", "]", ")", "except", "ValueError", ":", "raise", "exceptions", ".", "CommandError", "(", "(", "_", "(", "'Invalid changes-since value: %s'", ")", "%", "search_opts", "[", "'changes-since'", "]", ")", ")", "servers", "=", "cs", ".", "servers", ".", "list", "(", "detailed", "=", "detailed", ",", "search_opts", "=", "search_opts", ",", "sort_keys", "=", "sort_keys", ",", "sort_dirs", "=", "sort_dirs", ",", "marker", "=", "args", ".", "marker", ",", "limit", "=", "args", ".", "limit", ")", "convert", "=", "[", "(", "'OS-EXT-SRV-ATTR:host'", ",", "'host'", ")", ",", "(", "'OS-EXT-STS:task_state'", ",", "'task_state'", ")", ",", "(", "'OS-EXT-SRV-ATTR:instance_name'", ",", "'instance_name'", ")", ",", "(", "'OS-EXT-STS:power_state'", ",", "'power_state'", ")", ",", "(", "'hostId'", ",", "'host_id'", ")", "]", "_translate_keys", "(", "servers", ",", "convert", ")", "_translate_extended_states", "(", "servers", ")", "formatters", "=", "{", "}", "(", "cols", ",", "fmts", ")", "=", "_get_list_table_columns_and_formatters", "(", "args", ".", "fields", ",", "servers", ",", "exclude_fields", "=", "(", "'id'", ",", ")", ",", "filters", "=", "filters", ")", "if", "args", ".", "minimal", ":", "columns", "=", "[", "id_col", ",", "'Name'", "]", "elif", "cols", ":", "columns", "=", "(", "[", "id_col", "]", "+", "cols", ")", "formatters", ".", "update", "(", "fmts", ")", "else", ":", "columns", "=", "[", "id_col", ",", "'Name'", ",", "'Status'", ",", "'Task State'", ",", "'Power State'", ",", "'Networks'", "]", "if", "search_opts", "[", "'all_tenants'", "]", ":", "columns", ".", "insert", "(", "2", ",", "'Tenant ID'", ")", "if", "search_opts", "[", "'changes-since'", "]", ":", "columns", ".", "append", "(", "'Updated'", ")", "formatters", "[", "'Networks'", "]", "=", "utils", ".", "format_servers_list_networks", "sortby_index", "=", "1", "if", "args", ".", "sort", ":", "sortby_index", "=", "None", "utils", ".", "print_list", "(", "servers", ",", "columns", ",", "formatters", ",", "sortby_index", "=", "sortby_index", ")" ]
convert the value into a list .
train
false
20,557
def set_session_data(storage, messages): storage.request.session[storage.session_key] = storage.serialize_messages(messages) if hasattr(storage, '_loaded_data'): del storage._loaded_data
[ "def", "set_session_data", "(", "storage", ",", "messages", ")", ":", "storage", ".", "request", ".", "session", "[", "storage", ".", "session_key", "]", "=", "storage", ".", "serialize_messages", "(", "messages", ")", "if", "hasattr", "(", "storage", ",", "'_loaded_data'", ")", ":", "del", "storage", ".", "_loaded_data" ]
store session data persistently so that it is propagated automatically to new logged in clients .
train
false
20,558
def get_certificate_template(course_key, mode): (org_id, template) = (None, None) course_organization = get_course_organizations(course_key) if course_organization: org_id = course_organization[0]['id'] if (org_id and mode): template = CertificateTemplate.objects.filter(organization_id=org_id, course_key=course_key, mode=mode, is_active=True) if ((not template) and org_id and mode): template = CertificateTemplate.objects.filter(organization_id=org_id, course_key=CourseKeyField.Empty, mode=mode, is_active=True) if ((not template) and org_id): template = CertificateTemplate.objects.filter(organization_id=org_id, course_key=CourseKeyField.Empty, mode=None, is_active=True) if ((not template) and mode): template = CertificateTemplate.objects.filter(organization_id=None, course_key=CourseKeyField.Empty, mode=mode, is_active=True) return (template[0].template if template else None)
[ "def", "get_certificate_template", "(", "course_key", ",", "mode", ")", ":", "(", "org_id", ",", "template", ")", "=", "(", "None", ",", "None", ")", "course_organization", "=", "get_course_organizations", "(", "course_key", ")", "if", "course_organization", ":", "org_id", "=", "course_organization", "[", "0", "]", "[", "'id'", "]", "if", "(", "org_id", "and", "mode", ")", ":", "template", "=", "CertificateTemplate", ".", "objects", ".", "filter", "(", "organization_id", "=", "org_id", ",", "course_key", "=", "course_key", ",", "mode", "=", "mode", ",", "is_active", "=", "True", ")", "if", "(", "(", "not", "template", ")", "and", "org_id", "and", "mode", ")", ":", "template", "=", "CertificateTemplate", ".", "objects", ".", "filter", "(", "organization_id", "=", "org_id", ",", "course_key", "=", "CourseKeyField", ".", "Empty", ",", "mode", "=", "mode", ",", "is_active", "=", "True", ")", "if", "(", "(", "not", "template", ")", "and", "org_id", ")", ":", "template", "=", "CertificateTemplate", ".", "objects", ".", "filter", "(", "organization_id", "=", "org_id", ",", "course_key", "=", "CourseKeyField", ".", "Empty", ",", "mode", "=", "None", ",", "is_active", "=", "True", ")", "if", "(", "(", "not", "template", ")", "and", "mode", ")", ":", "template", "=", "CertificateTemplate", ".", "objects", ".", "filter", "(", "organization_id", "=", "None", ",", "course_key", "=", "CourseKeyField", ".", "Empty", ",", "mode", "=", "mode", ",", "is_active", "=", "True", ")", "return", "(", "template", "[", "0", "]", ".", "template", "if", "template", "else", "None", ")" ]
retrieves the custom certificate template based on course_key and mode .
train
false
20,559
def _test_rational_new(cls): assert (cls(0) is S.Zero) assert (cls(1) is S.One) assert (cls((-1)) is S.NegativeOne) assert (cls('1') is S.One) assert (cls(u'-1') is S.NegativeOne) i = Integer(10) assert _strictly_equal(i, cls('10')) assert _strictly_equal(i, cls(u'10')) assert _strictly_equal(i, cls(long(10))) assert _strictly_equal(i, cls(i)) raises(TypeError, (lambda : cls(Symbol('x'))))
[ "def", "_test_rational_new", "(", "cls", ")", ":", "assert", "(", "cls", "(", "0", ")", "is", "S", ".", "Zero", ")", "assert", "(", "cls", "(", "1", ")", "is", "S", ".", "One", ")", "assert", "(", "cls", "(", "(", "-", "1", ")", ")", "is", "S", ".", "NegativeOne", ")", "assert", "(", "cls", "(", "'1'", ")", "is", "S", ".", "One", ")", "assert", "(", "cls", "(", "u'-1'", ")", "is", "S", ".", "NegativeOne", ")", "i", "=", "Integer", "(", "10", ")", "assert", "_strictly_equal", "(", "i", ",", "cls", "(", "'10'", ")", ")", "assert", "_strictly_equal", "(", "i", ",", "cls", "(", "u'10'", ")", ")", "assert", "_strictly_equal", "(", "i", ",", "cls", "(", "long", "(", "10", ")", ")", ")", "assert", "_strictly_equal", "(", "i", ",", "cls", "(", "i", ")", ")", "raises", "(", "TypeError", ",", "(", "lambda", ":", "cls", "(", "Symbol", "(", "'x'", ")", ")", ")", ")" ]
tests that are common between integer and rational .
train
false
20,560
def remove_args(url, keep_params=(), frags=False): parsed = urlsplit(url) filtered_query = '&'.join((qry_item for qry_item in parsed.query.split('&') if qry_item.startswith(keep_params))) if frags: frag = parsed[4:] else: frag = ('',) return urlunsplit(((parsed[:3] + (filtered_query,)) + frag))
[ "def", "remove_args", "(", "url", ",", "keep_params", "=", "(", ")", ",", "frags", "=", "False", ")", ":", "parsed", "=", "urlsplit", "(", "url", ")", "filtered_query", "=", "'&'", ".", "join", "(", "(", "qry_item", "for", "qry_item", "in", "parsed", ".", "query", ".", "split", "(", "'&'", ")", "if", "qry_item", ".", "startswith", "(", "keep_params", ")", ")", ")", "if", "frags", ":", "frag", "=", "parsed", "[", "4", ":", "]", "else", ":", "frag", "=", "(", "''", ",", ")", "return", "urlunsplit", "(", "(", "(", "parsed", "[", ":", "3", "]", "+", "(", "filtered_query", ",", ")", ")", "+", "frag", ")", ")" ]
remove all param arguments from a url .
train
false
20,561
def runRPC(port=4242): print '[*] Starting Veil-Evasion RPC server...' import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('127.0.0.1', port)) s.listen(1) server = VeilEvasionServer(s, name='VeilEvasionServer') server.join()
[ "def", "runRPC", "(", "port", "=", "4242", ")", ":", "print", "'[*] Starting Veil-Evasion RPC server...'", "import", "socket", "s", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "s", ".", "setsockopt", "(", "socket", ".", "SOL_SOCKET", ",", "socket", ".", "SO_REUSEADDR", ",", "1", ")", "s", ".", "bind", "(", "(", "'127.0.0.1'", ",", "port", ")", ")", "s", ".", "listen", "(", "1", ")", "server", "=", "VeilEvasionServer", "(", "s", ",", "name", "=", "'VeilEvasionServer'", ")", "server", ".", "join", "(", ")" ]
invoke a veil-evasion rpc instance on the specified port .
train
false
20,562
def convergence(first_front, optimal_front): distances = [] for ind in first_front: distances.append(float('inf')) for opt_ind in optimal_front: dist = 0.0 for i in xrange(len(opt_ind)): dist += ((ind.fitness.values[i] - opt_ind[i]) ** 2) if (dist < distances[(-1)]): distances[(-1)] = dist distances[(-1)] = sqrt(distances[(-1)]) return (sum(distances) / len(distances))
[ "def", "convergence", "(", "first_front", ",", "optimal_front", ")", ":", "distances", "=", "[", "]", "for", "ind", "in", "first_front", ":", "distances", ".", "append", "(", "float", "(", "'inf'", ")", ")", "for", "opt_ind", "in", "optimal_front", ":", "dist", "=", "0.0", "for", "i", "in", "xrange", "(", "len", "(", "opt_ind", ")", ")", ":", "dist", "+=", "(", "(", "ind", ".", "fitness", ".", "values", "[", "i", "]", "-", "opt_ind", "[", "i", "]", ")", "**", "2", ")", "if", "(", "dist", "<", "distances", "[", "(", "-", "1", ")", "]", ")", ":", "distances", "[", "(", "-", "1", ")", "]", "=", "dist", "distances", "[", "(", "-", "1", ")", "]", "=", "sqrt", "(", "distances", "[", "(", "-", "1", ")", "]", ")", "return", "(", "sum", "(", "distances", ")", "/", "len", "(", "distances", ")", ")" ]
given a pareto front first_front and the optimal pareto front .
train
false
20,564
def view_image(): try: _id = request.args[0] except: return 'Need to provide the id of the Image' table = s3db.doc_image record = db((table.id == _id)).select(table.name, table.file, table.comments, limitby=(0, 1)).first() desc = DIV(record.comments, _class='imageDesc') filename = record.name url = URL(c='default', f='download', args=record.file) alt = (record.comments if record.comments else filename) image = IMG(_src=url, _alt=alt) output = Storage(image=image, desc=desc) return output
[ "def", "view_image", "(", ")", ":", "try", ":", "_id", "=", "request", ".", "args", "[", "0", "]", "except", ":", "return", "'Need to provide the id of the Image'", "table", "=", "s3db", ".", "doc_image", "record", "=", "db", "(", "(", "table", ".", "id", "==", "_id", ")", ")", ".", "select", "(", "table", ".", "name", ",", "table", ".", "file", ",", "table", ".", "comments", ",", "limitby", "=", "(", "0", ",", "1", ")", ")", ".", "first", "(", ")", "desc", "=", "DIV", "(", "record", ".", "comments", ",", "_class", "=", "'imageDesc'", ")", "filename", "=", "record", ".", "name", "url", "=", "URL", "(", "c", "=", "'default'", ",", "f", "=", "'download'", ",", "args", "=", "record", ".", "file", ")", "alt", "=", "(", "record", ".", "comments", "if", "record", ".", "comments", "else", "filename", ")", "image", "=", "IMG", "(", "_src", "=", "url", ",", "_alt", "=", "alt", ")", "output", "=", "Storage", "(", "image", "=", "image", ",", "desc", "=", "desc", ")", "return", "output" ]
view a fullscreen version of an image - called from reports .
train
false
20,565
def compute_labels(pos, neg): labels = np.zeros((len(pos) + len(neg))) labels[:len(pos)] = 1.0 labels[len(pos):] = 0.0 return labels
[ "def", "compute_labels", "(", "pos", ",", "neg", ")", ":", "labels", "=", "np", ".", "zeros", "(", "(", "len", "(", "pos", ")", "+", "len", "(", "neg", ")", ")", ")", "labels", "[", ":", "len", "(", "pos", ")", "]", "=", "1.0", "labels", "[", "len", "(", "pos", ")", ":", "]", "=", "0.0", "return", "labels" ]
construct list of labels .
train
false
20,566
def read_user_yes_no(question, default_value): return click.prompt(question, default=default_value, type=click.BOOL)
[ "def", "read_user_yes_no", "(", "question", ",", "default_value", ")", ":", "return", "click", ".", "prompt", "(", "question", ",", "default", "=", "default_value", ",", "type", "=", "click", ".", "BOOL", ")" ]
prompt the user to reply with yes or no .
train
true
20,567
def jwt_get_username_from_payload_handler(payload): return payload.get('username')
[ "def", "jwt_get_username_from_payload_handler", "(", "payload", ")", ":", "return", "payload", ".", "get", "(", "'username'", ")" ]
override this function if username is formatted differently in payload .
train
false
20,569
def isdag(d, keys): return (not getcycle(d, keys))
[ "def", "isdag", "(", "d", ",", "keys", ")", ":", "return", "(", "not", "getcycle", "(", "d", ",", "keys", ")", ")" ]
does dask form a directed acyclic graph when calculating keys? keys may be a single key or list of keys .
train
false
20,570
def finditer(pattern, string, flags=0): return _compile(pattern, flags).finditer(string)
[ "def", "finditer", "(", "pattern", ",", "string", ",", "flags", "=", "0", ")", ":", "return", "_compile", "(", "pattern", ",", "flags", ")", ".", "finditer", "(", "string", ")" ]
return an iterator over all non-overlapping matches in the string .
train
false
20,572
def tstd_lls(y, params, df): (mu, sigma2) = params.T df = (df * 1.0) lls = ((gammaln(((df + 1) / 2.0)) - gammaln((df / 2.0))) - (0.5 * np.log(((df - 2) * np.pi)))) lls -= ((((df + 1) / 2.0) * np.log((1.0 + ((((y - mu) ** 2) / (df - 2)) / sigma2)))) + (0.5 * np.log(sigma2))) return lls
[ "def", "tstd_lls", "(", "y", ",", "params", ",", "df", ")", ":", "(", "mu", ",", "sigma2", ")", "=", "params", ".", "T", "df", "=", "(", "df", "*", "1.0", ")", "lls", "=", "(", "(", "gammaln", "(", "(", "(", "df", "+", "1", ")", "/", "2.0", ")", ")", "-", "gammaln", "(", "(", "df", "/", "2.0", ")", ")", ")", "-", "(", "0.5", "*", "np", ".", "log", "(", "(", "(", "df", "-", "2", ")", "*", "np", ".", "pi", ")", ")", ")", ")", "lls", "-=", "(", "(", "(", "(", "df", "+", "1", ")", "/", "2.0", ")", "*", "np", ".", "log", "(", "(", "1.0", "+", "(", "(", "(", "(", "y", "-", "mu", ")", "**", "2", ")", "/", "(", "df", "-", "2", ")", ")", "/", "sigma2", ")", ")", ")", ")", "+", "(", "0.5", "*", "np", ".", "log", "(", "sigma2", ")", ")", ")", "return", "lls" ]
t loglikelihood given observations and mean mu and variance sigma2 = 1 parameters y : array .
train
false
20,573
def compute_node_utilization_update(context, host, free_ram_mb_delta=0, free_disk_gb_delta=0, work_delta=0, vm_delta=0): session = get_session() compute_node = None with session.begin(subtransactions=True): compute_node = session.query(models.ComputeNode).options(joinedload('service')).filter((models.Service.host == host)).filter_by(deleted=False).with_lockmode('update').first() if (compute_node is None): raise exception.NotFound((_('No ComputeNode for %(host)s') % locals())) table = models.ComputeNode.__table__ if (free_ram_mb_delta != 0): compute_node.free_ram_mb = (table.c.free_ram_mb + free_ram_mb_delta) if (free_disk_gb_delta != 0): compute_node.free_disk_gb = (table.c.free_disk_gb + free_disk_gb_delta) if (work_delta != 0): compute_node.current_workload = (table.c.current_workload + work_delta) if (vm_delta != 0): compute_node.running_vms = (table.c.running_vms + vm_delta) return compute_node
[ "def", "compute_node_utilization_update", "(", "context", ",", "host", ",", "free_ram_mb_delta", "=", "0", ",", "free_disk_gb_delta", "=", "0", ",", "work_delta", "=", "0", ",", "vm_delta", "=", "0", ")", ":", "session", "=", "get_session", "(", ")", "compute_node", "=", "None", "with", "session", ".", "begin", "(", "subtransactions", "=", "True", ")", ":", "compute_node", "=", "session", ".", "query", "(", "models", ".", "ComputeNode", ")", ".", "options", "(", "joinedload", "(", "'service'", ")", ")", ".", "filter", "(", "(", "models", ".", "Service", ".", "host", "==", "host", ")", ")", ".", "filter_by", "(", "deleted", "=", "False", ")", ".", "with_lockmode", "(", "'update'", ")", ".", "first", "(", ")", "if", "(", "compute_node", "is", "None", ")", ":", "raise", "exception", ".", "NotFound", "(", "(", "_", "(", "'No ComputeNode for %(host)s'", ")", "%", "locals", "(", ")", ")", ")", "table", "=", "models", ".", "ComputeNode", ".", "__table__", "if", "(", "free_ram_mb_delta", "!=", "0", ")", ":", "compute_node", ".", "free_ram_mb", "=", "(", "table", ".", "c", ".", "free_ram_mb", "+", "free_ram_mb_delta", ")", "if", "(", "free_disk_gb_delta", "!=", "0", ")", ":", "compute_node", ".", "free_disk_gb", "=", "(", "table", ".", "c", ".", "free_disk_gb", "+", "free_disk_gb_delta", ")", "if", "(", "work_delta", "!=", "0", ")", ":", "compute_node", ".", "current_workload", "=", "(", "table", ".", "c", ".", "current_workload", "+", "work_delta", ")", "if", "(", "vm_delta", "!=", "0", ")", ":", "compute_node", ".", "running_vms", "=", "(", "table", ".", "c", ".", "running_vms", "+", "vm_delta", ")", "return", "compute_node" ]
update a specific computenode entry by a series of deltas .
train
false
20,574
def grab_lock(l): l.acquire() print 'Got the lock again', l.filename l.release()
[ "def", "grab_lock", "(", "l", ")", ":", "l", ".", "acquire", "(", ")", "print", "'Got the lock again'", ",", "l", ".", "filename", "l", ".", "release", "(", ")" ]
stub fn to grab lock inside a greenlet .
train
false
20,575
def flag_modified(instance, key): (state, dict_) = (instance_state(instance), instance_dict(instance)) impl = state.manager[key].impl state._modified_event(dict_, impl, NO_VALUE, force=True)
[ "def", "flag_modified", "(", "instance", ",", "key", ")", ":", "(", "state", ",", "dict_", ")", "=", "(", "instance_state", "(", "instance", ")", ",", "instance_dict", "(", "instance", ")", ")", "impl", "=", "state", ".", "manager", "[", "key", "]", ".", "impl", "state", ".", "_modified_event", "(", "dict_", ",", "impl", ",", "NO_VALUE", ",", "force", "=", "True", ")" ]
mark an attribute on an instance as modified .
train
false
20,576
def enable_third_party_auth(): from third_party_auth import settings as auth_settings auth_settings.apply_settings(settings)
[ "def", "enable_third_party_auth", "(", ")", ":", "from", "third_party_auth", "import", "settings", "as", "auth_settings", "auth_settings", ".", "apply_settings", "(", "settings", ")" ]
enable the use of third_party_auth .
train
false
20,577
@app.cli.command('initdb') def initdb_command(): init_db() print 'Initialized the database.'
[ "@", "app", ".", "cli", ".", "command", "(", "'initdb'", ")", "def", "initdb_command", "(", ")", ":", "init_db", "(", ")", "print", "'Initialized the database.'" ]
creates the database tables .
train
false
20,578
def set_metadata(xml): try: exml = etree.fromstring(xml) except Exception as err: raise GeoNodeException(('Uploaded XML document is not XML: %s' % str(err))) tagname = get_tagname(exml) if (tagname == 'GetRecordByIdResponse'): LOGGER.info('stripping CSW root element') exml = exml.getchildren()[0] tagname = get_tagname(exml) if (tagname == 'MD_Metadata'): (identifier, vals, regions, keywords) = iso2dict(exml) elif (tagname == 'metadata'): (identifier, vals, regions, keywords) = fgdc2dict(exml) elif (tagname == 'Record'): (identifier, vals, regions, keywords) = dc2dict(exml) else: raise RuntimeError('Unsupported metadata format') if (not vals.get('date')): vals['date'] = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S') return [identifier, vals, regions, keywords]
[ "def", "set_metadata", "(", "xml", ")", ":", "try", ":", "exml", "=", "etree", ".", "fromstring", "(", "xml", ")", "except", "Exception", "as", "err", ":", "raise", "GeoNodeException", "(", "(", "'Uploaded XML document is not XML: %s'", "%", "str", "(", "err", ")", ")", ")", "tagname", "=", "get_tagname", "(", "exml", ")", "if", "(", "tagname", "==", "'GetRecordByIdResponse'", ")", ":", "LOGGER", ".", "info", "(", "'stripping CSW root element'", ")", "exml", "=", "exml", ".", "getchildren", "(", ")", "[", "0", "]", "tagname", "=", "get_tagname", "(", "exml", ")", "if", "(", "tagname", "==", "'MD_Metadata'", ")", ":", "(", "identifier", ",", "vals", ",", "regions", ",", "keywords", ")", "=", "iso2dict", "(", "exml", ")", "elif", "(", "tagname", "==", "'metadata'", ")", ":", "(", "identifier", ",", "vals", ",", "regions", ",", "keywords", ")", "=", "fgdc2dict", "(", "exml", ")", "elif", "(", "tagname", "==", "'Record'", ")", ":", "(", "identifier", ",", "vals", ",", "regions", ",", "keywords", ")", "=", "dc2dict", "(", "exml", ")", "else", ":", "raise", "RuntimeError", "(", "'Unsupported metadata format'", ")", "if", "(", "not", "vals", ".", "get", "(", "'date'", ")", ")", ":", "vals", "[", "'date'", "]", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%S'", ")", "return", "[", "identifier", ",", "vals", ",", "regions", ",", "keywords", "]" ]
generate dict of model properties based on xml metadata .
train
false
20,579
@register.tag def include_block(parser, token): tokens = token.split_contents() try: tag_name = tokens.pop(0) block_var_token = tokens.pop(0) except IndexError: raise template.TemplateSyntaxError((u'%r tag requires at least one argument' % tag_name)) block_var = parser.compile_filter(block_var_token) if (tokens and (tokens[0] == u'with')): tokens.pop(0) extra_context = token_kwargs(tokens, parser) else: extra_context = None use_parent_context = True if (tokens and (tokens[0] == u'only')): tokens.pop(0) use_parent_context = False if tokens: raise template.TemplateSyntaxError((u'Unexpected argument to %r tag: %r' % (tag_name, tokens[0]))) return IncludeBlockNode(block_var, extra_context, use_parent_context)
[ "@", "register", ".", "tag", "def", "include_block", "(", "parser", ",", "token", ")", ":", "tokens", "=", "token", ".", "split_contents", "(", ")", "try", ":", "tag_name", "=", "tokens", ".", "pop", "(", "0", ")", "block_var_token", "=", "tokens", ".", "pop", "(", "0", ")", "except", "IndexError", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "(", "u'%r tag requires at least one argument'", "%", "tag_name", ")", ")", "block_var", "=", "parser", ".", "compile_filter", "(", "block_var_token", ")", "if", "(", "tokens", "and", "(", "tokens", "[", "0", "]", "==", "u'with'", ")", ")", ":", "tokens", ".", "pop", "(", "0", ")", "extra_context", "=", "token_kwargs", "(", "tokens", ",", "parser", ")", "else", ":", "extra_context", "=", "None", "use_parent_context", "=", "True", "if", "(", "tokens", "and", "(", "tokens", "[", "0", "]", "==", "u'only'", ")", ")", ":", "tokens", ".", "pop", "(", "0", ")", "use_parent_context", "=", "False", "if", "tokens", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "(", "u'Unexpected argument to %r tag: %r'", "%", "(", "tag_name", ",", "tokens", "[", "0", "]", ")", ")", ")", "return", "IncludeBlockNode", "(", "block_var", ",", "extra_context", ",", "use_parent_context", ")" ]
render the passed item of streamfield content .
train
false
20,580
def printResult(records, domainname): (answers, authority, additional) = records if answers: sys.stdout.write((((domainname + ' IN \n ') + '\n '.join((str(x.payload) for x in answers))) + '\n')) else: sys.stderr.write(('ERROR: No SRV records found for name %r\n' % (domainname,)))
[ "def", "printResult", "(", "records", ",", "domainname", ")", ":", "(", "answers", ",", "authority", ",", "additional", ")", "=", "records", "if", "answers", ":", "sys", ".", "stdout", ".", "write", "(", "(", "(", "(", "domainname", "+", "' IN \\n '", ")", "+", "'\\n '", ".", "join", "(", "(", "str", "(", "x", ".", "payload", ")", "for", "x", "in", "answers", ")", ")", ")", "+", "'\\n'", ")", ")", "else", ":", "sys", ".", "stderr", ".", "write", "(", "(", "'ERROR: No SRV records found for name %r\\n'", "%", "(", "domainname", ",", ")", ")", ")" ]
print a comma separated list of reverse domain names and associated pointer records .
train
false
20,581
def fixTimeout(second): if isinstance(second, float): second = int(ceil(second)) assert isinstance(second, (int, long)) return max(second, 1)
[ "def", "fixTimeout", "(", "second", ")", ":", "if", "isinstance", "(", "second", ",", "float", ")", ":", "second", "=", "int", "(", "ceil", "(", "second", ")", ")", "assert", "isinstance", "(", "second", ",", "(", "int", ",", "long", ")", ")", "return", "max", "(", "second", ",", "1", ")" ]
fix timeout value: convert to integer with a minimum of 1 second .
train
false
20,582
def del_repo(alias): repos = list_repos() if repos: deleted_from = dict() for repo in repos: source = repos[repo][0] if (source['name'] == alias): deleted_from[source['file']] = 0 _del_repo_from_file(alias, source['file']) if deleted_from: ret = '' for repo in repos: source = repos[repo][0] if (source['file'] in deleted_from): deleted_from[source['file']] += 1 for (repo_file, count) in six.iteritems(deleted_from): msg = "Repo '{0}' has been removed from {1}.\n" if ((count == 1) and os.path.isfile(repo_file)): msg = "File {1} containing repo '{0}' has been removed.\n" try: os.remove(repo_file) except OSError: pass ret += msg.format(alias, repo_file) refresh_db() return ret return "Repo {0} doesn't exist in the opkg repo lists".format(alias)
[ "def", "del_repo", "(", "alias", ")", ":", "repos", "=", "list_repos", "(", ")", "if", "repos", ":", "deleted_from", "=", "dict", "(", ")", "for", "repo", "in", "repos", ":", "source", "=", "repos", "[", "repo", "]", "[", "0", "]", "if", "(", "source", "[", "'name'", "]", "==", "alias", ")", ":", "deleted_from", "[", "source", "[", "'file'", "]", "]", "=", "0", "_del_repo_from_file", "(", "alias", ",", "source", "[", "'file'", "]", ")", "if", "deleted_from", ":", "ret", "=", "''", "for", "repo", "in", "repos", ":", "source", "=", "repos", "[", "repo", "]", "[", "0", "]", "if", "(", "source", "[", "'file'", "]", "in", "deleted_from", ")", ":", "deleted_from", "[", "source", "[", "'file'", "]", "]", "+=", "1", "for", "(", "repo_file", ",", "count", ")", "in", "six", ".", "iteritems", "(", "deleted_from", ")", ":", "msg", "=", "\"Repo '{0}' has been removed from {1}.\\n\"", "if", "(", "(", "count", "==", "1", ")", "and", "os", ".", "path", ".", "isfile", "(", "repo_file", ")", ")", ":", "msg", "=", "\"File {1} containing repo '{0}' has been removed.\\n\"", "try", ":", "os", ".", "remove", "(", "repo_file", ")", "except", "OSError", ":", "pass", "ret", "+=", "msg", ".", "format", "(", "alias", ",", "repo_file", ")", "refresh_db", "(", ")", "return", "ret", "return", "\"Repo {0} doesn't exist in the opkg repo lists\"", ".", "format", "(", "alias", ")" ]
delete a repo .
train
false
20,583
def CONTAINSSTRING(expr, pattern): return expr.like(('%%%s%%' % pattern))
[ "def", "CONTAINSSTRING", "(", "expr", ",", "pattern", ")", ":", "return", "expr", ".", "like", "(", "(", "'%%%s%%'", "%", "pattern", ")", ")" ]
emulate sqlobjects containsstring .
train
false
20,584
def DeclareExtraKeyFlags(flag_values=FLAGS): gflags.ADOPT_module_key_flags(module_bar, flag_values=flag_values)
[ "def", "DeclareExtraKeyFlags", "(", "flag_values", "=", "FLAGS", ")", ":", "gflags", ".", "ADOPT_module_key_flags", "(", "module_bar", ",", "flag_values", "=", "flag_values", ")" ]
declares some extra key flags .
train
false
20,587
def get_sgemv_fix(info): path = os.path.abspath(os.path.dirname(__file__)) if needs_sgemv_fix(info): return [os.path.join(path, 'src', 'apple_sgemv_fix.c')] else: return []
[ "def", "get_sgemv_fix", "(", "info", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "if", "needs_sgemv_fix", "(", "info", ")", ":", "return", "[", "os", ".", "path", ".", "join", "(", "path", ",", "'src'", ",", "'apple_sgemv_fix.c'", ")", "]", "else", ":", "return", "[", "]" ]
returns source file needed to correct sgemv .
train
false
20,589
def read_raw_eeglab(input_fname, montage=None, eog=(), event_id=None, event_id_func='strip_to_integer', preload=False, verbose=None, uint16_codec=None): return RawEEGLAB(input_fname=input_fname, montage=montage, preload=preload, eog=eog, event_id=event_id, event_id_func=event_id_func, verbose=verbose, uint16_codec=uint16_codec)
[ "def", "read_raw_eeglab", "(", "input_fname", ",", "montage", "=", "None", ",", "eog", "=", "(", ")", ",", "event_id", "=", "None", ",", "event_id_func", "=", "'strip_to_integer'", ",", "preload", "=", "False", ",", "verbose", "=", "None", ",", "uint16_codec", "=", "None", ")", ":", "return", "RawEEGLAB", "(", "input_fname", "=", "input_fname", ",", "montage", "=", "montage", ",", "preload", "=", "preload", ",", "eog", "=", "eog", ",", "event_id", "=", "event_id", ",", "event_id_func", "=", "event_id_func", ",", "verbose", "=", "verbose", ",", "uint16_codec", "=", "uint16_codec", ")" ]
read an eeglab .
train
false
20,591
def l2_normalize(x, axis): if (axis < 0): axis = (axis % len(x.get_shape())) return tf.nn.l2_normalize(x, dim=axis)
[ "def", "l2_normalize", "(", "x", ",", "axis", ")", ":", "if", "(", "axis", "<", "0", ")", ":", "axis", "=", "(", "axis", "%", "len", "(", "x", ".", "get_shape", "(", ")", ")", ")", "return", "tf", ".", "nn", ".", "l2_normalize", "(", "x", ",", "dim", "=", "axis", ")" ]
l2 normalization .
train
false
20,592
def _dump_arg_defaults(kwargs): if current_app: kwargs.setdefault('cls', current_app.json_encoder) if (not current_app.config['JSON_AS_ASCII']): kwargs.setdefault('ensure_ascii', False) kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS']) else: kwargs.setdefault('sort_keys', True) kwargs.setdefault('cls', JSONEncoder)
[ "def", "_dump_arg_defaults", "(", "kwargs", ")", ":", "if", "current_app", ":", "kwargs", ".", "setdefault", "(", "'cls'", ",", "current_app", ".", "json_encoder", ")", "if", "(", "not", "current_app", ".", "config", "[", "'JSON_AS_ASCII'", "]", ")", ":", "kwargs", ".", "setdefault", "(", "'ensure_ascii'", ",", "False", ")", "kwargs", ".", "setdefault", "(", "'sort_keys'", ",", "current_app", ".", "config", "[", "'JSON_SORT_KEYS'", "]", ")", "else", ":", "kwargs", ".", "setdefault", "(", "'sort_keys'", ",", "True", ")", "kwargs", ".", "setdefault", "(", "'cls'", ",", "JSONEncoder", ")" ]
inject default arguments for dump functions .
train
true
20,593
def kill_cursors(cursor_ids): data = _ZERO_32 data += struct.pack('<i', len(cursor_ids)) for cursor_id in cursor_ids: data += struct.pack('<q', cursor_id) return __pack_message(2007, data)
[ "def", "kill_cursors", "(", "cursor_ids", ")", ":", "data", "=", "_ZERO_32", "data", "+=", "struct", ".", "pack", "(", "'<i'", ",", "len", "(", "cursor_ids", ")", ")", "for", "cursor_id", "in", "cursor_ids", ":", "data", "+=", "struct", ".", "pack", "(", "'<q'", ",", "cursor_id", ")", "return", "__pack_message", "(", "2007", ",", "data", ")" ]
get a **killcursors** message .
train
true
20,595
@when(u'we select from table') def step_select_from_table(context): context.cli.sendline(u'select * from a;')
[ "@", "when", "(", "u'we select from table'", ")", "def", "step_select_from_table", "(", "context", ")", ":", "context", ".", "cli", ".", "sendline", "(", "u'select * from a;'", ")" ]
send select from table .
train
false
20,596
def read_char(fid, count=1): return _unpack_simple(fid, ('>S%s' % count), 'S')
[ "def", "read_char", "(", "fid", ",", "count", "=", "1", ")", ":", "return", "_unpack_simple", "(", "fid", ",", "(", "'>S%s'", "%", "count", ")", ",", "'S'", ")" ]
read character from bti file .
train
false
20,600
def isPathInsideLoops(loops, path): for loop in loops: if isPathInsideLoop(loop, path): return True return False
[ "def", "isPathInsideLoops", "(", "loops", ",", "path", ")", ":", "for", "loop", "in", "loops", ":", "if", "isPathInsideLoop", "(", "loop", ",", "path", ")", ":", "return", "True", "return", "False" ]
determine if a path is inside another loop in a list .
train
false
20,601
def is_dn(s): if (s == ''): return 1 rm = dn_regex.match(s) return ((rm != None) and (rm.group(0) == s))
[ "def", "is_dn", "(", "s", ")", ":", "if", "(", "s", "==", "''", ")", ":", "return", "1", "rm", "=", "dn_regex", ".", "match", "(", "s", ")", "return", "(", "(", "rm", "!=", "None", ")", "and", "(", "rm", ".", "group", "(", "0", ")", "==", "s", ")", ")" ]
returns 1 if s is a ldap dn .
train
false
20,602
def mul(lin_op, val_dict, is_abs=False): if (lin_op.type is lo.VARIABLE): if (lin_op.data in val_dict): if is_abs: return np.abs(val_dict[lin_op.data]) else: return val_dict[lin_op.data] else: return np.mat(np.zeros(lin_op.size)) elif (lin_op.type is lo.NO_OP): return np.mat(np.zeros(lin_op.size)) else: eval_args = [] for arg in lin_op.args: eval_args.append(mul(arg, val_dict, is_abs)) if is_abs: return op_abs_mul(lin_op, eval_args) else: return op_mul(lin_op, eval_args)
[ "def", "mul", "(", "lin_op", ",", "val_dict", ",", "is_abs", "=", "False", ")", ":", "if", "(", "lin_op", ".", "type", "is", "lo", ".", "VARIABLE", ")", ":", "if", "(", "lin_op", ".", "data", "in", "val_dict", ")", ":", "if", "is_abs", ":", "return", "np", ".", "abs", "(", "val_dict", "[", "lin_op", ".", "data", "]", ")", "else", ":", "return", "val_dict", "[", "lin_op", ".", "data", "]", "else", ":", "return", "np", ".", "mat", "(", "np", ".", "zeros", "(", "lin_op", ".", "size", ")", ")", "elif", "(", "lin_op", ".", "type", "is", "lo", ".", "NO_OP", ")", ":", "return", "np", ".", "mat", "(", "np", ".", "zeros", "(", "lin_op", ".", "size", ")", ")", "else", ":", "eval_args", "=", "[", "]", "for", "arg", "in", "lin_op", ".", "args", ":", "eval_args", ".", "append", "(", "mul", "(", "arg", ",", "val_dict", ",", "is_abs", ")", ")", "if", "is_abs", ":", "return", "op_abs_mul", "(", "lin_op", ",", "eval_args", ")", "else", ":", "return", "op_mul", "(", "lin_op", ",", "eval_args", ")" ]
element-wise multiplication .
train
false
20,603
def set_datatypes_registry(d_registry): global _datatypes_registry _datatypes_registry = d_registry
[ "def", "set_datatypes_registry", "(", "d_registry", ")", ":", "global", "_datatypes_registry", "_datatypes_registry", "=", "d_registry" ]
set up datatypes_registry .
train
false
20,604
def filelineno(): if (not _state): raise RuntimeError('no active input()') return _state.filelineno()
[ "def", "filelineno", "(", ")", ":", "if", "(", "not", "_state", ")", ":", "raise", "RuntimeError", "(", "'no active input()'", ")", "return", "_state", ".", "filelineno", "(", ")" ]
return the line number in the current file .
train
false
20,605
def p_multiplicative_expression_1(t): pass
[ "def", "p_multiplicative_expression_1", "(", "t", ")", ":", "pass" ]
multiplicative_expression : cast_expression .
train
false
20,606
def get_checkout_phases_for_service(checkout_process, service): classes = get_provide_objects('front_service_checkout_phase_provider') for provider_cls in classes: provider = provider_cls() assert isinstance(provider, ServiceCheckoutPhaseProvider) phase = provider.get_checkout_phase(checkout_process, service) if phase: assert isinstance(phase, CheckoutPhaseViewMixin) (yield phase)
[ "def", "get_checkout_phases_for_service", "(", "checkout_process", ",", "service", ")", ":", "classes", "=", "get_provide_objects", "(", "'front_service_checkout_phase_provider'", ")", "for", "provider_cls", "in", "classes", ":", "provider", "=", "provider_cls", "(", ")", "assert", "isinstance", "(", "provider", ",", "ServiceCheckoutPhaseProvider", ")", "phase", "=", "provider", ".", "get_checkout_phase", "(", "checkout_process", ",", "service", ")", "if", "phase", ":", "assert", "isinstance", "(", "phase", ",", "CheckoutPhaseViewMixin", ")", "(", "yield", "phase", ")" ]
get checkout phases for given service .
train
false
20,608
def readUntilRegex(stream, regex, ignore_eof=False): name = b_('') while True: tok = stream.read(16) if (not tok): if (ignore_eof == True): return name else: raise PdfStreamError('Stream has ended unexpectedly') m = regex.search(tok) if (m is not None): name += tok[:m.start()] stream.seek((m.start() - len(tok)), 1) break name += tok return name
[ "def", "readUntilRegex", "(", "stream", ",", "regex", ",", "ignore_eof", "=", "False", ")", ":", "name", "=", "b_", "(", "''", ")", "while", "True", ":", "tok", "=", "stream", ".", "read", "(", "16", ")", "if", "(", "not", "tok", ")", ":", "if", "(", "ignore_eof", "==", "True", ")", ":", "return", "name", "else", ":", "raise", "PdfStreamError", "(", "'Stream has ended unexpectedly'", ")", "m", "=", "regex", ".", "search", "(", "tok", ")", "if", "(", "m", "is", "not", "None", ")", ":", "name", "+=", "tok", "[", ":", "m", ".", "start", "(", ")", "]", "stream", ".", "seek", "(", "(", "m", ".", "start", "(", ")", "-", "len", "(", "tok", ")", ")", ",", "1", ")", "break", "name", "+=", "tok", "return", "name" ]
reads until the regular expression pattern matched raise pdfstreamerror on premature end-of-file .
train
false
20,610
def runcmd(cmdv, additional_env=None): env = os.environ.copy() if (additional_env is not None): env.update(additional_env) env['PATH'] = ((os.path.join(common.INSTALL_ROOT, 'build', 'env', 'bin') + os.path.pathsep) + env['PATH']) shell_command = ' '.join(cmdv) LOG.info(("Running '%s' with %r" % (shell_command, additional_env))) popen = subprocess.Popen(shell_command, env=env, shell=True) return popen.wait()
[ "def", "runcmd", "(", "cmdv", ",", "additional_env", "=", "None", ")", ":", "env", "=", "os", ".", "environ", ".", "copy", "(", ")", "if", "(", "additional_env", "is", "not", "None", ")", ":", "env", ".", "update", "(", "additional_env", ")", "env", "[", "'PATH'", "]", "=", "(", "(", "os", ".", "path", ".", "join", "(", "common", ".", "INSTALL_ROOT", ",", "'build'", ",", "'env'", ",", "'bin'", ")", "+", "os", ".", "path", ".", "pathsep", ")", "+", "env", "[", "'PATH'", "]", ")", "shell_command", "=", "' '", ".", "join", "(", "cmdv", ")", "LOG", ".", "info", "(", "(", "\"Running '%s' with %r\"", "%", "(", "shell_command", ",", "additional_env", ")", ")", ")", "popen", "=", "subprocess", ".", "Popen", "(", "shell_command", ",", "env", "=", "env", ",", "shell", "=", "True", ")", "return", "popen", ".", "wait", "(", ")" ]
runcmd -> status code .
train
false
20,611
@click.command(u'new-language') @pass_context @click.argument(u'lang_code') @click.argument(u'app') def new_language(context, lang_code, app): import frappe.translate if (not context[u'sites']): raise Exception(u'--site is required') frappe.connect(site=context[u'sites'][0]) frappe.translate.write_translations_file(app, lang_code) print u'File created at ./apps/{app}/{app}/translations/{lang_code}.csv'.format(app=app, lang_code=lang_code) print u"You will need to add the language in frappe/geo/languages.json, if you haven't done it already."
[ "@", "click", ".", "command", "(", "u'new-language'", ")", "@", "pass_context", "@", "click", ".", "argument", "(", "u'lang_code'", ")", "@", "click", ".", "argument", "(", "u'app'", ")", "def", "new_language", "(", "context", ",", "lang_code", ",", "app", ")", ":", "import", "frappe", ".", "translate", "if", "(", "not", "context", "[", "u'sites'", "]", ")", ":", "raise", "Exception", "(", "u'--site is required'", ")", "frappe", ".", "connect", "(", "site", "=", "context", "[", "u'sites'", "]", "[", "0", "]", ")", "frappe", ".", "translate", ".", "write_translations_file", "(", "app", ",", "lang_code", ")", "print", "u'File created at ./apps/{app}/{app}/translations/{lang_code}.csv'", ".", "format", "(", "app", "=", "app", ",", "lang_code", "=", "lang_code", ")", "print", "u\"You will need to add the language in frappe/geo/languages.json, if you haven't done it already.\"" ]
create lang-code .
train
false
20,612
@core_helper def dashboard_activity_stream(user_id, filter_type=None, filter_id=None, offset=0): context = {'model': model, 'session': model.Session, 'user': c.user} if filter_type: action_functions = {'dataset': 'package_activity_list_html', 'user': 'user_activity_list_html', 'group': 'group_activity_list_html', 'organization': 'organization_activity_list_html'} action_function = logic.get_action(action_functions.get(filter_type)) return action_function(context, {'id': filter_id, 'offset': offset}) else: return logic.get_action('dashboard_activity_list_html')(context, {'offset': offset})
[ "@", "core_helper", "def", "dashboard_activity_stream", "(", "user_id", ",", "filter_type", "=", "None", ",", "filter_id", "=", "None", ",", "offset", "=", "0", ")", ":", "context", "=", "{", "'model'", ":", "model", ",", "'session'", ":", "model", ".", "Session", ",", "'user'", ":", "c", ".", "user", "}", "if", "filter_type", ":", "action_functions", "=", "{", "'dataset'", ":", "'package_activity_list_html'", ",", "'user'", ":", "'user_activity_list_html'", ",", "'group'", ":", "'group_activity_list_html'", ",", "'organization'", ":", "'organization_activity_list_html'", "}", "action_function", "=", "logic", ".", "get_action", "(", "action_functions", ".", "get", "(", "filter_type", ")", ")", "return", "action_function", "(", "context", ",", "{", "'id'", ":", "filter_id", ",", "'offset'", ":", "offset", "}", ")", "else", ":", "return", "logic", ".", "get_action", "(", "'dashboard_activity_list_html'", ")", "(", "context", ",", "{", "'offset'", ":", "offset", "}", ")" ]
return the dashboard activity stream of the current user .
train
false
20,613
def sp_ones_like(x): (data, indices, indptr, shape) = csm_properties(x) return CSM(format=x.format)(tensor.ones_like(data), indices, indptr, shape)
[ "def", "sp_ones_like", "(", "x", ")", ":", "(", "data", ",", "indices", ",", "indptr", ",", "shape", ")", "=", "csm_properties", "(", "x", ")", "return", "CSM", "(", "format", "=", "x", ".", "format", ")", "(", "tensor", ".", "ones_like", "(", "data", ")", ",", "indices", ",", "indptr", ",", "shape", ")" ]
construct a sparse matrix of ones with the same sparsity pattern .
train
false
20,615
def check_export(op): tpot_obj = TPOTClassifier(random_state=42) prng = np.random.RandomState(42) np.random.seed(42) args = [] for type_ in op.parameter_types()[0][1:]: args.append(prng.choice(tpot_obj._pset.terminals[type_]).value) export_string = op.export(*args) assert (export_string.startswith((op.__name__ + '(')) and export_string.endswith(')'))
[ "def", "check_export", "(", "op", ")", ":", "tpot_obj", "=", "TPOTClassifier", "(", "random_state", "=", "42", ")", "prng", "=", "np", ".", "random", ".", "RandomState", "(", "42", ")", "np", ".", "random", ".", "seed", "(", "42", ")", "args", "=", "[", "]", "for", "type_", "in", "op", ".", "parameter_types", "(", ")", "[", "0", "]", "[", "1", ":", "]", ":", "args", ".", "append", "(", "prng", ".", "choice", "(", "tpot_obj", ".", "_pset", ".", "terminals", "[", "type_", "]", ")", ".", "value", ")", "export_string", "=", "op", ".", "export", "(", "*", "args", ")", "assert", "(", "export_string", ".", "startswith", "(", "(", "op", ".", "__name__", "+", "'('", ")", ")", "and", "export_string", ".", "endswith", "(", "')'", ")", ")" ]
assert that a tpot operator exports as expected .
train
false
20,616
def resource_data_get_all(context, resource_id, data=None): if (data is None): data = context.session.query(models.ResourceData).filter_by(resource_id=resource_id).all() if (not data): raise exception.NotFound(_('no resource data found')) ret = {} for res in data: if res.redact: ret[res.key] = crypt.decrypt(res.decrypt_method, res.value) else: ret[res.key] = res.value return ret
[ "def", "resource_data_get_all", "(", "context", ",", "resource_id", ",", "data", "=", "None", ")", ":", "if", "(", "data", "is", "None", ")", ":", "data", "=", "context", ".", "session", ".", "query", "(", "models", ".", "ResourceData", ")", ".", "filter_by", "(", "resource_id", "=", "resource_id", ")", ".", "all", "(", ")", "if", "(", "not", "data", ")", ":", "raise", "exception", ".", "NotFound", "(", "_", "(", "'no resource data found'", ")", ")", "ret", "=", "{", "}", "for", "res", "in", "data", ":", "if", "res", ".", "redact", ":", "ret", "[", "res", ".", "key", "]", "=", "crypt", ".", "decrypt", "(", "res", ".", "decrypt_method", ",", "res", ".", "value", ")", "else", ":", "ret", "[", "res", ".", "key", "]", "=", "res", ".", "value", "return", "ret" ]
looks up resource_data by resource .
train
false
20,617
def volume_down(hass): hass.services.call(DOMAIN, SERVICE_VOLUME_DOWN)
[ "def", "volume_down", "(", "hass", ")", ":", "hass", ".", "services", ".", "call", "(", "DOMAIN", ",", "SERVICE_VOLUME_DOWN", ")" ]
press the keyboard button for volume down .
train
false
20,618
def FormatStats(data, percentiles=None, indent=0): if (len(data) == 0): return '' leader = (' ' * indent) out_str = (leader + ('mean=%.2f' % numpy.mean(data))) out_str += (('\n' + leader) + ('median=%.2f' % numpy.median(data))) out_str += (('\n' + leader) + ('stddev=%.2f' % numpy.std(data))) if percentiles: out_str += (('\n' + leader) + '/'.join(map(str, percentiles))) out_str += (' percentiles=%s' % numpy.percentile(data, percentiles)) return out_str
[ "def", "FormatStats", "(", "data", ",", "percentiles", "=", "None", ",", "indent", "=", "0", ")", ":", "if", "(", "len", "(", "data", ")", "==", "0", ")", ":", "return", "''", "leader", "=", "(", "' '", "*", "indent", ")", "out_str", "=", "(", "leader", "+", "(", "'mean=%.2f'", "%", "numpy", ".", "mean", "(", "data", ")", ")", ")", "out_str", "+=", "(", "(", "'\\n'", "+", "leader", ")", "+", "(", "'median=%.2f'", "%", "numpy", ".", "median", "(", "data", ")", ")", ")", "out_str", "+=", "(", "(", "'\\n'", "+", "leader", ")", "+", "(", "'stddev=%.2f'", "%", "numpy", ".", "std", "(", "data", ")", ")", ")", "if", "percentiles", ":", "out_str", "+=", "(", "(", "'\\n'", "+", "leader", ")", "+", "'/'", ".", "join", "(", "map", "(", "str", ",", "percentiles", ")", ")", ")", "out_str", "+=", "(", "' percentiles=%s'", "%", "numpy", ".", "percentile", "(", "data", ",", "percentiles", ")", ")", "return", "out_str" ]
compute basic stats for an array and return a string containing average .
train
false
20,619
def get_host_ip(ip, shorten=True): ip = netaddr.ip.IPAddress(ip) cidr = netaddr.ip.IPNetwork(ip) if (len(cidr) == 1): return pretty_hex(ip) else: pretty = pretty_hex(cidr[0]) if ((not shorten) or (len(cidr) <= 8)): return pretty else: cutoff = ((32 - cidr.prefixlen) / 4) return pretty[0:(- cutoff)]
[ "def", "get_host_ip", "(", "ip", ",", "shorten", "=", "True", ")", ":", "ip", "=", "netaddr", ".", "ip", ".", "IPAddress", "(", "ip", ")", "cidr", "=", "netaddr", ".", "ip", ".", "IPNetwork", "(", "ip", ")", "if", "(", "len", "(", "cidr", ")", "==", "1", ")", ":", "return", "pretty_hex", "(", "ip", ")", "else", ":", "pretty", "=", "pretty_hex", "(", "cidr", "[", "0", "]", ")", "if", "(", "(", "not", "shorten", ")", "or", "(", "len", "(", "cidr", ")", "<=", "8", ")", ")", ":", "return", "pretty", "else", ":", "cutoff", "=", "(", "(", "32", "-", "cidr", ".", "prefixlen", ")", "/", "4", ")", "return", "pretty", "[", "0", ":", "(", "-", "cutoff", ")", "]" ]
return the ip encoding needed for the tftp boot tree .
train
false
20,620
def gen_resp_headers(info, is_deleted=False): headers = {'X-Backend-Timestamp': Timestamp(info.get('created_at', 0)).internal, 'X-Backend-PUT-Timestamp': Timestamp(info.get('put_timestamp', 0)).internal, 'X-Backend-DELETE-Timestamp': Timestamp(info.get('delete_timestamp', 0)).internal, 'X-Backend-Status-Changed-At': Timestamp(info.get('status_changed_at', 0)).internal, 'X-Backend-Storage-Policy-Index': info.get('storage_policy_index', 0)} if (not is_deleted): headers.update({'X-Container-Object-Count': info.get('object_count', 0), 'X-Container-Bytes-Used': info.get('bytes_used', 0), 'X-Timestamp': Timestamp(info.get('created_at', 0)).normal, 'X-PUT-Timestamp': Timestamp(info.get('put_timestamp', 0)).normal}) return headers
[ "def", "gen_resp_headers", "(", "info", ",", "is_deleted", "=", "False", ")", ":", "headers", "=", "{", "'X-Backend-Timestamp'", ":", "Timestamp", "(", "info", ".", "get", "(", "'created_at'", ",", "0", ")", ")", ".", "internal", ",", "'X-Backend-PUT-Timestamp'", ":", "Timestamp", "(", "info", ".", "get", "(", "'put_timestamp'", ",", "0", ")", ")", ".", "internal", ",", "'X-Backend-DELETE-Timestamp'", ":", "Timestamp", "(", "info", ".", "get", "(", "'delete_timestamp'", ",", "0", ")", ")", ".", "internal", ",", "'X-Backend-Status-Changed-At'", ":", "Timestamp", "(", "info", ".", "get", "(", "'status_changed_at'", ",", "0", ")", ")", ".", "internal", ",", "'X-Backend-Storage-Policy-Index'", ":", "info", ".", "get", "(", "'storage_policy_index'", ",", "0", ")", "}", "if", "(", "not", "is_deleted", ")", ":", "headers", ".", "update", "(", "{", "'X-Container-Object-Count'", ":", "info", ".", "get", "(", "'object_count'", ",", "0", ")", ",", "'X-Container-Bytes-Used'", ":", "info", ".", "get", "(", "'bytes_used'", ",", "0", ")", ",", "'X-Timestamp'", ":", "Timestamp", "(", "info", ".", "get", "(", "'created_at'", ",", "0", ")", ")", ".", "normal", ",", "'X-PUT-Timestamp'", ":", "Timestamp", "(", "info", ".", "get", "(", "'put_timestamp'", ",", "0", ")", ")", ".", "normal", "}", ")", "return", "headers" ]
convert container info dict to headers .
train
false
20,623
def _alter_sequence(cr, seq_name, number_increment=None, number_next=None): if (number_increment == 0): raise UserError(_('Step must not be zero.')) cr.execute('SELECT relname FROM pg_class WHERE relkind=%s AND relname=%s', ('S', seq_name)) if (not cr.fetchone()): return statement = ('ALTER SEQUENCE %s' % (seq_name,)) if (number_increment is not None): statement += (' INCREMENT BY %d' % (number_increment,)) if (number_next is not None): statement += (' RESTART WITH %d' % (number_next,)) cr.execute(statement)
[ "def", "_alter_sequence", "(", "cr", ",", "seq_name", ",", "number_increment", "=", "None", ",", "number_next", "=", "None", ")", ":", "if", "(", "number_increment", "==", "0", ")", ":", "raise", "UserError", "(", "_", "(", "'Step must not be zero.'", ")", ")", "cr", ".", "execute", "(", "'SELECT relname FROM pg_class WHERE relkind=%s AND relname=%s'", ",", "(", "'S'", ",", "seq_name", ")", ")", "if", "(", "not", "cr", ".", "fetchone", "(", ")", ")", ":", "return", "statement", "=", "(", "'ALTER SEQUENCE %s'", "%", "(", "seq_name", ",", ")", ")", "if", "(", "number_increment", "is", "not", "None", ")", ":", "statement", "+=", "(", "' INCREMENT BY %d'", "%", "(", "number_increment", ",", ")", ")", "if", "(", "number_next", "is", "not", "None", ")", ":", "statement", "+=", "(", "' RESTART WITH %d'", "%", "(", "number_next", ",", ")", ")", "cr", ".", "execute", "(", "statement", ")" ]
alter a postresql sequence .
train
false
20,624
def table_from_file(file_in, start=0, stop=(-1)): table = pyo.SndTable() try: table.setSound(file_in, start=start, stop=stop) except TypeError: msg = 'bad file `{0}`, or format not supported'.format(file_in) raise PyoFormatException(msg) rate = pyo.sndinfo(file_in)[2] return (rate, table)
[ "def", "table_from_file", "(", "file_in", ",", "start", "=", "0", ",", "stop", "=", "(", "-", "1", ")", ")", ":", "table", "=", "pyo", ".", "SndTable", "(", ")", "try", ":", "table", ".", "setSound", "(", "file_in", ",", "start", "=", "start", ",", "stop", "=", "stop", ")", "except", "TypeError", ":", "msg", "=", "'bad file `{0}`, or format not supported'", ".", "format", "(", "file_in", ")", "raise", "PyoFormatException", "(", "msg", ")", "rate", "=", "pyo", ".", "sndinfo", "(", "file_in", ")", "[", "2", "]", "return", "(", "rate", ",", "table", ")" ]
read data from files .
train
false
20,625
def register_live_index(model_cls): uid = (str(model_cls) + 'live_indexing') render_done.connect(render_done_handler, model_cls, dispatch_uid=uid) pre_delete.connect(pre_delete_handler, model_cls, dispatch_uid=uid) return model_cls
[ "def", "register_live_index", "(", "model_cls", ")", ":", "uid", "=", "(", "str", "(", "model_cls", ")", "+", "'live_indexing'", ")", "render_done", ".", "connect", "(", "render_done_handler", ",", "model_cls", ",", "dispatch_uid", "=", "uid", ")", "pre_delete", ".", "connect", "(", "pre_delete_handler", ",", "model_cls", ",", "dispatch_uid", "=", "uid", ")", "return", "model_cls" ]
register a model and index for auto indexing .
train
false
20,626
@pytest.fixture def tab_registry(win_registry): registry = objreg.ObjectRegistry() objreg.register('tab-registry', registry, scope='window', window=0) (yield registry) objreg.delete('tab-registry', scope='window', window=0)
[ "@", "pytest", ".", "fixture", "def", "tab_registry", "(", "win_registry", ")", ":", "registry", "=", "objreg", ".", "ObjectRegistry", "(", ")", "objreg", ".", "register", "(", "'tab-registry'", ",", "registry", ",", "scope", "=", "'window'", ",", "window", "=", "0", ")", "(", "yield", "registry", ")", "objreg", ".", "delete", "(", "'tab-registry'", ",", "scope", "=", "'window'", ",", "window", "=", "0", ")" ]
fixture providing a tab registry for win_id 0 .
train
false
20,627
def getLittleEndianFloatGivenFile(file): return unpack('<f', file.read(4))[0]
[ "def", "getLittleEndianFloatGivenFile", "(", "file", ")", ":", "return", "unpack", "(", "'<f'", ",", "file", ".", "read", "(", "4", ")", ")", "[", "0", "]" ]
get little endian float given a file .
train
false
20,629
def debug_on_error(type, value, tb): traceback.print_exc(type, value, tb) print pdb.pm()
[ "def", "debug_on_error", "(", "type", ",", "value", ",", "tb", ")", ":", "traceback", ".", "print_exc", "(", "type", ",", "value", ",", "tb", ")", "print", "pdb", ".", "pm", "(", ")" ]
code due to thomas heller - published in python cookbook .
train
true
20,630
def basic_auth(realm, users, encrypt=None, debug=False): if check_auth(users, encrypt): if debug: cherrypy.log('Auth successful', 'TOOLS.BASIC_AUTH') return cherrypy.serving.response.headers['www-authenticate'] = httpauth.basicAuth(realm) raise cherrypy.HTTPError(401, 'You are not authorized to access that resource')
[ "def", "basic_auth", "(", "realm", ",", "users", ",", "encrypt", "=", "None", ",", "debug", "=", "False", ")", ":", "if", "check_auth", "(", "users", ",", "encrypt", ")", ":", "if", "debug", ":", "cherrypy", ".", "log", "(", "'Auth successful'", ",", "'TOOLS.BASIC_AUTH'", ")", "return", "cherrypy", ".", "serving", ".", "response", ".", "headers", "[", "'www-authenticate'", "]", "=", "httpauth", ".", "basicAuth", "(", "realm", ")", "raise", "cherrypy", ".", "HTTPError", "(", "401", ",", "'You are not authorized to access that resource'", ")" ]
to use basic login with a different server from gluon .
train
false
20,631
def maxinconsts(Z, R): Z = np.asarray(Z, order='c') R = np.asarray(R, order='c') is_valid_linkage(Z, throw=True, name='Z') is_valid_im(R, throw=True, name='R') n = (Z.shape[0] + 1) if (Z.shape[0] != R.shape[0]): raise ValueError('The inconsistency matrix and linkage matrix each have a different number of rows.') MI = np.zeros(((n - 1),)) [Z, R] = _copy_arrays_if_base_present([Z, R]) _hierarchy.get_max_Rfield_for_each_cluster(Z, R, MI, int(n), 3) return MI
[ "def", "maxinconsts", "(", "Z", ",", "R", ")", ":", "Z", "=", "np", ".", "asarray", "(", "Z", ",", "order", "=", "'c'", ")", "R", "=", "np", ".", "asarray", "(", "R", ",", "order", "=", "'c'", ")", "is_valid_linkage", "(", "Z", ",", "throw", "=", "True", ",", "name", "=", "'Z'", ")", "is_valid_im", "(", "R", ",", "throw", "=", "True", ",", "name", "=", "'R'", ")", "n", "=", "(", "Z", ".", "shape", "[", "0", "]", "+", "1", ")", "if", "(", "Z", ".", "shape", "[", "0", "]", "!=", "R", ".", "shape", "[", "0", "]", ")", ":", "raise", "ValueError", "(", "'The inconsistency matrix and linkage matrix each have a different number of rows.'", ")", "MI", "=", "np", ".", "zeros", "(", "(", "(", "n", "-", "1", ")", ",", ")", ")", "[", "Z", ",", "R", "]", "=", "_copy_arrays_if_base_present", "(", "[", "Z", ",", "R", "]", ")", "_hierarchy", ".", "get_max_Rfield_for_each_cluster", "(", "Z", ",", "R", ",", "MI", ",", "int", "(", "n", ")", ",", "3", ")", "return", "MI" ]
returns the maximum inconsistency coefficient for each non-singleton cluster and its descendents .
train
false
20,632
def make_template(skeleton, getter, action): def template(): skeleton(getter, action) return template
[ "def", "make_template", "(", "skeleton", ",", "getter", ",", "action", ")", ":", "def", "template", "(", ")", ":", "skeleton", "(", "getter", ",", "action", ")", "return", "template" ]
instantiate a template method with getter and action .
train
false
20,635
def encode_ascii(s): return s
[ "def", "encode_ascii", "(", "s", ")", ":", "return", "s" ]
in python 2 this is a no-op .
train
false