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
34,986
def my_dynamic_default(): return (3 + 4)
[ "def", "my_dynamic_default", "(", ")", ":", "return", "(", "3", "+", "4", ")" ]
calculates a sum .
train
false
34,988
def bisect_find_sha(start, end, sha, unpack_name): assert (start <= end) while (start <= end): i = ((start + end) // 2) file_sha = unpack_name(i) if (file_sha < sha): start = (i + 1) elif (file_sha > sha): end = (i - 1) else: return i return None
[ "def", "bisect_find_sha", "(", "start", ",", "end", ",", "sha", ",", "unpack_name", ")", ":", "assert", "(", "start", "<=", "end", ")", "while", "(", "start", "<=", "end", ")", ":", "i", "=", "(", "(", "start", "+", "end", ")", "//", "2", ")", ...
find a sha in a data blob with sorted shas .
train
false
34,989
def tailFile(filename, offset, length): try: with open(filename, 'rb') as f: overflow = False f.seek(0, 2) sz = f.tell() if (sz > (offset + length)): overflow = True offset = (sz - 1) if ((offset + length) > sz): if (offset > (sz - 1)): length = 0 offset = (sz - length) if (offset < 0): offset = 0 if (length < 0): length = 0 if (length == 0): data = '' else: f.seek(offset) data = f.read(length) offset = sz return [as_string(data), offset, overflow] except (OSError, IOError): return ['', offset, False]
[ "def", "tailFile", "(", "filename", ",", "offset", ",", "length", ")", ":", "try", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "overflow", "=", "False", "f", ".", "seek", "(", "0", ",", "2", ")", "sz", "=", "f", ".",...
read length bytes from the file named by filename starting at offset .
train
false
34,990
def parse_return(data): if (': ' in data): return data.split(': ')[1] if (':\n' in data): return data.split(':\n')[1] else: return data
[ "def", "parse_return", "(", "data", ")", ":", "if", "(", "': '", "in", "data", ")", ":", "return", "data", ".", "split", "(", "': '", ")", "[", "1", "]", "if", "(", "':\\n'", "in", "data", ")", ":", "return", "data", ".", "split", "(", "':\\n'", ...
returns the data portion of a string that is colon separated .
train
false
34,991
def contrast_allpairs(nm): contr = [] for i in range(nm): for j in range((i + 1), nm): contr_row = np.zeros(nm) contr_row[i] = 1 contr_row[j] = (-1) contr.append(contr_row) return np.array(contr)
[ "def", "contrast_allpairs", "(", "nm", ")", ":", "contr", "=", "[", "]", "for", "i", "in", "range", "(", "nm", ")", ":", "for", "j", "in", "range", "(", "(", "i", "+", "1", ")", ",", "nm", ")", ":", "contr_row", "=", "np", ".", "zeros", "(", ...
contrast or restriction matrix for all pairs of nm variables parameters nm : int returns contr : ndarray .
train
false
34,993
@use_clip_fps_by_default def detect_scenes(clip=None, luminosities=None, thr=10, progress_bar=False, fps=None): if (luminosities is None): luminosities = [f.sum() for f in clip.iter_frames(fps=fps, dtype='uint32', progress_bar=1)] luminosities = np.array(luminosities, dtype=float) if (clip is not None): end = clip.duration else: end = (len(luminosities) * (1.0 / fps)) lum_diffs = abs(np.diff(luminosities)) avg = lum_diffs.mean() luminosity_jumps = (1 + np.array(np.nonzero((lum_diffs > (thr * avg))))[0]) tt = (([0] + list(((1.0 / fps) * luminosity_jumps))) + [end]) cuts = [(t1, t2) for (t1, t2) in zip(tt, tt[1:])] return (cuts, luminosities)
[ "@", "use_clip_fps_by_default", "def", "detect_scenes", "(", "clip", "=", "None", ",", "luminosities", "=", "None", ",", "thr", "=", "10", ",", "progress_bar", "=", "False", ",", "fps", "=", "None", ")", ":", "if", "(", "luminosities", "is", "None", ")",...
detects scenes of a clip based on luminosity changes .
train
false
34,994
def logical_or(image1, image2): image1.load() image2.load() return image1._new(image1.im.chop_or(image2.im))
[ "def", "logical_or", "(", "image1", ",", "image2", ")", ":", "image1", ".", "load", "(", ")", "image2", ".", "load", "(", ")", "return", "image1", ".", "_new", "(", "image1", ".", "im", ".", "chop_or", "(", "image2", ".", "im", ")", ")" ]
logical or between two images .
train
false
34,995
@contextmanager def disconnected_from(signal, listener): signal.disconnect(listener) (yield) signal.connect(listener)
[ "@", "contextmanager", "def", "disconnected_from", "(", "signal", ",", "listener", ")", ":", "signal", ".", "disconnect", "(", "listener", ")", "(", "yield", ")", "signal", ".", "connect", "(", "listener", ")" ]
temporarily disconnect a single listener from a blinker signal .
train
false
34,996
@contextfunction def dajaxice_js_import(context): return Markup(dajaxice_orig_tag(context))
[ "@", "contextfunction", "def", "dajaxice_js_import", "(", "context", ")", ":", "return", "Markup", "(", "dajaxice_orig_tag", "(", "context", ")", ")" ]
thin wrapper for dajaxice .
train
false
34,997
def _create_rand_fdist(numsamples, numoutcomes): import random fdist = FreqDist() for x in range(numoutcomes): y = (random.randint(1, ((1 + numsamples) // 2)) + random.randint(0, (numsamples // 2))) fdist[y] += 1 return fdist
[ "def", "_create_rand_fdist", "(", "numsamples", ",", "numoutcomes", ")", ":", "import", "random", "fdist", "=", "FreqDist", "(", ")", "for", "x", "in", "range", "(", "numoutcomes", ")", ":", "y", "=", "(", "random", ".", "randint", "(", "1", ",", "(", ...
create a new frequency distribution .
train
false
34,998
def strategy_connected_sequential(G, colors, traversal='bfs'): if (traversal == 'bfs'): traverse = nx.bfs_edges elif (traversal == 'dfs'): traverse = nx.dfs_edges else: raise nx.NetworkXError("Please specify one of the strings 'bfs' or 'dfs' for connected sequential ordering") for component in nx.connected_component_subgraphs(G): source = arbitrary_element(component) (yield source) for (_, end) in traverse(component, source): (yield end)
[ "def", "strategy_connected_sequential", "(", "G", ",", "colors", ",", "traversal", "=", "'bfs'", ")", ":", "if", "(", "traversal", "==", "'bfs'", ")", ":", "traverse", "=", "nx", ".", "bfs_edges", "elif", "(", "traversal", "==", "'dfs'", ")", ":", "trave...
returns an iterable over nodes in g in the order given by a breadth-first or depth-first traversal .
train
false
35,001
@contextmanager def ensure_clean_path(path): try: if isinstance(path, list): filenames = [create_tempfile(p) for p in path] (yield filenames) else: filenames = [create_tempfile(path)] (yield filenames[0]) finally: for f in filenames: safe_remove(f)
[ "@", "contextmanager", "def", "ensure_clean_path", "(", "path", ")", ":", "try", ":", "if", "isinstance", "(", "path", ",", "list", ")", ":", "filenames", "=", "[", "create_tempfile", "(", "p", ")", "for", "p", "in", "path", "]", "(", "yield", "filenam...
return essentially a named temporary file that is not opened and deleted on existing; if path is a list .
train
false
35,004
def specialClass(cls, prepend=None, append=None, defaults=None, override=None): if (prepend is None): prepend = [] if (append is None): append = [] if (defaults is None): defaults = {} if (override is None): override = {} class CustomClass(cls, ): 'Customized subclass with preset args/params' def __init__(self, *args, **params): newparams = defaults.copy() newparams.update(params) newparams.update(override) cls.__init__(self, *((list(prepend) + list(args)) + list(append)), **newparams) CustomClass.__name__ = ('%s%s' % (cls.__name__, defaults)) return CustomClass
[ "def", "specialClass", "(", "cls", ",", "prepend", "=", "None", ",", "append", "=", "None", ",", "defaults", "=", "None", ",", "override", "=", "None", ")", ":", "if", "(", "prepend", "is", "None", ")", ":", "prepend", "=", "[", "]", "if", "(", "...
like functools .
train
false
35,005
def cyclic_metasploit_find(subseq, sets=None): sets = (sets or [string.ascii_uppercase, string.ascii_lowercase, string.digits]) if isinstance(subseq, (int, long)): subseq = packing.pack(subseq, 'all', 'little', False) return _gen_find(subseq, metasploit_pattern(sets))
[ "def", "cyclic_metasploit_find", "(", "subseq", ",", "sets", "=", "None", ")", ":", "sets", "=", "(", "sets", "or", "[", "string", ".", "ascii_uppercase", ",", "string", ".", "ascii_lowercase", ",", "string", ".", "digits", "]", ")", "if", "isinstance", ...
cyclic_metasploit_find -> int calculates the position of a substring into a metasploit pattern sequence .
train
false
35,006
def youku(link): pattern = 'http:\\/\\/v\\.youku\\.com\\/v_show/id_([\\w]+)\\.html' match = re.match(pattern, link) if (not match): return None return ('http://player.youku.com/embed/%s' % match.group(1))
[ "def", "youku", "(", "link", ")", ":", "pattern", "=", "'http:\\\\/\\\\/v\\\\.youku\\\\.com\\\\/v_show/id_([\\\\w]+)\\\\.html'", "match", "=", "re", ".", "match", "(", "pattern", ",", "link", ")", "if", "(", "not", "match", ")", ":", "return", "None", "return", ...
find youku player url .
train
false
35,007
def HTMLSchemaTree(schema, se_class, se_tree, se_oid, level): se_obj = schema.get_obj(se_class, se_oid) if (se_obj != None): print ('\n <dt><strong>%s (%s)</strong></dt>\n <dd>\n %s\n ' % (', '.join(se_obj.names), se_obj.oid, se_obj.desc)) if se_tree[se_oid]: print '<dl>' for sub_se_oid in se_tree[se_oid]: HTMLSchemaTree(schema, se_class, se_tree, sub_se_oid, (level + 1)) print '</dl>' print '</dd>'
[ "def", "HTMLSchemaTree", "(", "schema", ",", "se_class", ",", "se_tree", ",", "se_oid", ",", "level", ")", ":", "se_obj", "=", "schema", ".", "get_obj", "(", "se_class", ",", "se_oid", ")", "if", "(", "se_obj", "!=", "None", ")", ":", "print", "(", "...
html output for browser .
train
false
35,009
def Case(re): return SwitchCase(re, nocase=0)
[ "def", "Case", "(", "re", ")", ":", "return", "SwitchCase", "(", "re", ",", "nocase", "=", "0", ")" ]
case is an re which matches the same strings as re .
train
false
35,010
def patch_select(aggressive=True): patch_module('select') if aggressive: select = __import__('select') remove_item(select, 'epoll') remove_item(select, 'kqueue') remove_item(select, 'kevent') remove_item(select, 'devpoll') if (sys.version_info[:2] >= (3, 4)): select = __import__('select') orig_select_select = get_original('select', 'select') assert (select.select is not orig_select_select) selectors = __import__('selectors') if (selectors.SelectSelector._select in (select.select, orig_select_select)): def _select(self, *args, **kwargs): return select.select(*args, **kwargs) selectors.SelectSelector._select = _select _select._gevent_monkey = True if aggressive: remove_item(selectors, 'EpollSelector') remove_item(selectors, 'KqueueSelector') remove_item(selectors, 'DevpollSelector') selectors.DefaultSelector = selectors.SelectSelector
[ "def", "patch_select", "(", "aggressive", "=", "True", ")", ":", "patch_module", "(", "'select'", ")", "if", "aggressive", ":", "select", "=", "__import__", "(", "'select'", ")", "remove_item", "(", "select", ",", "'epoll'", ")", "remove_item", "(", "select"...
replace :func:select .
train
false
35,011
def encode_document(text, cats=None, id=None): text = unicode(text) cats = dict(((unicode(cat), bool(is_in_cat)) for (cat, is_in_cat) in (cats or {}).iteritems())) return (JSONValueProtocol.write(None, {'text': text, 'cats': cats, 'id': id}) + '\n')
[ "def", "encode_document", "(", "text", ",", "cats", "=", "None", ",", "id", "=", "None", ")", ":", "text", "=", "unicode", "(", "text", ")", "cats", "=", "dict", "(", "(", "(", "unicode", "(", "cat", ")", ",", "bool", "(", "is_in_cat", ")", ")", ...
encode a document as a json so that mrtextclassifier can read it .
train
false
35,012
def security_group_get_by_name(context, project_id, group_name, columns_to_join=None): return IMPL.security_group_get_by_name(context, project_id, group_name, columns_to_join=None)
[ "def", "security_group_get_by_name", "(", "context", ",", "project_id", ",", "group_name", ",", "columns_to_join", "=", "None", ")", ":", "return", "IMPL", ".", "security_group_get_by_name", "(", "context", ",", "project_id", ",", "group_name", ",", "columns_to_join...
returns a security group with the specified name from a project .
train
false
35,013
def get_cursors(source, spelling): root_cursor = (source if isinstance(source, Cursor) else source.cursor) cursors = [] for cursor in root_cursor.walk_preorder(): if (cursor.spelling == spelling): cursors.append(cursor) return cursors
[ "def", "get_cursors", "(", "source", ",", "spelling", ")", ":", "root_cursor", "=", "(", "source", "if", "isinstance", "(", "source", ",", "Cursor", ")", "else", "source", ".", "cursor", ")", "cursors", "=", "[", "]", "for", "cursor", "in", "root_cursor"...
obtain all cursors from a source object with a specific spelling .
train
false
35,014
def default_secure_cookie(): return is_https_enabled()
[ "def", "default_secure_cookie", "(", ")", ":", "return", "is_https_enabled", "(", ")" ]
enable secure cookies if https is enabled .
train
false
35,016
def _get_indentword(source): indent_word = u' ' try: for t in generate_tokens(source): if (t[0] == token.INDENT): indent_word = t[1] break except (SyntaxError, tokenize.TokenError): pass return indent_word
[ "def", "_get_indentword", "(", "source", ")", ":", "indent_word", "=", "u' '", "try", ":", "for", "t", "in", "generate_tokens", "(", "source", ")", ":", "if", "(", "t", "[", "0", "]", "==", "token", ".", "INDENT", ")", ":", "indent_word", "=", "t"...
return indentation type .
train
true
35,017
def parse_references(references, in_reply_to): replyto = (in_reply_to.split()[0] if in_reply_to else in_reply_to) if (not references): if replyto: return [replyto] else: return [] references = references.split() if (replyto not in references): references.append(replyto) return references
[ "def", "parse_references", "(", "references", ",", "in_reply_to", ")", ":", "replyto", "=", "(", "in_reply_to", ".", "split", "(", ")", "[", "0", "]", "if", "in_reply_to", "else", "in_reply_to", ")", "if", "(", "not", "references", ")", ":", "if", "reply...
parse a references: header and returns an array of messageids .
train
false
35,018
def get_dn(fqdn=None): val = [] LOG = logging.getLogger(__name__) try: if (fqdn is None): fqdn = socket.getfqdn() if ('.' in fqdn): tups = fqdn.split('.') if (len(tups) > 2): val.append(('.%s' % '.'.join(tups[(-2):]))) else: LOG.warning("allowed_hosts value to '*'. It is a security risk") val.append('*') else: LOG.warning("allowed_hosts value to '*'. It is a security risk") val.append('*') except: LOG.warning("allowed_hosts value to '*'. It is a security risk") val.append('*') return val
[ "def", "get_dn", "(", "fqdn", "=", "None", ")", ":", "val", "=", "[", "]", "LOG", "=", "logging", ".", "getLogger", "(", "__name__", ")", "try", ":", "if", "(", "fqdn", "is", "None", ")", ":", "fqdn", "=", "socket", ".", "getfqdn", "(", ")", "i...
this function returns fqdn .
train
false
35,019
def ALL_REGIONS_WITHOUT_CONTENT_RATINGS(): return (set(ALL_REGIONS) - set(ALL_REGIONS_WITH_CONTENT_RATINGS()))
[ "def", "ALL_REGIONS_WITHOUT_CONTENT_RATINGS", "(", ")", ":", "return", "(", "set", "(", "ALL_REGIONS", ")", "-", "set", "(", "ALL_REGIONS_WITH_CONTENT_RATINGS", "(", ")", ")", ")" ]
regions without ratings bodies and fallback to the generic rating body .
train
false
35,020
def _GetCompleteKeyOrError(arg): if isinstance(arg, Key): key = arg elif isinstance(arg, basestring): key = Key(arg) elif isinstance(arg, Entity): key = arg.key() elif (not isinstance(arg, Key)): raise datastore_errors.BadArgumentError(('Expects argument to be an Entity or Key; received %s (a %s).' % (arg, typename(arg)))) assert isinstance(key, Key) if (not key.has_id_or_name()): raise datastore_errors.BadKeyError(('Key %r is not complete.' % key)) return key
[ "def", "_GetCompleteKeyOrError", "(", "arg", ")", ":", "if", "isinstance", "(", "arg", ",", "Key", ")", ":", "key", "=", "arg", "elif", "isinstance", "(", "arg", ",", "basestring", ")", ":", "key", "=", "Key", "(", "arg", ")", "elif", "isinstance", "...
expects an entity or a key .
train
false
35,021
def findNodeJustBefore(target, nodes): while (target is not None): node = target.previousSibling while (node is not None): if (node in nodes): return node node = node.previousSibling target = target.parentNode raise RuntimeError('Oops')
[ "def", "findNodeJustBefore", "(", "target", ",", "nodes", ")", ":", "while", "(", "target", "is", "not", "None", ")", ":", "node", "=", "target", ".", "previousSibling", "while", "(", "node", "is", "not", "None", ")", ":", "if", "(", "node", "in", "n...
find the last element which is a sibling of c{target} and is in c{nodes} .
train
false
35,022
def _transaction_func(entering, exiting, using): if (using is None): using = DEFAULT_DB_ALIAS if callable(using): return Transaction(entering, exiting, DEFAULT_DB_ALIAS)(using) return Transaction(entering, exiting, using)
[ "def", "_transaction_func", "(", "entering", ",", "exiting", ",", "using", ")", ":", "if", "(", "using", "is", "None", ")", ":", "using", "=", "DEFAULT_DB_ALIAS", "if", "callable", "(", "using", ")", ":", "return", "Transaction", "(", "entering", ",", "e...
takes 3 things .
train
true
35,023
@with_setup(reset) def test_duplicate(): b1 = Bundle() b2 = Bundle() register('foo', b1) register('foo', b1) assert (len(_REGISTRY) == 1) assert_raises(RegistryError, register, 'foo', b2) assert_raises(RegistryError, register, 'foo', 's1', 's2', 's3')
[ "@", "with_setup", "(", "reset", ")", "def", "test_duplicate", "(", ")", ":", "b1", "=", "Bundle", "(", ")", "b2", "=", "Bundle", "(", ")", "register", "(", "'foo'", ",", "b1", ")", "register", "(", "'foo'", ",", "b1", ")", "assert", "(", "len", ...
test name clashes .
train
false
35,024
def format_score(scr, test): md = testMeta[test] if md: return '{0}\n{1}'.format(scr, md) else: return scr
[ "def", "format_score", "(", "scr", ",", "test", ")", ":", "md", "=", "testMeta", "[", "test", "]", "if", "md", ":", "return", "'{0}\\n{1}'", ".", "format", "(", "scr", ",", "md", ")", "else", ":", "return", "scr" ]
build up the score labels for the right y-axis by first appending a carriage return to each string and then tacking on the appropriate meta information .
train
false
35,025
def filePathToSafeString(filePath): retVal = filePath.replace('/', '_').replace('\\', '_') retVal = retVal.replace(' ', '_').replace(':', '_') return retVal
[ "def", "filePathToSafeString", "(", "filePath", ")", ":", "retVal", "=", "filePath", ".", "replace", "(", "'/'", ",", "'_'", ")", ".", "replace", "(", "'\\\\'", ",", "'_'", ")", "retVal", "=", "retVal", ".", "replace", "(", "' '", ",", "'_'", ")", "....
returns string representation of a given filepath safe for a single filename usage .
train
false
35,026
def assert_raise_message(exceptions, message, function, *args, **kwargs): try: function(*args, **kwargs) except exceptions as e: error_message = str(e) if (message not in error_message): raise AssertionError(('Error message does not include the expected string: %r. Observed error message: %r' % (message, error_message))) else: if isinstance(exceptions, tuple): names = ' or '.join((e.__name__ for e in exceptions)) else: names = exceptions.__name__ raise AssertionError(('%s not raised by %s' % (names, function.__name__)))
[ "def", "assert_raise_message", "(", "exceptions", ",", "message", ",", "function", ",", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "function", "(", "*", "args", ",", "**", "kwargs", ")", "except", "exceptions", "as", "e", ":", "error_message...
helper function to test error messages in exceptions .
train
false
35,027
def norm_brightness_err(img1, img2): if (img1.ndim == 3): (img1, img2) = (rgb2gray(img1), rgb2gray(img2)) ambe = np.abs((img1.mean() - img2.mean())) nbe = (ambe / dtype_range[img1.dtype.type][1]) return nbe
[ "def", "norm_brightness_err", "(", "img1", ",", "img2", ")", ":", "if", "(", "img1", ".", "ndim", "==", "3", ")", ":", "(", "img1", ",", "img2", ")", "=", "(", "rgb2gray", "(", "img1", ")", ",", "rgb2gray", "(", "img2", ")", ")", "ambe", "=", "...
normalized absolute mean brightness error between two images parameters img1 : array-like img2 : array-like returns norm_brightness_error : float normalized absolute mean brightness error .
train
false
35,028
@local_optimizer([gemm_no_inplace]) def local_gemm_to_ger(node): if (node.op == gemm_no_inplace): (z, a, x, y, b) = node.inputs if (x.broadcastable[1] and y.broadcastable[0]): xv = x.dimshuffle(0) yv = y.dimshuffle(1) try: bval = T.get_scalar_constant_value(b) except T.NotScalarConstantError: return if (bval == 1): rval = ger(z, a, xv, yv) return [rval] elif (bval == 0): zeros = T.zeros([x.shape[0], y.shape[1]], x.dtype) rval = ger(zeros, a, xv, yv) return [rval] else: return
[ "@", "local_optimizer", "(", "[", "gemm_no_inplace", "]", ")", "def", "local_gemm_to_ger", "(", "node", ")", ":", "if", "(", "node", ".", "op", "==", "gemm_no_inplace", ")", ":", "(", "z", ",", "a", ",", "x", ",", "y", ",", "b", ")", "=", "node", ...
gemm computing an outer-product -> ger .
train
false
35,029
def find_unit_clause(clauses, model): for clause in clauses: num_not_in_model = 0 for literal in disjuncts(clause): sym = literal_symbol(literal) if (sym not in model): num_not_in_model += 1 (P, value) = (sym, (not (literal.func is Not))) if (num_not_in_model == 1): return (P, value) return (None, None)
[ "def", "find_unit_clause", "(", "clauses", ",", "model", ")", ":", "for", "clause", "in", "clauses", ":", "num_not_in_model", "=", "0", "for", "literal", "in", "disjuncts", "(", "clause", ")", ":", "sym", "=", "literal_symbol", "(", "literal", ")", "if", ...
a unit clause has only 1 variable that is not bound in the model .
train
false
35,031
def _datacopied(arr, original): if (arr is original): return False if ((not isinstance(original, numpy.ndarray)) and hasattr(original, '__array__')): return False return (arr.base is None)
[ "def", "_datacopied", "(", "arr", ",", "original", ")", ":", "if", "(", "arr", "is", "original", ")", ":", "return", "False", "if", "(", "(", "not", "isinstance", "(", "original", ",", "numpy", ".", "ndarray", ")", ")", "and", "hasattr", "(", "origin...
strict check for arr not sharing any data with original .
train
false
35,032
def df_search(graph, root=None): seen = {} search = [] if (len(graph.nodes()) < 1): return search if (root is None): root = graph.nodes()[0] seen[root] = 1 search.append(root) current = graph.children(root) while (len(current) > 0): node = current[0] current = current[1:] if (node not in seen): search.append(node) seen[node] = 1 current = (graph.children(node) + current) return search
[ "def", "df_search", "(", "graph", ",", "root", "=", "None", ")", ":", "seen", "=", "{", "}", "search", "=", "[", "]", "if", "(", "len", "(", "graph", ".", "nodes", "(", ")", ")", "<", "1", ")", ":", "return", "search", "if", "(", "root", "is"...
depth first search of g .
train
false
35,033
def create_temp_file(buffer): (fd, absolute_file_name) = mkstemp(text=True) file = os.fdopen(fd, ('wb' if (type(buffer) is bytes) else 'w')) file.write(buffer) file.close() return absolute_file_name
[ "def", "create_temp_file", "(", "buffer", ")", ":", "(", "fd", ",", "absolute_file_name", ")", "=", "mkstemp", "(", "text", "=", "True", ")", "file", "=", "os", ".", "fdopen", "(", "fd", ",", "(", "'wb'", "if", "(", "type", "(", "buffer", ")", "is"...
helper method to create temp file on disk .
train
false
35,034
def getDotProduct(firstComplex, secondComplex): return ((firstComplex.real * secondComplex.real) + (firstComplex.imag * secondComplex.imag))
[ "def", "getDotProduct", "(", "firstComplex", ",", "secondComplex", ")", ":", "return", "(", "(", "firstComplex", ".", "real", "*", "secondComplex", ".", "real", ")", "+", "(", "firstComplex", ".", "imag", "*", "secondComplex", ".", "imag", ")", ")" ]
get the dot product of a pair of complexes .
train
false
35,035
def sanitize_help(parser): wrapper = textwrap.TextWrapper(width=79) parser.description = wrapper.fill(parser.description) if (not parser.epilog): return parser cleanlog = parser.epilog.replace(u':option:', u'').replace(u':program:', u'').replace(u'::', u':').replace(u'``', u'"') newlog = prev_section = u'' for section in cleanlog.split(u'\n\n'): if section.startswith(u' '): newlog += (section + u'\n') else: if prev_section.startswith(u' '): newlog += u'\n' newlog += (wrapper.fill(section) + u'\n\n') prev_section = section parser.epilog = newlog return parser
[ "def", "sanitize_help", "(", "parser", ")", ":", "wrapper", "=", "textwrap", ".", "TextWrapper", "(", "width", "=", "79", ")", "parser", ".", "description", "=", "wrapper", ".", "fill", "(", "parser", ".", "description", ")", "if", "(", "not", "parser", ...
remove sphinx directives & reflow text to width of 79 characters .
train
false
35,036
def addFakePlugin(testCase, dropinSource='fakeendpoint.py'): import sys savedModules = sys.modules.copy() savedPluginPath = list(plugins.__path__) def cleanup(): sys.modules.clear() sys.modules.update(savedModules) plugins.__path__[:] = savedPluginPath testCase.addCleanup(cleanup) fp = FilePath(testCase.mktemp()) fp.createDirectory() getModule(__name__).filePath.sibling(dropinSource).copyTo(fp.child(dropinSource)) plugins.__path__.append(fp.path)
[ "def", "addFakePlugin", "(", "testCase", ",", "dropinSource", "=", "'fakeendpoint.py'", ")", ":", "import", "sys", "savedModules", "=", "sys", ".", "modules", ".", "copy", "(", ")", "savedPluginPath", "=", "list", "(", "plugins", ".", "__path__", ")", "def",...
for the duration of c{testcase} .
train
false
35,038
def modified_since(path, dt): return (exists(path) and (last_modified_time(path) > dt))
[ "def", "modified_since", "(", "path", ",", "dt", ")", ":", "return", "(", "exists", "(", "path", ")", "and", "(", "last_modified_time", "(", "path", ")", ">", "dt", ")", ")" ]
check whether path was modified since dt .
train
false
35,040
def skipOverWhitespace(stream): tok = WHITESPACES[0] cnt = 0 while (tok in WHITESPACES): tok = stream.read(1) cnt += 1 return (cnt > 1)
[ "def", "skipOverWhitespace", "(", "stream", ")", ":", "tok", "=", "WHITESPACES", "[", "0", "]", "cnt", "=", "0", "while", "(", "tok", "in", "WHITESPACES", ")", ":", "tok", "=", "stream", ".", "read", "(", "1", ")", "cnt", "+=", "1", "return", "(", ...
similar to readnonwhitespace .
train
false
35,042
def get_csv_directory(args): if (not args.verbose): return csvdir = args.directory got_from = 'command line' if (csvdir is None): (csvdir, got_from) = defaults.get_default_csv_dir_with_origin() print(('Using CSV directory %(csvdir)s (from %(got_from)s)' % dict(csvdir=csvdir, got_from=got_from))) return csvdir
[ "def", "get_csv_directory", "(", "args", ")", ":", "if", "(", "not", "args", ".", "verbose", ")", ":", "return", "csvdir", "=", "args", ".", "directory", "got_from", "=", "'command line'", "if", "(", "csvdir", "is", "None", ")", ":", "(", "csvdir", ","...
prints and returns the csv directory were about to use .
train
false
35,044
def issue_tags(issue): labels = issue.get('labels', []) return [label['name'].replace('tag: ', '') for label in labels if label['name'].startswith('tag: ')]
[ "def", "issue_tags", "(", "issue", ")", ":", "labels", "=", "issue", ".", "get", "(", "'labels'", ",", "[", "]", ")", "return", "[", "label", "[", "'name'", "]", ".", "replace", "(", "'tag: '", ",", "''", ")", "for", "label", "in", "labels", "if", ...
returns list of tags for this issue .
train
true
35,045
def _make_renderer(): renderer = Renderer(string_encoding='ascii', file_encoding='ascii') return renderer
[ "def", "_make_renderer", "(", ")", ":", "renderer", "=", "Renderer", "(", "string_encoding", "=", "'ascii'", ",", "file_encoding", "=", "'ascii'", ")", "return", "renderer" ]
return a default renderer instance for testing purposes .
train
false
35,046
def smooth(x, window_len=11, window='flat'): if (x.ndim != 1): raise ValueError('smooth only accepts 1 dimension arrays.') if (x.size < window_len): raise ValueError('Input vector needs to be bigger than window size.') if (window_len < 3): return x if (not (window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman'])): raise ValueError("Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'") s = numpy.r_[(((2 * x[0]) - x[window_len:1:(-1)]), x, ((2 * x[(-1)]) - x[(-1):(- window_len):(-1)]))] if (window == 'flat'): w = numpy.ones(window_len, 'd') else: w = eval((('numpy.' + window) + '(window_len)')) y = numpy.convolve((w / w.sum()), s, mode='same') return y[(window_len - 1):((- window_len) + 1)]
[ "def", "smooth", "(", "x", ",", "window_len", "=", "11", ",", "window", "=", "'flat'", ")", ":", "if", "(", "x", ".", "ndim", "!=", "1", ")", ":", "raise", "ValueError", "(", "'smooth only accepts 1 dimension arrays.'", ")", "if", "(", "x", ".", "size"...
running smoothed average .
train
true
35,047
def _get_viewport(viewport): try: assert (viewport is not None) v = viewport.split('x') if (len(v) != 2): raise ValueError('Viewport must have width and height') (w, h) = (int(v[0]), int(v[1])) if (not ((99 < w < 4097) and (99 < h < 4097))): raise ValueError('Viewport out of bounds') except (AssertionError, TypeError, ValueError): return _DEFAULT_VIEWPORT return viewport
[ "def", "_get_viewport", "(", "viewport", ")", ":", "try", ":", "assert", "(", "viewport", "is", "not", "None", ")", "v", "=", "viewport", ".", "split", "(", "'x'", ")", "if", "(", "len", "(", "v", ")", "!=", "2", ")", ":", "raise", "ValueError", ...
check that viewport is valid and within acceptable bounds .
train
false
35,049
def _new_DatetimeIndex(cls, d): tz = d.pop('tz', None) result = cls.__new__(cls, verify_integrity=False, **d) if (tz is not None): result = result.tz_localize('UTC').tz_convert(tz) return result
[ "def", "_new_DatetimeIndex", "(", "cls", ",", "d", ")", ":", "tz", "=", "d", ".", "pop", "(", "'tz'", ",", "None", ")", "result", "=", "cls", ".", "__new__", "(", "cls", ",", "verify_integrity", "=", "False", ",", "**", "d", ")", "if", "(", "tz",...
this is called upon unpickling .
train
false
35,050
def check_dir(path): if (not os.path.exists(path)): os.mkdir(path)
[ "def", "check_dir", "(", "path", ")", ":", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ")", ":", "os", ".", "mkdir", "(", "path", ")" ]
create a directory if it doesnt exist .
train
false
35,051
@contextfunction def administration_module_list(context, modules): request = context['request'] response_format = 'html' if ('response_format' in context): response_format = context['response_format'] return Markup(render_to_string('core/administration/tags/module_list', {'modules': modules}, context_instance=RequestContext(request), response_format=response_format))
[ "@", "contextfunction", "def", "administration_module_list", "(", "context", ",", "modules", ")", ":", "request", "=", "context", "[", "'request'", "]", "response_format", "=", "'html'", "if", "(", "'response_format'", "in", "context", ")", ":", "response_format",...
print a list of users .
train
false
35,052
def create_fakedir(outputdir, tiles): for (tilepath, tilemtime) in tiles.iteritems(): dirpath = os.path.join(outputdir, *(str(x) for x in tilepath[:(-1)])) if (len(tilepath) == 0): imgname = 'base.png' else: imgname = (str(tilepath[(-1)]) + '.png') if (not os.path.exists(dirpath)): os.makedirs(dirpath) finalpath = os.path.join(dirpath, imgname) open(finalpath, 'w').close() os.utime(finalpath, (tilemtime, tilemtime))
[ "def", "create_fakedir", "(", "outputdir", ",", "tiles", ")", ":", "for", "(", "tilepath", ",", "tilemtime", ")", "in", "tiles", ".", "iteritems", "(", ")", ":", "dirpath", "=", "os", ".", "path", ".", "join", "(", "outputdir", ",", "*", "(", "str", ...
takes a base output directory and a tiles dict mapping tile paths to tile mtimes as returned by get_tile_set() .
train
false
35,053
def update_table(f, new): query = get_change_column_query(f, new) if query: frappe.db.sql(query)
[ "def", "update_table", "(", "f", ",", "new", ")", ":", "query", "=", "get_change_column_query", "(", "f", ",", "new", ")", "if", "query", ":", "frappe", ".", "db", ".", "sql", "(", "query", ")" ]
update table .
train
false
35,054
def muteLogLoading(mute): if (not mute): log_loading.setLevel(logging.WARNING) else: log_loading.setLevel(logging.CRITICAL)
[ "def", "muteLogLoading", "(", "mute", ")", ":", "if", "(", "not", "mute", ")", ":", "log_loading", ".", "setLevel", "(", "logging", ".", "WARNING", ")", "else", ":", "log_loading", ".", "setLevel", "(", "logging", ".", "CRITICAL", ")" ]
this mutes the log loading: used when a class is loaded several times .
train
false
35,057
def is_equivalent_mismatch(expected): def to_dict(mismatch): return {'details': mismatch.get_details(), 'description': mismatch.describe()} if (expected is None): return Is(None) return AfterPreprocessing(to_dict, Equals(to_dict(expected)), annotate=False)
[ "def", "is_equivalent_mismatch", "(", "expected", ")", ":", "def", "to_dict", "(", "mismatch", ")", ":", "return", "{", "'details'", ":", "mismatch", ".", "get_details", "(", ")", ",", "'description'", ":", "mismatch", ".", "describe", "(", ")", "}", "if",...
matches another mismatch .
train
false
35,058
def bulk_delete_ccx_override_fields(ccx, ids): ids = filter(None, ids) ids = list(set(ids)) if ids: CcxFieldOverride.objects.filter(ccx=ccx, id__in=ids).delete()
[ "def", "bulk_delete_ccx_override_fields", "(", "ccx", ",", "ids", ")", ":", "ids", "=", "filter", "(", "None", ",", "ids", ")", "ids", "=", "list", "(", "set", "(", "ids", ")", ")", "if", "ids", ":", "CcxFieldOverride", ".", "objects", ".", "filter", ...
bulk delete for ccxfieldoverride model .
train
false
35,059
def unmap_url_cache(cachedir, url, expected_hash, method='md5'): cachedir = os.path.realpath(cachedir) if (not os.path.isdir(cachedir)): try: os.makedirs(cachedir) except Exception: raise ValueError(('Could not create cache directory %s' % cachedir)) file_from_url = os.path.basename(url) file_local_path = os.path.join(cachedir, file_from_url) file_hash = None failure_counter = 0 while (not (file_hash == expected_hash)): if os.path.isfile(file_local_path): file_hash = hash_file(file_local_path, method) if (file_hash == expected_hash): src = file_from_url else: logging.error(('Seems that file %s is corrupted, trying to download it again' % file_from_url)) src = url failure_counter += 1 else: src = url if (failure_counter > 1): raise EnvironmentError(('Consistently failed to download the package %s. Aborting further download attempts. This might mean either the network connection has problems or the expected hash string that was determined for this file is wrong' % file_from_url)) file_path = utils.unmap_url(cachedir, src, cachedir) return file_path
[ "def", "unmap_url_cache", "(", "cachedir", ",", "url", ",", "expected_hash", ",", "method", "=", "'md5'", ")", ":", "cachedir", "=", "os", ".", "path", ".", "realpath", "(", "cachedir", ")", "if", "(", "not", "os", ".", "path", ".", "isdir", "(", "ca...
downloads a file from a url to a cache directory .
train
false
35,060
def check_submodules(): if (not os.path.exists('.git')): return with open('.gitmodules') as f: for l in f: if ('path' in l): p = l.split('=')[(-1)].strip() if (not os.path.exists(p)): raise ValueError(('Submodule %s missing' % p)) proc = subprocess.Popen(['git', 'submodule', 'status'], stdout=subprocess.PIPE) (status, _) = proc.communicate() status = status.decode('ascii', 'replace') for line in status.splitlines(): if (line.startswith('-') or line.startswith('+')): raise ValueError(('Submodule not clean: %s' % line))
[ "def", "check_submodules", "(", ")", ":", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "'.git'", ")", ")", ":", "return", "with", "open", "(", "'.gitmodules'", ")", "as", "f", ":", "for", "l", "in", "f", ":", "if", "(", "'path'", "in"...
verify that the submodules are checked out and clean use git submodule update --init; on failure .
train
true
35,061
def _from_bytes(value): result = (value.decode('utf-8') if isinstance(value, six.binary_type) else value) if isinstance(result, six.text_type): return result else: raise ValueError('{0!r} could not be converted to unicode'.format(value))
[ "def", "_from_bytes", "(", "value", ")", ":", "result", "=", "(", "value", ".", "decode", "(", "'utf-8'", ")", "if", "isinstance", "(", "value", ",", "six", ".", "binary_type", ")", "else", "value", ")", "if", "isinstance", "(", "result", ",", "six", ...
converts bytes to a string value .
train
true
35,063
def read_device_map(path): devices = {} with open(path, 'r') as stream: for line in stream: piece = line.strip().split(',') devices[int(piece[0], 16)] = piece[1] return devices
[ "def", "read_device_map", "(", "path", ")", ":", "devices", "=", "{", "}", "with", "open", "(", "path", ",", "'r'", ")", "as", "stream", ":", "for", "line", "in", "stream", ":", "piece", "=", "line", ".", "strip", "(", ")", ".", "split", "(", "',...
a helper method to read the device path to address mapping from file:: 0x0001 .
train
false
35,064
def rel_query(rel, thing_id, name, filters=[]): q = rel._query((rel.c._thing1_id == thing_id), (rel.c._t2_deleted == False), (rel.c._name == name), sort=desc('_date'), eager_load=True) if filters: q._filter(*filters) return q
[ "def", "rel_query", "(", "rel", ",", "thing_id", ",", "name", ",", "filters", "=", "[", "]", ")", ":", "q", "=", "rel", ".", "_query", "(", "(", "rel", ".", "c", ".", "_thing1_id", "==", "thing_id", ")", ",", "(", "rel", ".", "c", ".", "_t2_del...
general relationship query .
train
false
35,065
@profiler.trace def subnet_create(request, network_id, **kwargs): LOG.debug(('subnet_create(): netid=%s, kwargs=%s' % (network_id, kwargs))) body = {'subnet': {'network_id': network_id}} if ('tenant_id' not in kwargs): kwargs['tenant_id'] = request.user.project_id body['subnet'].update(kwargs) subnet = neutronclient(request).create_subnet(body=body).get('subnet') return Subnet(subnet)
[ "@", "profiler", ".", "trace", "def", "subnet_create", "(", "request", ",", "network_id", ",", "**", "kwargs", ")", ":", "LOG", ".", "debug", "(", "(", "'subnet_create(): netid=%s, kwargs=%s'", "%", "(", "network_id", ",", "kwargs", ")", ")", ")", "body", ...
create a subnet on a specified network .
train
true
35,066
def list_patterns(refresh=False): if refresh: refresh_db() return _get_patterns()
[ "def", "list_patterns", "(", "refresh", "=", "False", ")", ":", "if", "refresh", ":", "refresh_db", "(", ")", "return", "_get_patterns", "(", ")" ]
list all known patterns from available repos .
train
false
35,068
def normalize_encoding(encoding): if isinstance(encoding, bytes): encoding = str(encoding, 'ascii') chars = [] punct = False for c in encoding: if (c.isalnum() or (c == '.')): if (punct and chars): chars.append('_') chars.append(c) punct = False else: punct = True return ''.join(chars)
[ "def", "normalize_encoding", "(", "encoding", ")", ":", "if", "isinstance", "(", "encoding", ",", "bytes", ")", ":", "encoding", "=", "str", "(", "encoding", ",", "'ascii'", ")", "chars", "=", "[", "]", "punct", "=", "False", "for", "c", "in", "encodin...
normalize an encoding name .
train
false
35,069
def read_mnist_labels(fn): with open_if_filename(fn, 'rb') as f: (magic, number) = struct.unpack('>ii', f.read(8)) if (magic != MNIST_LABEL_MAGIC): raise ValueError(('wrong magic number reading MNIST label file: ' + fn)) array = numpy.fromfile(f, dtype='uint8') return array
[ "def", "read_mnist_labels", "(", "fn", ")", ":", "with", "open_if_filename", "(", "fn", ",", "'rb'", ")", "as", "f", ":", "(", "magic", ",", "number", ")", "=", "struct", ".", "unpack", "(", "'>ii'", ",", "f", ".", "read", "(", "8", ")", ")", "if...
read mnist labels from the original ubyte file format .
train
false
35,070
def monitor_save_globals(sock, settings, filename): return communicate(sock, '__save_globals__()', settings=[settings, filename])
[ "def", "monitor_save_globals", "(", "sock", ",", "settings", ",", "filename", ")", ":", "return", "communicate", "(", "sock", ",", "'__save_globals__()'", ",", "settings", "=", "[", "settings", ",", "filename", "]", ")" ]
save globals() to file .
train
false
35,071
def compile_gpu_func(nan_is_error, inf_is_error, big_is_error): global f_gpumin, f_gpumax, f_gpuabsmax if (not cuda.cuda_available): return guard_input = cuda.fvector('nan_guard') cuda_compile_failed = False if ((nan_is_error or inf_is_error) and (f_gpumin is None)): try: f_gpumin = theano.function([guard_input], T.min(guard_input), mode='FAST_RUN') except RuntimeError: cuda_compile_failed = True if (inf_is_error and (not cuda_compile_failed) and (f_gpumax is None)): try: f_gpumax = theano.function([guard_input], T.max(guard_input), mode='FAST_RUN') except RuntimeError: cuda_compile_failed = True if (big_is_error and (not cuda_compile_failed) and (f_gpuabsmax is None)): try: f_gpuabsmax = theano.function([guard_input], T.max(T.abs_(guard_input)), mode='FAST_RUN') except RuntimeError: cuda_compile_failed = True
[ "def", "compile_gpu_func", "(", "nan_is_error", ",", "inf_is_error", ",", "big_is_error", ")", ":", "global", "f_gpumin", ",", "f_gpumax", ",", "f_gpuabsmax", "if", "(", "not", "cuda", ".", "cuda_available", ")", ":", "return", "guard_input", "=", "cuda", ".",...
compile utility function used by contains_nan and contains_inf .
train
false
35,073
def getDictionarySplitWords(dictionary, value): if getIsQuoted(value): return [value] for dictionaryKey in dictionary.keys(): value = value.replace(dictionaryKey, ((' ' + dictionaryKey) + ' ')) dictionarySplitWords = [] for word in value.split(): dictionarySplitWords.append(word) return dictionarySplitWords
[ "def", "getDictionarySplitWords", "(", "dictionary", ",", "value", ")", ":", "if", "getIsQuoted", "(", "value", ")", ":", "return", "[", "value", "]", "for", "dictionaryKey", "in", "dictionary", ".", "keys", "(", ")", ":", "value", "=", "value", ".", "re...
get split line for evaluators .
train
false
35,076
def fix_script(path): if os.path.isfile(path): script = open(path, 'rb') try: firstline = script.readline() if (not firstline.startswith(binary('#!python'))): return False exename = sys.executable.encode(sys.getfilesystemencoding()) firstline = ((binary('#!') + exename) + binary(os.linesep)) rest = script.read() finally: script.close() script = open(path, 'wb') try: script.write(firstline) script.write(rest) finally: script.close() return True
[ "def", "fix_script", "(", "path", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "script", "=", "open", "(", "path", ",", "'rb'", ")", "try", ":", "firstline", "=", "script", ".", "readline", "(", ")", "if", "(", "not", ...
replace #!python with #!/path/to/python return true if file was changed .
train
true
35,077
def _check_multiple_ips_to_host(config): host_ip_map = {} for (groupnames, group) in config.items(): if ('_hosts' in groupnames): for (hostname, entries) in group.items(): if (hostname not in host_ip_map): host_ip_map[hostname] = entries['ip'] else: current_ip = host_ip_map[hostname] new_ip = entries['ip'] if (not (current_ip == new_ip)): raise MultipleIpForHostError(hostname, current_ip, new_ip) logger.debug('No hosts with multiple IPs found.') return True
[ "def", "_check_multiple_ips_to_host", "(", "config", ")", ":", "host_ip_map", "=", "{", "}", "for", "(", "groupnames", ",", "group", ")", "in", "config", ".", "items", "(", ")", ":", "if", "(", "'_hosts'", "in", "groupnames", ")", ":", "for", "(", "hos...
check for multiple ips assigned to a single hostname .
train
false
35,078
def makeStatBar(width, maxPosition, doneChar='=', undoneChar='-', currentChar='>'): aValue = (width / float(maxPosition)) def statBar(position, force=0, last=['']): assert (len(last) == 1), "Don't mess with the last parameter." done = int((aValue * position)) toDo = ((width - done) - 2) result = ('[%s%s%s]' % ((doneChar * done), currentChar, (undoneChar * toDo))) if force: last[0] = result return result if (result == last[0]): return '' last[0] = result return result statBar.__doc__ = ("statBar(position, force = 0) -> '[%s%s%s]'-style progress bar\n\n returned string is %d characters long, and the range goes from 0..%d.\n The 'position' argument is where the '%s' will be drawn. If force is false,\n '' will be returned instead if the resulting progress bar is identical to the\n previously returned progress bar.\n" % ((doneChar * 3), currentChar, (undoneChar * 3), width, maxPosition, currentChar)) return statBar
[ "def", "makeStatBar", "(", "width", ",", "maxPosition", ",", "doneChar", "=", "'='", ",", "undoneChar", "=", "'-'", ",", "currentChar", "=", "'>'", ")", ":", "aValue", "=", "(", "width", "/", "float", "(", "maxPosition", ")", ")", "def", "statBar", "("...
creates a function that will return a string representing a progress bar .
train
false
35,081
def _classname_to_internal_name(s): if (not s): return s while True: match = re.search('(?:Bib)?(?:La)?TeX', s) if match: s = s.replace(match.group(0), (match.group(0)[0] + match.group(0)[1:].lower())) else: break s = re.sub('(?<=[a-z])[A-Z]|(?<!^)[A-Z](?=[a-z])', '_\\g<0>', s).lower() if s.endswith('_plugin'): s = s[:(-7)] return s
[ "def", "_classname_to_internal_name", "(", "s", ")", ":", "if", "(", "not", "s", ")", ":", "return", "s", "while", "True", ":", "match", "=", "re", ".", "search", "(", "'(?:Bib)?(?:La)?TeX'", ",", "s", ")", "if", "match", ":", "s", "=", "s", ".", "...
converts a python class name in to an internal name the intention here is to mirror how st treats *command objects .
train
false
35,083
def loadText(fileName, encoding='utf8'): try: fp = codecs.open(fileName, mode='r', encoding=encoding) content = fp.readlines() fp.close() logger.log(CUSTOM_LOGGING.SYSINFO, ('return file "%s" content .' % fileName)) return content except Exception as e: logger.log(CUSTOM_LOGGING.WARNING, e)
[ "def", "loadText", "(", "fileName", ",", "encoding", "=", "'utf8'", ")", ":", "try", ":", "fp", "=", "codecs", ".", "open", "(", "fileName", ",", "mode", "=", "'r'", ",", "encoding", "=", "encoding", ")", "content", "=", "fp", ".", "readlines", "(", ...
read file with given filename and encoding .
train
false
35,084
def horizontal_flip_async(image_data, output_encoding=PNG, quality=None, correct_orientation=UNCHANGED_ORIENTATION, rpc=None, transparent_substitution_rgb=None): image = Image(image_data) image.horizontal_flip() image.set_correct_orientation(correct_orientation) return image.execute_transforms_async(output_encoding=output_encoding, quality=quality, rpc=rpc, transparent_substitution_rgb=transparent_substitution_rgb)
[ "def", "horizontal_flip_async", "(", "image_data", ",", "output_encoding", "=", "PNG", ",", "quality", "=", "None", ",", "correct_orientation", "=", "UNCHANGED_ORIENTATION", ",", "rpc", "=", "None", ",", "transparent_substitution_rgb", "=", "None", ")", ":", "imag...
flip the image horizontally - async version .
train
false
35,085
def _compute_log_det_cholesky(matrix_chol, covariance_type, n_features): if (covariance_type == 'full'): (n_components, _, _) = matrix_chol.shape log_det_chol = np.sum(np.log(matrix_chol.reshape(n_components, (-1))[:, ::(n_features + 1)]), 1) elif (covariance_type == 'tied'): log_det_chol = np.sum(np.log(np.diag(matrix_chol))) elif (covariance_type == 'diag'): log_det_chol = np.sum(np.log(matrix_chol), axis=1) else: log_det_chol = (n_features * np.log(matrix_chol)) return log_det_chol
[ "def", "_compute_log_det_cholesky", "(", "matrix_chol", ",", "covariance_type", ",", "n_features", ")", ":", "if", "(", "covariance_type", "==", "'full'", ")", ":", "(", "n_components", ",", "_", ",", "_", ")", "=", "matrix_chol", ".", "shape", "log_det_chol",...
compute the log-det of the cholesky decomposition of matrices .
train
false
35,088
@needs(['reset']) def reset_hard(): sh('git clean -dxf')
[ "@", "needs", "(", "[", "'reset'", "]", ")", "def", "reset_hard", "(", ")", ":", "sh", "(", "'git clean -dxf'", ")" ]
reset a development environment .
train
false
35,089
def get_demo_exploration_components(demo_path): demo_filepath = os.path.join(feconf.SAMPLE_EXPLORATIONS_DIR, demo_path) if demo_filepath.endswith('yaml'): file_contents = utils.get_file_contents(demo_filepath) return (file_contents, []) elif os.path.isdir(demo_filepath): return utils.get_exploration_components_from_dir(demo_filepath) else: raise Exception(('Unrecognized file path: %s' % demo_path))
[ "def", "get_demo_exploration_components", "(", "demo_path", ")", ":", "demo_filepath", "=", "os", ".", "path", ".", "join", "(", "feconf", ".", "SAMPLE_EXPLORATIONS_DIR", ",", "demo_path", ")", "if", "demo_filepath", ".", "endswith", "(", "'yaml'", ")", ":", "...
gets the content of demo_path in the sample explorations folder .
train
false
35,090
def rsync_module_interpolation(template, device): replacements = {'ip': rsync_ip(device.get('ip', '')), 'port': device.get('port', ''), 'replication_ip': rsync_ip(device.get('replication_ip', '')), 'replication_port': device.get('replication_port', ''), 'region': device.get('region', ''), 'zone': device.get('zone', ''), 'device': device.get('device', ''), 'meta': device.get('meta', '')} try: module = template.format(**replacements) except KeyError as e: raise ValueError(('Cannot interpolate rsync_module, invalid variable: %s' % e)) return module
[ "def", "rsync_module_interpolation", "(", "template", ",", "device", ")", ":", "replacements", "=", "{", "'ip'", ":", "rsync_ip", "(", "device", ".", "get", "(", "'ip'", ",", "''", ")", ")", ",", "'port'", ":", "device", ".", "get", "(", "'port'", ",",...
interpolate devices variables inside a rsync module template .
train
false
35,091
def from_scipy_sparse_matrix(A, parallel_edges=False, create_using=None, edge_attribute='weight'): G = _prep_create_using(create_using) (n, m) = A.shape if (n != m): raise nx.NetworkXError(('Adjacency matrix is not square. nx,ny=%s' % (A.shape,))) G.add_nodes_from(range(n)) triples = _generate_weighted_edges(A) if ((A.dtype.kind in ('i', 'u')) and G.is_multigraph() and parallel_edges): chain = itertools.chain.from_iterable triples = chain((((u, v, 1) for d in range(w)) for (u, v, w) in triples)) if (G.is_multigraph() and (not G.is_directed())): triples = ((u, v, d) for (u, v, d) in triples if (u <= v)) G.add_weighted_edges_from(triples, weight=edge_attribute) return G
[ "def", "from_scipy_sparse_matrix", "(", "A", ",", "parallel_edges", "=", "False", ",", "create_using", "=", "None", ",", "edge_attribute", "=", "'weight'", ")", ":", "G", "=", "_prep_create_using", "(", "create_using", ")", "(", "n", ",", "m", ")", "=", "A...
creates a new graph from an adjacency matrix given as a scipy sparse matrix .
train
false
35,092
def toVolts(raw): return (DIGITAL_ANALOG_16_STEP * raw)
[ "def", "toVolts", "(", "raw", ")", ":", "return", "(", "DIGITAL_ANALOG_16_STEP", "*", "raw", ")" ]
convert raw iosync analog input value to voltage value .
train
false
35,093
def _handle_get(gs_stub, filename, param_dict, headers): if (filename.rfind('/') == 0): return _handle_get_bucket(gs_stub, filename, param_dict) else: result = _handle_head(gs_stub, filename) if (result.status_code == 404): return result (start, end) = _Range(headers).value st_size = result.headers['content-length'] if (end is None): end = (st_size - 1) result.headers['content-range'] = ('bytes: %d-%d/%d' % (start, end, st_size)) result.content = gs_stub.get_object(filename, start, end) return result
[ "def", "_handle_get", "(", "gs_stub", ",", "filename", ",", "param_dict", ",", "headers", ")", ":", "if", "(", "filename", ".", "rfind", "(", "'/'", ")", "==", "0", ")", ":", "return", "_handle_get_bucket", "(", "gs_stub", ",", "filename", ",", "param_di...
handle get object and get bucket .
train
false
35,094
def iddr_rsvd(m, n, matvect, matvec, k): (U, V, S, ier) = _id.iddr_rsvd(m, n, matvect, matvec, k) if (ier != 0): raise _RETCODE_ERROR return (U, V, S)
[ "def", "iddr_rsvd", "(", "m", ",", "n", ",", "matvect", ",", "matvec", ",", "k", ")", ":", "(", "U", ",", "V", ",", "S", ",", "ier", ")", "=", "_id", ".", "iddr_rsvd", "(", "m", ",", "n", ",", "matvect", ",", "matvec", ",", "k", ")", "if", ...
compute svd of a real matrix to a specified rank using random matrix-vector multiplication .
train
false
35,096
def insert_default_options(): options = get_default_options() options.reverse() for arg in options: sys.argv.insert(1, arg)
[ "def", "insert_default_options", "(", ")", ":", "options", "=", "get_default_options", "(", ")", "options", ".", "reverse", "(", ")", "for", "arg", "in", "options", ":", "sys", ".", "argv", ".", "insert", "(", "1", ",", "arg", ")" ]
insert default options to sys .
train
true
35,097
def _is_dupe(msg, request): storage = django_messages.get_messages(request) if (not storage): return False try: smsg = unicode(msg) is_dupe = False for message in storage: if (unicode(message) == smsg): is_dupe = True break except (UnicodeDecodeError, UnicodeEncodeError): return False storage.used = False return is_dupe
[ "def", "_is_dupe", "(", "msg", ",", "request", ")", ":", "storage", "=", "django_messages", ".", "get_messages", "(", "request", ")", "if", "(", "not", "storage", ")", ":", "return", "False", "try", ":", "smsg", "=", "unicode", "(", "msg", ")", "is_dup...
returns whether a particular message is already cued for display .
train
false
35,099
def thrift_library_config(append=None, **kwargs): blade_config.update_config('thrift_config', append, kwargs)
[ "def", "thrift_library_config", "(", "append", "=", "None", ",", "**", "kwargs", ")", ":", "blade_config", ".", "update_config", "(", "'thrift_config'", ",", "append", ",", "kwargs", ")" ]
thrift config .
train
false
35,100
def get_init_path(directory_path): for (suffix, _, _) in imp.get_suffixes(): path = os.path.join(directory_path, ('__init__' + suffix)) if os.path.exists(path): return path return None
[ "def", "get_init_path", "(", "directory_path", ")", ":", "for", "(", "suffix", ",", "_", ",", "_", ")", "in", "imp", ".", "get_suffixes", "(", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "directory_path", ",", "(", "'__init__'", "+", ...
the __init__ file can be searched in a directory .
train
false
35,101
def _build_xpath_expr(attrs): if ('class_' in attrs): attrs['class'] = attrs.pop('class_') s = [(u('@%s=%r') % (k, v)) for (k, v) in iteritems(attrs)] return (u('[%s]') % ' and '.join(s))
[ "def", "_build_xpath_expr", "(", "attrs", ")", ":", "if", "(", "'class_'", "in", "attrs", ")", ":", "attrs", "[", "'class'", "]", "=", "attrs", ".", "pop", "(", "'class_'", ")", "s", "=", "[", "(", "u", "(", "'@%s=%r'", ")", "%", "(", "k", ",", ...
build an xpath expression to simulate bs4s ability to pass in kwargs to search for attributes when using the lxml parser .
train
false
35,102
def save_caffe_image(img, filename, autoscale=True, autoscale_center=None): if (len(img.shape) == 2): img = np.tile(img[:, :, np.newaxis], (1, 1, 3)) else: img = img[::(-1)].transpose((1, 2, 0)) if (autoscale_center is not None): img = norm01c(img, autoscale_center) elif autoscale: img = img.copy() img -= img.min() img *= (1.0 / (img.max() + 1e-10)) skimage.io.imsave(filename, img)
[ "def", "save_caffe_image", "(", "img", ",", "filename", ",", "autoscale", "=", "True", ",", "autoscale_center", "=", "None", ")", ":", "if", "(", "len", "(", "img", ".", "shape", ")", "==", "2", ")", ":", "img", "=", "np", ".", "tile", "(", "img", ...
takes an image in caffe format or and saves it to a file .
train
false
35,103
def _retry_sys_call(f, *args, **kwargs): while True: rc = f(*args) try: _check_rc(rc) except InterruptedSystemCall: continue else: break
[ "def", "_retry_sys_call", "(", "f", ",", "*", "args", ",", "**", "kwargs", ")", ":", "while", "True", ":", "rc", "=", "f", "(", "*", "args", ")", "try", ":", "_check_rc", "(", "rc", ")", "except", "InterruptedSystemCall", ":", "continue", "else", ":"...
make a call .
train
false
35,104
def atomic_replace(src_filename, dst_filename): def same_fs(filename_a, filename_b): '\n Checks if both files reside on the\n same FS device\n ' stats_a = os.stat(filename_a) stats_b = os.stat(filename_b) return (stats_a.st_dev == stats_b.st_dev) if (os.path.exists(dst_filename) and (not same_fs(src_filename, dst_filename))): dst_path = os.path.dirname(os.path.abspath(dst_filename)) dst_temp_filename = os.tempnam(dst_path) shutil.copy(src_filename, dst_temp_filename) shutil.move(dst_temp_filename, dst_filename) else: shutil.move(src_filename, dst_filename)
[ "def", "atomic_replace", "(", "src_filename", ",", "dst_filename", ")", ":", "def", "same_fs", "(", "filename_a", ",", "filename_b", ")", ":", "stats_a", "=", "os", ".", "stat", "(", "filename_a", ")", "stats_b", "=", "os", ".", "stat", "(", "filename_b", ...
does an "atomic" replace of a file by another .
train
false
35,105
def eta(lam): if (lam > 0): return mp.sqrt((2 * (lam - mp.log((lam + 1))))) elif (lam < 0): return (- mp.sqrt((2 * (lam - mp.log((lam + 1)))))) else: return 0
[ "def", "eta", "(", "lam", ")", ":", "if", "(", "lam", ">", "0", ")", ":", "return", "mp", ".", "sqrt", "(", "(", "2", "*", "(", "lam", "-", "mp", ".", "log", "(", "(", "lam", "+", "1", ")", ")", ")", ")", ")", "elif", "(", "lam", "<", ...
function from dlmf 8 .
train
false
35,107
def onGlobalDataDel(key): DEBUG_MSG(('onDelGlobalData: %s' % key))
[ "def", "onGlobalDataDel", "(", "key", ")", ":", "DEBUG_MSG", "(", "(", "'onDelGlobalData: %s'", "%", "key", ")", ")" ]
kbengine method .
train
false
35,108
def getTreeBuilder(treeType, implementation=None, **kwargs): treeType = treeType.lower() if (treeType not in treeBuilderCache): if (treeType == 'dom'): import dom if (implementation == None): from xml.dom import minidom implementation = minidom return dom.getDomModule(implementation, **kwargs).TreeBuilder elif (treeType == 'simpletree'): import simpletree treeBuilderCache[treeType] = simpletree.TreeBuilder elif (treeType == 'beautifulsoup'): import soup treeBuilderCache[treeType] = soup.TreeBuilder elif (treeType == 'lxml'): import etree_lxml treeBuilderCache[treeType] = etree_lxml.TreeBuilder elif (treeType == 'etree'): if (implementation == None): try: import xml.etree.cElementTree as ET except ImportError: try: import xml.etree.ElementTree as ET except ImportError: try: import cElementTree as ET except ImportError: import elementtree.ElementTree as ET implementation = ET import etree return etree.getETreeModule(implementation, **kwargs).TreeBuilder else: raise ValueError(('Unrecognised treebuilder "%s" ' % treeType)) return treeBuilderCache.get(treeType)
[ "def", "getTreeBuilder", "(", "treeType", ",", "implementation", "=", "None", ",", "**", "kwargs", ")", ":", "treeType", "=", "treeType", ".", "lower", "(", ")", "if", "(", "treeType", "not", "in", "treeBuilderCache", ")", ":", "if", "(", "treeType", "==...
get a treebuilder class for various types of tree with built-in support treetype - the name of the tree type required .
train
false
35,109
@commands(u'subject') @example(u'.subject roll call') def meetingsubject(bot, trigger): if (not ismeetingrunning(trigger.sender)): bot.say(u"Can't do that, start meeting first") return if (not trigger.group(2)): bot.say(u'what is the subject?') return if (not ischair(trigger.nick, trigger.sender)): bot.say(u'Only meeting head or chairs can do that') return meetings_dict[trigger.sender][u'current_subject'] = trigger.group(2) logfile = codecs.open(((((meeting_log_path + trigger.sender) + u'/') + figure_logfile_name(trigger.sender)) + u'.html'), u'a', encoding=u'utf-8') logfile.write(((u'</ul><h3>' + trigger.group(2)) + u'</h3><ul>')) logfile.close() logplain(((((u'Current subject: ' + trigger.group(2)) + u', (set by ') + trigger.nick) + u')'), trigger.sender) bot.say((u'\x02Current subject\x0f: ' + trigger.group(2)))
[ "@", "commands", "(", "u'subject'", ")", "@", "example", "(", "u'.subject roll call'", ")", "def", "meetingsubject", "(", "bot", ",", "trigger", ")", ":", "if", "(", "not", "ismeetingrunning", "(", "trigger", ".", "sender", ")", ")", ":", "bot", ".", "sa...
change the meeting subject .
train
false
35,110
@login_required def _get_item_in_course(request, usage_key): usage_key = usage_key.replace(course_key=modulestore().fill_in_run(usage_key.course_key)) course_key = usage_key.course_key if (not has_course_author_access(request.user, course_key)): raise PermissionDenied() course = modulestore().get_course(course_key) item = modulestore().get_item(usage_key, depth=1) lms_link = get_lms_link_for_item(item.location) preview_lms_link = get_lms_link_for_item(item.location, preview=True) return (course, item, lms_link, preview_lms_link)
[ "@", "login_required", "def", "_get_item_in_course", "(", "request", ",", "usage_key", ")", ":", "usage_key", "=", "usage_key", ".", "replace", "(", "course_key", "=", "modulestore", "(", ")", ".", "fill_in_run", "(", "usage_key", ".", "course_key", ")", ")", ...
helper method for getting the old location .
train
false
35,111
def dist_matrix_linkage(matrix, linkage=AVERAGE): distances = condensedform(matrix) if ((linkage == WARD) and (not _HAS_WARD_LINKAGE_FROM_DIST)): y = numpy.asarray(distances, dtype=float) scipy.spatial.distance.is_valid_y(y, throw=True) N = scipy.spatial.distance.num_obs_y(y) Z = numpy.zeros(((N - 1), 4)) method = scipy.cluster.hierarchy._cpy_euclid_methods['ward'] scipy.cluster.hierarchy._hierarchy.linkage(y, Z, int(N), int(method)) return Z else: return scipy.cluster.hierarchy.linkage(distances, method=linkage)
[ "def", "dist_matrix_linkage", "(", "matrix", ",", "linkage", "=", "AVERAGE", ")", ":", "distances", "=", "condensedform", "(", "matrix", ")", "if", "(", "(", "linkage", "==", "WARD", ")", "and", "(", "not", "_HAS_WARD_LINKAGE_FROM_DIST", ")", ")", ":", "y"...
return linkage using a precomputed distance matrix .
train
false
35,112
def test_io_dig_points(): tempdir = _TempDir() points = _read_dig_points(hsp_fname) dest = op.join(tempdir, 'test.txt') dest_bad = op.join(tempdir, 'test.mne') assert_raises(ValueError, _write_dig_points, dest, points[:, :2]) assert_raises(ValueError, _write_dig_points, dest_bad, points) _write_dig_points(dest, points) points1 = _read_dig_points(dest, unit='m') err = 'Dig points diverged after writing and reading.' assert_array_equal(points, points1, err) points2 = np.array([[(-106.93), 99.8], [99.8, 68.81]]) np.savetxt(dest, points2, delimiter=' DCTB ', newline='\n') assert_raises(ValueError, _read_dig_points, dest)
[ "def", "test_io_dig_points", "(", ")", ":", "tempdir", "=", "_TempDir", "(", ")", "points", "=", "_read_dig_points", "(", "hsp_fname", ")", "dest", "=", "op", ".", "join", "(", "tempdir", ",", "'test.txt'", ")", "dest_bad", "=", "op", ".", "join", "(", ...
test writing for dig files .
train
false
35,113
def vertical_flip_async(image_data, output_encoding=PNG, quality=None, correct_orientation=UNCHANGED_ORIENTATION, rpc=None, transparent_substitution_rgb=None): image = Image(image_data) image.vertical_flip() image.set_correct_orientation(correct_orientation) return image.execute_transforms_async(output_encoding=output_encoding, quality=quality, rpc=rpc, transparent_substitution_rgb=transparent_substitution_rgb)
[ "def", "vertical_flip_async", "(", "image_data", ",", "output_encoding", "=", "PNG", ",", "quality", "=", "None", ",", "correct_orientation", "=", "UNCHANGED_ORIENTATION", ",", "rpc", "=", "None", ",", "transparent_substitution_rgb", "=", "None", ")", ":", "image"...
flip the image vertically - async version .
train
false
35,119
def arcball_constrain_to_axis(point, axis): v = numpy.array(point, dtype=numpy.float64, copy=True) a = numpy.array(axis, dtype=numpy.float64, copy=True) v -= (a * numpy.dot(a, v)) n = vector_norm(v) if (n > _EPS): if (v[2] < 0.0): numpy.negative(v, v) v /= n return v if (a[2] == 1.0): return numpy.array([1.0, 0.0, 0.0]) return unit_vector([(- a[1]), a[0], 0.0])
[ "def", "arcball_constrain_to_axis", "(", "point", ",", "axis", ")", ":", "v", "=", "numpy", ".", "array", "(", "point", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "True", ")", "a", "=", "numpy", ".", "array", "(", "axis", ",", "d...
return sphere point perpendicular to axis .
train
true