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
29,860
def test_source_files_specify_encoding(): pattern = re.compile(u'#.*?coding[:=][ \\t]*utf-?8') decode_errors = [] no_specification = [] for (abs_path, rel_path) in walk_python_files(): try: with io.open(abs_path, encoding=u'utf-8') as f: for line in f: line = line.strip() if pattern.match(line): break elif (line and (not line.startswith(u'#'))): no_specification.append(rel_path) break except UnicodeDecodeError: decode_errors.append(rel_path) msgs = [] if no_specification: msgs.append(u'The following files are missing an encoding specification: {}'.format(no_specification)) if decode_errors: msgs.append(u'The following files are not valid UTF-8: {}'.format(decode_errors)) if msgs: assert False, u'\n\n'.join(msgs)
[ "def", "test_source_files_specify_encoding", "(", ")", ":", "pattern", "=", "re", ".", "compile", "(", "u'#.*?coding[:=][ \\\\t]*utf-?8'", ")", "decode_errors", "=", "[", "]", "no_specification", "=", "[", "]", "for", "(", "abs_path", ",", "rel_path", ")", "in",...
test that * .
train
false
29,861
def _restore_logging(log_name='flocker.test'): def decorator(function): @wraps(function) def wrapper(self): def restore_logger(logger, level, handlers): logger.setLevel(level) for handler in logger.handlers[:]: logger.removeHandler(handler) for handler in handlers: logger.addHandler(handler) logger = logging.getLogger(log_name) self.addCleanup(restore_logger, logger, logger.getEffectiveLevel(), logger.handlers[:]) return function(self, log_name) return wrapper return decorator
[ "def", "_restore_logging", "(", "log_name", "=", "'flocker.test'", ")", ":", "def", "decorator", "(", "function", ")", ":", "@", "wraps", "(", "function", ")", "def", "wrapper", "(", "self", ")", ":", "def", "restore_logger", "(", "logger", ",", "level", ...
save and restore a logging configuration .
train
false
29,863
def _get_account_policy_data_value(name, key): cmd = 'dscl . -readpl /Users/{0} accountPolicyData {1}'.format(name, key) try: ret = salt.utils.mac_utils.execute_return_result(cmd) except CommandExecutionError as exc: if ('eDSUnknownNodeName' in exc.strerror): raise CommandExecutionError('User not found: {0}'.format(name)) raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror)) return ret
[ "def", "_get_account_policy_data_value", "(", "name", ",", "key", ")", ":", "cmd", "=", "'dscl . -readpl /Users/{0} accountPolicyData {1}'", ".", "format", "(", "name", ",", "key", ")", "try", ":", "ret", "=", "salt", ".", "utils", ".", "mac_utils", ".", "exec...
return the value for a key in the accountpolicy section of the users plist file .
train
true
29,868
def createAES(key, IV, implList=None): if (implList == None): implList = ['cryptlib', 'openssl', 'pycrypto', 'python'] for impl in implList: if ((impl == 'cryptlib') and cryptomath.cryptlibpyLoaded): return Cryptlib_AES.new(key, 2, IV) elif ((impl == 'openssl') and cryptomath.m2cryptoLoaded): return OpenSSL_AES.new(key, 2, IV) elif ((impl == 'pycrypto') and cryptomath.pycryptoLoaded): return PyCrypto_AES.new(key, 2, IV) elif (impl == 'python'): return Python_AES.new(key, 2, IV) raise NotImplementedError()
[ "def", "createAES", "(", "key", ",", "IV", ",", "implList", "=", "None", ")", ":", "if", "(", "implList", "==", "None", ")", ":", "implList", "=", "[", "'cryptlib'", ",", "'openssl'", ",", "'pycrypto'", ",", "'python'", "]", "for", "impl", "in", "imp...
create a new aes object .
train
false
29,870
def is_option(value, *options): if (not isinstance(value, string_type)): raise VdtTypeError(value) if (not (value in options)): raise VdtValueError(value) return value
[ "def", "is_option", "(", "value", ",", "*", "options", ")", ":", "if", "(", "not", "isinstance", "(", "value", ",", "string_type", ")", ")", ":", "raise", "VdtTypeError", "(", "value", ")", "if", "(", "not", "(", "value", "in", "options", ")", ")", ...
this check matches the value to any of a set of options .
train
false
29,871
def test_make_png(): rgba_save = np.random.randint(256, size=(100, 100, 4)).astype(np.ubyte) rgb_save = rgba_save[:, :, :3] png_out = op.join(temp_dir, 'random.png') for rgb_a in (rgba_save, rgb_save): write_png(png_out, rgb_a) rgb_a_read = read_png(png_out) assert_array_equal(rgb_a, rgb_a_read)
[ "def", "test_make_png", "(", ")", ":", "rgba_save", "=", "np", ".", "random", ".", "randint", "(", "256", ",", "size", "=", "(", "100", ",", "100", ",", "4", ")", ")", ".", "astype", "(", "np", ".", "ubyte", ")", "rgb_save", "=", "rgba_save", "["...
test to ensure that make_png functions correctly .
train
false
29,872
@login_required def unfollow(request, username, template_name='relationships/relationship_delete_confirm.html', success_template_name='relationships/relationship_delete_success.html', content_type='text/html'): to_user = get_object_or_404(User, username=username) from_user = request.user next = request.GET.get('next', None) if (request.method == 'POST'): relationship = get_object_or_404(Relationship, to_user=to_user, from_user=from_user) relationship.delete() if request.is_ajax(): response = {'success': 'Success', 'to_user': {'username': to_user.username, 'user_id': to_user.pk}, 'from_user': {'username': from_user.username, 'user_id': from_user.pk}} return HttpResponse(json.dumps(response), content_type='application/json') if next: return HttpResponseRedirect(next) template_name = success_template_name context = {'to_user': to_user, 'next': next} return render_to_response(template_name, context, context_instance=RequestContext(request), content_type=content_type)
[ "@", "login_required", "def", "unfollow", "(", "request", ",", "username", ",", "template_name", "=", "'relationships/relationship_delete_confirm.html'", ",", "success_template_name", "=", "'relationships/relationship_delete_success.html'", ",", "content_type", "=", "'text/html...
removes a "follow" relationship .
train
false
29,876
def handle_recreate_index(request): groups = [name.replace('check_', '') for name in request.POST.keys() if name.startswith('check_')] indexes = [write_index(group) for group in groups] recreate_indexes(indexes=indexes) mapping_types_names = [mt.get_mapping_type_name() for mt in get_mapping_types() if (mt.get_index_group() in groups)] reindex(mapping_types_names) return HttpResponseRedirect(request.path)
[ "def", "handle_recreate_index", "(", "request", ")", ":", "groups", "=", "[", "name", ".", "replace", "(", "'check_'", ",", "''", ")", "for", "name", "in", "request", ".", "POST", ".", "keys", "(", ")", "if", "name", ".", "startswith", "(", "'check_'",...
deletes an index .
train
false
29,877
def _reverse_intervals(intervals): return [((b, a), indices, f) for ((a, b), indices, f) in reversed(intervals)]
[ "def", "_reverse_intervals", "(", "intervals", ")", ":", "return", "[", "(", "(", "b", ",", "a", ")", ",", "indices", ",", "f", ")", "for", "(", "(", "a", ",", "b", ")", ",", "indices", ",", "f", ")", "in", "reversed", "(", "intervals", ")", "]...
reverse intervals for traversal from right to left and from top to bottom .
train
false
29,878
def get_app_label(app): return app.__name__.split('.')[(-2)]
[ "def", "get_app_label", "(", "app", ")", ":", "return", "app", ".", "__name__", ".", "split", "(", "'.'", ")", "[", "(", "-", "2", ")", "]" ]
returns the _internal_ app label for the given app module .
train
false
29,879
@pytest.fixture(scope='module') def vm_tests_fixtures(): filenames = os.listdir(os.path.join(testutils.fixture_path, 'VMTests')) files = [os.path.join(testutils.fixture_path, 'VMTests', f) for f in filenames] vm_fixtures = {} try: for (f, fn) in zip(files, filenames): if (f[(-5):] == '.json'): vm_fixtures[fn[:(-5)]] = json.load(open(f, 'r')) except IOError as e: raise IOError('Could not read vmtests.json from fixtures', "Make sure you did 'git submodule init'") return vm_fixtures
[ "@", "pytest", ".", "fixture", "(", "scope", "=", "'module'", ")", "def", "vm_tests_fixtures", "(", ")", ":", "filenames", "=", "os", ".", "listdir", "(", "os", ".", "path", ".", "join", "(", "testutils", ".", "fixture_path", ",", "'VMTests'", ")", ")"...
read vm tests from fixtures fixtures/vmtests/* .
train
false
29,880
def axes_ticklabels_overlap(ax): return (axis_ticklabels_overlap(ax.get_xticklabels()), axis_ticklabels_overlap(ax.get_yticklabels()))
[ "def", "axes_ticklabels_overlap", "(", "ax", ")", ":", "return", "(", "axis_ticklabels_overlap", "(", "ax", ".", "get_xticklabels", "(", ")", ")", ",", "axis_ticklabels_overlap", "(", "ax", ".", "get_yticklabels", "(", ")", ")", ")" ]
return booleans for whether the x and y ticklabels on an axes overlap .
train
false
29,883
@not_implemented_for('undirected') @not_implemented_for('multigraph') def directed_modularity_matrix(G, nodelist=None, weight=None): if (nodelist is None): nodelist = list(G) A = nx.to_scipy_sparse_matrix(G, nodelist=nodelist, weight=weight, format='csr') k_in = A.sum(axis=0) k_out = A.sum(axis=1) m = k_in.sum() X = ((k_out * k_in) / m) return (A - X)
[ "@", "not_implemented_for", "(", "'undirected'", ")", "@", "not_implemented_for", "(", "'multigraph'", ")", "def", "directed_modularity_matrix", "(", "G", ",", "nodelist", "=", "None", ",", "weight", "=", "None", ")", ":", "if", "(", "nodelist", "is", "None", ...
return the directed modularity matrix of g .
train
false
29,884
def test_scenario_outline3_fr_from_string(): lang = Language('fr') scenario = Scenario.from_string(OUTLINED_SCENARIO2, language=lang) assert_equals(scenario.name, 'Ajouter 2 nombres') assert_equals(scenario.outlines, [{u'input_1': u'20', u'input_2': u'30', u'bouton': u'add', u'output': u'50'}, {u'input_1': u'2', u'input_2': u'5', u'bouton': u'add', u'output': u'7'}, {u'input_1': u'0', u'input_2': u'40', u'bouton': u'add', u'output': u'40'}])
[ "def", "test_scenario_outline3_fr_from_string", "(", ")", ":", "lang", "=", "Language", "(", "'fr'", ")", "scenario", "=", "Scenario", ".", "from_string", "(", "OUTLINED_SCENARIO2", ",", "language", "=", "lang", ")", "assert_equals", "(", "scenario", ".", "name"...
language: fr -> scenario .
train
false
29,886
def trim1(a, proportiontocut, tail='right', axis=0): a = np.asarray(a) if (axis is None): a = a.ravel() axis = 0 nobs = a.shape[axis] if (proportiontocut >= 1): return [] if (tail.lower() == 'right'): lowercut = 0 uppercut = (nobs - int((proportiontocut * nobs))) elif (tail.lower() == 'left'): lowercut = int((proportiontocut * nobs)) uppercut = nobs atmp = np.partition(a, (lowercut, (uppercut - 1)), axis) return atmp[lowercut:uppercut]
[ "def", "trim1", "(", "a", ",", "proportiontocut", ",", "tail", "=", "'right'", ",", "axis", "=", "0", ")", ":", "a", "=", "np", ".", "asarray", "(", "a", ")", "if", "(", "axis", "is", "None", ")", ":", "a", "=", "a", ".", "ravel", "(", ")", ...
slices off a proportion from one end of the passed array distribution .
train
false
29,887
def vectors_in_basis(expr, to_sys): vectors = list(expr.atoms(BaseVectorField)) new_vectors = [] for v in vectors: cs = v._coord_sys jac = cs.jacobian(to_sys, cs.coord_functions()) new = (jac.T * Matrix(to_sys.base_vectors()))[v._index] new_vectors.append(new) return expr.subs(list(zip(vectors, new_vectors)))
[ "def", "vectors_in_basis", "(", "expr", ",", "to_sys", ")", ":", "vectors", "=", "list", "(", "expr", ".", "atoms", "(", "BaseVectorField", ")", ")", "new_vectors", "=", "[", "]", "for", "v", "in", "vectors", ":", "cs", "=", "v", ".", "_coord_sys", "...
transform all base vectors in base vectors of a specified coord basis .
train
false
29,889
def processArchiveRemoveSolid(elementNode, geometryOutput): solidMatchingPlugins = getSolidMatchingPlugins(elementNode) if (len(solidMatchingPlugins) == 0): elementNode.parentNode.xmlObject.archivableObjects.append(elementNode.xmlObject) matrix.getBranchMatrixSetElementNode(elementNode) return processElementNodeByGeometry(elementNode, getGeometryOutputByManipulation(elementNode, geometryOutput))
[ "def", "processArchiveRemoveSolid", "(", "elementNode", ",", "geometryOutput", ")", ":", "solidMatchingPlugins", "=", "getSolidMatchingPlugins", "(", "elementNode", ")", "if", "(", "len", "(", "solidMatchingPlugins", ")", "==", "0", ")", ":", "elementNode", ".", "...
process the target by the manipulationfunction .
train
false
29,890
@lazyobject def STDHANDLES(): hs = [lazyimps._winapi.STD_INPUT_HANDLE, lazyimps._winapi.STD_OUTPUT_HANDLE, lazyimps._winapi.STD_ERROR_HANDLE] hcons = [] for h in hs: hcon = GetStdHandle(int(h)) hcons.append(hcon) return tuple(hcons)
[ "@", "lazyobject", "def", "STDHANDLES", "(", ")", ":", "hs", "=", "[", "lazyimps", ".", "_winapi", ".", "STD_INPUT_HANDLE", ",", "lazyimps", ".", "_winapi", ".", "STD_OUTPUT_HANDLE", ",", "lazyimps", ".", "_winapi", ".", "STD_ERROR_HANDLE", "]", "hcons", "="...
tuple of the windows handles for .
train
false
29,891
def msg_register(self, msgType, isFriendChat=False, isGroupChat=False, isMpChat=False): if (not isinstance(msgType, list)): msgType = [msgType] def _msg_register(fn): for _msgType in msgType: if isFriendChat: self.functionDict['FriendChat'][_msgType] = fn if isGroupChat: self.functionDict['GroupChat'][_msgType] = fn if isMpChat: self.functionDict['MpChat'][_msgType] = fn if (not any((isFriendChat, isGroupChat, isMpChat))): self.functionDict['FriendChat'][_msgType] = fn return _msg_register
[ "def", "msg_register", "(", "self", ",", "msgType", ",", "isFriendChat", "=", "False", ",", "isGroupChat", "=", "False", ",", "isMpChat", "=", "False", ")", ":", "if", "(", "not", "isinstance", "(", "msgType", ",", "list", ")", ")", ":", "msgType", "="...
a decorator constructor return a specific decorator based on information given .
train
false
29,892
def mime_decode(line): newline = '' pos = 0 while 1: res = mime_code.search(line, pos) if (res is None): break newline = ((newline + line[pos:res.start(0)]) + chr(int(res.group(1), 16))) pos = res.end(0) return (newline + line[pos:])
[ "def", "mime_decode", "(", "line", ")", ":", "newline", "=", "''", "pos", "=", "0", "while", "1", ":", "res", "=", "mime_code", ".", "search", "(", "line", ",", "pos", ")", "if", "(", "res", "is", "None", ")", ":", "break", "newline", "=", "(", ...
decode a single line of quoted-printable text to 8bit .
train
false
29,893
def get_opening_type(zone): if ('MOTION' in zone['name']): return 'motion' if ('KEY' in zone['name']): return 'safety' if ('SMOKE' in zone['name']): return 'smoke' if ('WATER' in zone['name']): return 'water' return 'opening'
[ "def", "get_opening_type", "(", "zone", ")", ":", "if", "(", "'MOTION'", "in", "zone", "[", "'name'", "]", ")", ":", "return", "'motion'", "if", "(", "'KEY'", "in", "zone", "[", "'name'", "]", ")", ":", "return", "'safety'", "if", "(", "'SMOKE'", "in...
helper function to try to guess sensor type from name .
train
false
29,894
def framework(): return s3_rest_controller(dtargs={'dt_text_maximum_len': 160}, hide_filter=True)
[ "def", "framework", "(", ")", ":", "return", "s3_rest_controller", "(", "dtargs", "=", "{", "'dt_text_maximum_len'", ":", "160", "}", ",", "hide_filter", "=", "True", ")" ]
restful crud controller .
train
false
29,895
def get_template_path(relative_path, **kwargs): if ((not current_request_has_associated_site_theme()) and microsite.is_request_in_microsite()): relative_path = microsite.get_template_path(relative_path, **kwargs) return relative_path
[ "def", "get_template_path", "(", "relative_path", ",", "**", "kwargs", ")", ":", "if", "(", "(", "not", "current_request_has_associated_site_theme", "(", ")", ")", "and", "microsite", ".", "is_request_in_microsite", "(", ")", ")", ":", "relative_path", "=", "mic...
this is a proxy function to hide microsite_configuration behind comprehensive theming .
train
false
29,897
@click.command('src') def bench_src(): import bench print os.path.dirname(bench.__path__[0])
[ "@", "click", ".", "command", "(", "'src'", ")", "def", "bench_src", "(", ")", ":", "import", "bench", "print", "os", ".", "path", ".", "dirname", "(", "bench", ".", "__path__", "[", "0", "]", ")" ]
prints bench source folder path .
train
false
29,898
def _max_cardinality_node(G, choices, wanna_connect): max_number = (-1) for x in choices: number = len([y for y in G[x] if (y in wanna_connect)]) if (number > max_number): max_number = number max_cardinality_node = x return max_cardinality_node
[ "def", "_max_cardinality_node", "(", "G", ",", "choices", ",", "wanna_connect", ")", ":", "max_number", "=", "(", "-", "1", ")", "for", "x", "in", "choices", ":", "number", "=", "len", "(", "[", "y", "for", "y", "in", "G", "[", "x", "]", "if", "(...
returns a the node in choices that has more connections in g to nodes in wanna_connect .
train
false
29,899
def LogBinomialCoef(n, k): return (((n * math.log(n)) - (k * math.log(k))) - ((n - k) * math.log((n - k))))
[ "def", "LogBinomialCoef", "(", "n", ",", "k", ")", ":", "return", "(", "(", "(", "n", "*", "math", ".", "log", "(", "n", ")", ")", "-", "(", "k", "*", "math", ".", "log", "(", "k", ")", ")", ")", "-", "(", "(", "n", "-", "k", ")", "*", ...
computes the log of the binomial coefficient .
train
true
29,900
def getPluginFileNames(): return archive.getPluginFileNamesFromDirectoryPath(archive.getSkeinforgePluginsPath())
[ "def", "getPluginFileNames", "(", ")", ":", "return", "archive", ".", "getPluginFileNamesFromDirectoryPath", "(", "archive", ".", "getSkeinforgePluginsPath", "(", ")", ")" ]
get analyze plugin filenames .
train
false
29,903
def provider_id(): return _counter.count()
[ "def", "provider_id", "(", ")", ":", "return", "_counter", ".", "count", "(", ")" ]
a simple counter to be used in the config to generate unique ids .
train
false
29,904
def this_month(t): now = time.localtime(t) ntime = (now[0], now[1], 1, 0, 0, 0, 0, 0, now[8]) return time.mktime(ntime)
[ "def", "this_month", "(", "t", ")", ":", "now", "=", "time", ".", "localtime", "(", "t", ")", "ntime", "=", "(", "now", "[", "0", "]", ",", "now", "[", "1", "]", ",", "1", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "now", "[...
return timestamp for start of next month .
train
false
29,905
def _set_autocommit(connection): if hasattr(connection.connection, 'autocommit'): connection.connection.autocommit(True) elif hasattr(connection.connection, 'set_isolation_level'): connection.connection.set_isolation_level(0)
[ "def", "_set_autocommit", "(", "connection", ")", ":", "if", "hasattr", "(", "connection", ".", "connection", ",", "'autocommit'", ")", ":", "connection", ".", "connection", ".", "autocommit", "(", "True", ")", "elif", "hasattr", "(", "connection", ".", "con...
make sure a connection is in autocommit mode .
train
false
29,908
def editor_command(): editor = os.environ.get('EDITOR') if editor: return editor return open_anything()
[ "def", "editor_command", "(", ")", ":", "editor", "=", "os", ".", "environ", ".", "get", "(", "'EDITOR'", ")", "if", "editor", ":", "return", "editor", "return", "open_anything", "(", ")" ]
get a command for opening a text file .
train
false
29,909
def test_destop(): from vispy.gloo.gl import gl2 _test_function_names(gl2) _test_constant_names(gl2)
[ "def", "test_destop", "(", ")", ":", "from", "vispy", ".", "gloo", ".", "gl", "import", "gl2", "_test_function_names", "(", "gl2", ")", "_test_constant_names", "(", "gl2", ")" ]
desktop backend should have all es 2 .
train
false
29,910
def get_columns_dict(columns): columns_dict = {} for (idx, col) in enumerate(columns): col_dict = {} if isinstance(col, basestring): col = col.split(u':') if (len(col) > 1): if (u'/' in col[1]): (col_dict[u'fieldtype'], col_dict[u'options']) = col[1].split(u'/') else: col_dict[u'fieldtype'] = col[1] col_dict[u'fieldname'] = frappe.scrub(col[0]) else: col_dict.update(col) if (u'fieldname' not in col_dict): col_dict[u'fieldname'] = frappe.scrub(col_dict[u'label']) columns_dict[idx] = col_dict columns_dict[col_dict[u'fieldname']] = col_dict return columns_dict
[ "def", "get_columns_dict", "(", "columns", ")", ":", "columns_dict", "=", "{", "}", "for", "(", "idx", ",", "col", ")", "in", "enumerate", "(", "columns", ")", ":", "col_dict", "=", "{", "}", "if", "isinstance", "(", "col", ",", "basestring", ")", ":...
returns a dict with column docfield values as dict the keys for the dict are both idx and fieldname .
train
false
29,911
def hello4(): response.view = 'simple_examples/hello3.html' return dict(message=T('Hello World'))
[ "def", "hello4", "(", ")", ":", "response", ".", "view", "=", "'simple_examples/hello3.html'", "return", "dict", "(", "message", "=", "T", "(", "'Hello World'", ")", ")" ]
page rendered by template simple_examples/index3 .
train
false
29,912
def getJumpPointIfInside(boundary, otherPoint, perimeterWidth, runningJumpSpace): insetBoundary = intercircle.getSimplifiedInsetFromClockwiseLoop(boundary, (- perimeterWidth)) closestJumpDistanceIndex = euclidean.getClosestDistanceIndexToLine(otherPoint, insetBoundary) jumpIndex = ((closestJumpDistanceIndex.index + 1) % len(insetBoundary)) jumpPoint = euclidean.getClosestPointOnSegment(insetBoundary[closestJumpDistanceIndex.index], insetBoundary[jumpIndex], otherPoint) jumpPoint = getJumpPoint(jumpPoint, otherPoint, boundary, runningJumpSpace) if euclidean.isPointInsideLoop(boundary, jumpPoint): return jumpPoint return None
[ "def", "getJumpPointIfInside", "(", "boundary", ",", "otherPoint", ",", "perimeterWidth", ",", "runningJumpSpace", ")", ":", "insetBoundary", "=", "intercircle", ".", "getSimplifiedInsetFromClockwiseLoop", "(", "boundary", ",", "(", "-", "perimeterWidth", ")", ")", ...
get the jump point if it is inside the boundary .
train
false
29,913
@deprecated('load_bars_from_yahoo is deprecated, please register a yahoo_equities data bundle instead') def load_bars_from_yahoo(indexes=None, stocks=None, start=None, end=None, adjusted=True): data = _load_raw_yahoo_data(indexes, stocks, start, end) panel = pd.Panel(data) panel.minor_axis = ['open', 'high', 'low', 'close', 'volume', 'price'] panel.major_axis = panel.major_axis.tz_localize(pytz.utc) if adjusted: adj_cols = ['open', 'high', 'low', 'close'] for ticker in panel.items: ratio = (panel[ticker]['price'] / panel[ticker]['close']) ratio_filtered = ratio.fillna(0).values for col in adj_cols: panel[ticker][col] *= ratio_filtered return panel
[ "@", "deprecated", "(", "'load_bars_from_yahoo is deprecated, please register a yahoo_equities data bundle instead'", ")", "def", "load_bars_from_yahoo", "(", "indexes", "=", "None", ",", "stocks", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", ...
loads data from yahoo into a panel with the following column names for each indicated security: - open - high - low - close - volume - price note that price is yahoos adjusted close .
train
false
29,914
def _valid_iface(iface): ifaces = list_interfaces() if (iface in ifaces.keys()): return True return False
[ "def", "_valid_iface", "(", "iface", ")", ":", "ifaces", "=", "list_interfaces", "(", ")", "if", "(", "iface", "in", "ifaces", ".", "keys", "(", ")", ")", ":", "return", "True", "return", "False" ]
validate the specified interface .
train
false
29,917
def del_pid(pidfile): if os.path.exists(pidfile): os.remove(pidfile)
[ "def", "del_pid", "(", "pidfile", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "pidfile", ")", ":", "os", ".", "remove", "(", "pidfile", ")" ]
the pidfile should normally be removed after a process has finished .
train
false
29,918
def red_groebner(G, ring): def reduction(P): '\n The actual reduction algorithm.\n ' Q = [] for (i, p) in enumerate(P): h = p.rem((P[:i] + P[(i + 1):])) if h: Q.append(h) return [p.monic() for p in Q] F = G H = [] while F: f0 = F.pop() if (not any((monomial_divides(f.LM, f0.LM) for f in (F + H)))): H.append(f0) return reduction(H)
[ "def", "red_groebner", "(", "G", ",", "ring", ")", ":", "def", "reduction", "(", "P", ")", ":", "Q", "=", "[", "]", "for", "(", "i", ",", "p", ")", "in", "enumerate", "(", "P", ")", ":", "h", "=", "p", ".", "rem", "(", "(", "P", "[", ":",...
compute reduced groebner basis .
train
false
29,919
def custom_headers(): headers = {} dnt = ('1' if config.get('network', 'do-not-track') else '0') headers['DNT'] = dnt headers['X-Do-Not-Track'] = dnt config_headers = config.get('network', 'custom-headers') if (config_headers is not None): for (header, value) in config_headers.items(): headers[header.encode('ascii')] = value.encode('ascii') accept_language = config.get('network', 'accept-language') if (accept_language is not None): headers['Accept-Language'] = accept_language.encode('ascii') return sorted(headers.items())
[ "def", "custom_headers", "(", ")", ":", "headers", "=", "{", "}", "dnt", "=", "(", "'1'", "if", "config", ".", "get", "(", "'network'", ",", "'do-not-track'", ")", "else", "'0'", ")", "headers", "[", "'DNT'", "]", "=", "dnt", "headers", "[", "'X-Do-N...
set some custom headers across all http responses .
train
false
29,920
def paramiko_tunnel(lport, rport, server, remoteip='127.0.0.1', keyfile=None, password=None, timeout=60): if (paramiko is None): raise ImportError('Paramiko not available') if (password is None): if (not _try_passwordless_paramiko(server, keyfile)): password = getpass(("%s's password: " % server)) p = Process(target=_paramiko_tunnel, args=(lport, rport, server, remoteip), kwargs=dict(keyfile=keyfile, password=password)) p.daemon = True p.start() return p
[ "def", "paramiko_tunnel", "(", "lport", ",", "rport", ",", "server", ",", "remoteip", "=", "'127.0.0.1'", ",", "keyfile", "=", "None", ",", "password", "=", "None", ",", "timeout", "=", "60", ")", ":", "if", "(", "paramiko", "is", "None", ")", ":", "...
launch a tunner with paramiko in a subprocess .
train
true
29,922
def get_data_names(series_or_dataframe): names = getattr(series_or_dataframe, 'name', None) if (not names): names = getattr(series_or_dataframe, 'columns', None) if (not names): shape = getattr(series_or_dataframe, 'shape', [1]) nvars = (1 if (len(shape) == 1) else series.shape[1]) names = ['X%d' for names in range(nvars)] if (nvars == 1): names = names[0] else: names = names.tolist() return names
[ "def", "get_data_names", "(", "series_or_dataframe", ")", ":", "names", "=", "getattr", "(", "series_or_dataframe", ",", "'name'", ",", "None", ")", "if", "(", "not", "names", ")", ":", "names", "=", "getattr", "(", "series_or_dataframe", ",", "'columns'", "...
input can be an array or pandas-like .
train
false
29,925
def _ExecuteRequest(request): service = request.service_name() method = request.method() service_methods = remote_api_services.SERVICE_PB_MAP.get(service, {}) (request_class, response_class) = service_methods.get(method, (None, None)) if (not request_class): raise apiproxy_errors.CallNotFoundError(('%s.%s does not exist' % (service, method))) request_data = request_class() request_data.ParseFromString(request.request()) response_data = response_class() def MakeRequest(): apiproxy_stub_map.MakeSyncCall(service, method, request_data, response_data) if (service in THREAD_SAFE_SERVICES): MakeRequest() else: with GLOBAL_API_LOCK: MakeRequest() return response_data
[ "def", "_ExecuteRequest", "(", "request", ")", ":", "service", "=", "request", ".", "service_name", "(", ")", "method", "=", "request", ".", "method", "(", ")", "service_methods", "=", "remote_api_services", ".", "SERVICE_PB_MAP", ".", "get", "(", "service", ...
executes an api method call and returns the response object .
train
false
29,926
def cosh(x): np = import_module('numpy') if isinstance(x, (int, float)): return interval(np.cosh(x), np.cosh(x)) elif isinstance(x, interval): if ((x.start < 0) and (x.end > 0)): end = max(np.cosh(x.start), np.cosh(x.end)) return interval(1, end, is_valid=x.is_valid) else: start = np.cosh(x.start) end = np.cosh(x.end) return interval(start, end, is_valid=x.is_valid) else: raise NotImplementedError
[ "def", "cosh", "(", "x", ")", ":", "np", "=", "import_module", "(", "'numpy'", ")", "if", "isinstance", "(", "x", ",", "(", "int", ",", "float", ")", ")", ":", "return", "interval", "(", "np", ".", "cosh", "(", "x", ")", ",", "np", ".", "cosh",...
elementwise hyperbolic cosine function .
train
false
29,927
def held(name): ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} state = __salt__['pkg.get_selections'](pattern=name) if (not state): ret.update(comment='Package {0} does not have a state'.format(name)) elif (not salt.utils.is_true(state.get('hold', False))): if (not __opts__['test']): result = __salt__['pkg.set_selections'](selection={'hold': [name]}) ret.update(changes=result[name], result=True, comment='Package {0} is now being held'.format(name)) else: ret.update(result=None, comment='Package {0} is set to be held'.format(name)) else: ret.update(result=True, comment='Package {0} is already held'.format(name)) return ret
[ "def", "held", "(", "name", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", "}", "state", "=", "__salt__", "[", "'pkg.get_selections'", "]", "(", "pattern"...
set package in hold state .
train
true
29,928
def _markers(pem_marker): if is_bytes(pem_marker): pem_marker = pem_marker.decode('utf-8') return (b(('-----BEGIN %s-----' % pem_marker)), b(('-----END %s-----' % pem_marker)))
[ "def", "_markers", "(", "pem_marker", ")", ":", "if", "is_bytes", "(", "pem_marker", ")", ":", "pem_marker", "=", "pem_marker", ".", "decode", "(", "'utf-8'", ")", "return", "(", "b", "(", "(", "'-----BEGIN %s-----'", "%", "pem_marker", ")", ")", ",", "b...
returns the start and end pem markers .
train
false
29,929
def _to_json(unencoded): return jsonutils.dumps(list(unencoded))
[ "def", "_to_json", "(", "unencoded", ")", ":", "return", "jsonutils", ".", "dumps", "(", "list", "(", "unencoded", ")", ")" ]
convert attribute values into json representation .
train
false
29,930
def test_sort_locations_file_expand_dir(data): finder = PackageFinder([data.find_links], [], session=PipSession()) (files, urls) = finder._sort_locations([data.find_links], expand_dir=True) assert (files and (not urls)), ('files and not urls should have been found at find-links url: %s' % data.find_links)
[ "def", "test_sort_locations_file_expand_dir", "(", "data", ")", ":", "finder", "=", "PackageFinder", "(", "[", "data", ".", "find_links", "]", ",", "[", "]", ",", "session", "=", "PipSession", "(", ")", ")", "(", "files", ",", "urls", ")", "=", "finder",...
test that a file:// dir gets listdir run with expand_dir .
train
false
29,931
def norm_angle(a): a = ((a + 360) % 360) if (a > 180): a = (a - 360) return a
[ "def", "norm_angle", "(", "a", ")", ":", "a", "=", "(", "(", "a", "+", "360", ")", "%", "360", ")", "if", "(", "a", ">", "180", ")", ":", "a", "=", "(", "a", "-", "360", ")", "return", "a" ]
return angle between -180 and +180 .
train
false
29,933
def update_course_enrollment(username, course_id, mode=None, is_active=None): course_key = CourseKey.from_string(course_id) try: user = User.objects.get(username=username) except User.DoesNotExist: msg = u"Not user with username '{username}' found.".format(username=username) log.warn(msg) raise UserNotFoundError(msg) try: enrollment = CourseEnrollment.objects.get(user=user, course_id=course_key) return _update_enrollment(enrollment, is_active=is_active, mode=mode) except CourseEnrollment.DoesNotExist: return None
[ "def", "update_course_enrollment", "(", "username", ",", "course_id", ",", "mode", "=", "None", ",", "is_active", "=", "None", ")", ":", "course_key", "=", "CourseKey", ".", "from_string", "(", "course_id", ")", "try", ":", "user", "=", "User", ".", "objec...
modify a course enrollment for a user .
train
false
29,934
def _plot_unit_points(ax, x, data, color, err_kws, **kwargs): if isinstance(color, list): for (i, obs) in enumerate(data): ax.plot(x, obs, 'o', color=color[i], alpha=0.8, markersize=4, label='_nolegend_', **err_kws) else: ax.plot(x, data.T, 'o', color=color, alpha=0.5, markersize=4, label='_nolegend_', **err_kws)
[ "def", "_plot_unit_points", "(", "ax", ",", "x", ",", "data", ",", "color", ",", "err_kws", ",", "**", "kwargs", ")", ":", "if", "isinstance", "(", "color", ",", "list", ")", ":", "for", "(", "i", ",", "obs", ")", "in", "enumerate", "(", "data", ...
plot each original data point discretely .
train
false
29,935
def get_backends(force_load=False): global BACKENDSCACHE if ((not BACKENDSCACHE) or force_load): with _import_lock: for auth_backend in setting('SOCIAL_AUTH_AUTHENTICATION_BACKENDS'): (mod, cls_name) = auth_backend.rsplit('.', 1) module = __import__(mod, {}, {}, ['BACKENDS', cls_name]) backend = getattr(module, cls_name) if issubclass(backend, SocialAuthBackend): name = backend.name backends = getattr(module, 'BACKENDS', {}) if ((name in backends) and backends[name].enabled()): BACKENDSCACHE[name] = backends[name] return BACKENDSCACHE
[ "def", "get_backends", "(", "force_load", "=", "False", ")", ":", "global", "BACKENDSCACHE", "if", "(", "(", "not", "BACKENDSCACHE", ")", "or", "force_load", ")", ":", "with", "_import_lock", ":", "for", "auth_backend", "in", "setting", "(", "'SOCIAL_AUTH_AUTH...
entry point to the backends cache .
train
false
29,936
def fix_default_encoding(): if (sys.getdefaultencoding() == 'utf-8'): return False sys_modules = sys.modules our_sys = sys_modules.pop('sys') try: vanilla_sys = __import__('sys') vanilla_sys.setdefaultencoding('utf-8') assert (sys.getdefaultencoding() == 'utf-8') finally: sys_modules['sys'] = our_sys for attr in dir(locale): if (attr[0:3] != 'LC_'): continue aref = getattr(locale, attr) try: locale.setlocale(aref, '') except locale.Error: continue try: lang = locale.getlocale(aref)[0] except (TypeError, ValueError): continue if lang: try: locale.setlocale(aref, (lang, 'UTF-8')) except locale.Error: os.environ[attr] = (lang + '.UTF-8') try: locale.setlocale(locale.LC_ALL, '') except locale.Error: pass return True
[ "def", "fix_default_encoding", "(", ")", ":", "if", "(", "sys", ".", "getdefaultencoding", "(", ")", "==", "'utf-8'", ")", ":", "return", "False", "sys_modules", "=", "sys", ".", "modules", "our_sys", "=", "sys_modules", ".", "pop", "(", "'sys'", ")", "t...
forces utf8 solidly on all platforms .
train
false
29,937
def write_cores(core_data, dir_list): syslog.syslog(('Writing core files to %s' % dir_list)) for result_dir in dir_list: if (not os.path.isdir(result_dir)): os.makedirs(result_dir) core_path = os.path.join(result_dir, 'core') core_path = write_to_file(core_path, core_file, report=True)
[ "def", "write_cores", "(", "core_data", ",", "dir_list", ")", ":", "syslog", ".", "syslog", "(", "(", "'Writing core files to %s'", "%", "dir_list", ")", ")", "for", "result_dir", "in", "dir_list", ":", "if", "(", "not", "os", ".", "path", ".", "isdir", ...
write core files to all directories .
train
false
29,938
@verbose def tfr_multitaper(inst, freqs, n_cycles, time_bandwidth=4.0, use_fft=True, return_itc=True, decim=1, n_jobs=1, picks=None, average=True, verbose=None): tfr_params = dict(n_cycles=n_cycles, n_jobs=n_jobs, use_fft=use_fft, zero_mean=True, time_bandwidth=time_bandwidth) return _tfr_aux('multitaper', inst, freqs, decim, return_itc, picks, average, **tfr_params)
[ "@", "verbose", "def", "tfr_multitaper", "(", "inst", ",", "freqs", ",", "n_cycles", ",", "time_bandwidth", "=", "4.0", ",", "use_fft", "=", "True", ",", "return_itc", "=", "True", ",", "decim", "=", "1", ",", "n_jobs", "=", "1", ",", "picks", "=", "...
compute time-frequency representation using dpss tapers .
train
false
29,939
def test_organize_commands(): commands = [CorrectedCommand('ls'), CorrectedCommand('ls -la', priority=9000), CorrectedCommand('ls -lh', priority=100), CorrectedCommand(u'echo caf\xe9', priority=200), CorrectedCommand('ls -lh', priority=9999)] assert (list(organize_commands(iter(commands))) == [CorrectedCommand('ls'), CorrectedCommand('ls -lh', priority=100), CorrectedCommand(u'echo caf\xe9', priority=200), CorrectedCommand('ls -la', priority=9000)])
[ "def", "test_organize_commands", "(", ")", ":", "commands", "=", "[", "CorrectedCommand", "(", "'ls'", ")", ",", "CorrectedCommand", "(", "'ls -la'", ",", "priority", "=", "9000", ")", ",", "CorrectedCommand", "(", "'ls -lh'", ",", "priority", "=", "100", ")...
ensures that the function removes duplicates and sorts commands .
train
false
29,940
def oo_merge_hostvars(hostvars, variables, inventory_hostname): if (not isinstance(hostvars, Mapping)): raise errors.AnsibleFilterError('|failed expects hostvars is dictionary or object') if (not isinstance(variables, dict)): raise errors.AnsibleFilterError('|failed expects variables is a dictionary') if (not isinstance(inventory_hostname, string_types)): raise errors.AnsibleFilterError('|failed expects inventory_hostname is a string') ansible_version = pkg_resources.get_distribution('ansible').version merged_hostvars = {} if (LooseVersion(ansible_version) >= LooseVersion('2.0.0')): merged_hostvars = oo_merge_dicts(hostvars[inventory_hostname], variables) else: merged_hostvars = oo_merge_dicts(hostvars[inventory_hostname], hostvars) return merged_hostvars
[ "def", "oo_merge_hostvars", "(", "hostvars", ",", "variables", ",", "inventory_hostname", ")", ":", "if", "(", "not", "isinstance", "(", "hostvars", ",", "Mapping", ")", ")", ":", "raise", "errors", ".", "AnsibleFilterError", "(", "'|failed expects hostvars is dic...
merge host and play variables .
train
false
29,941
def pde_1st_linear_constant_coeff_homogeneous(eq, func, order, match, solvefun): f = func.func x = func.args[0] y = func.args[1] b = match[match['b']] c = match[match['c']] d = match[match['d']] return Eq(f(x, y), (exp((((- S(d)) / ((b ** 2) + (c ** 2))) * ((b * x) + (c * y)))) * solvefun(((c * x) - (b * y)))))
[ "def", "pde_1st_linear_constant_coeff_homogeneous", "(", "eq", ",", "func", ",", "order", ",", "match", ",", "solvefun", ")", ":", "f", "=", "func", ".", "func", "x", "=", "func", ".", "args", "[", "0", "]", "y", "=", "func", ".", "args", "[", "1", ...
solves a first order linear homogeneous partial differential equation with constant coefficients .
train
false
29,942
def maybe_evaluate(value): if isinstance(value, lazy): return value.evaluate() return value
[ "def", "maybe_evaluate", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "lazy", ")", ":", "return", "value", ".", "evaluate", "(", ")", "return", "value" ]
evaluate value only if value is a :class:lazy instance .
train
false
29,943
def get_country_code(request): if ('X-AppEngine-Country' in request.headers): if (request.headers['X-AppEngine-Country'] in pytz.country_timezones): return request.headers['X-AppEngine-Country'] return None
[ "def", "get_country_code", "(", "request", ")", ":", "if", "(", "'X-AppEngine-Country'", "in", "request", ".", "headers", ")", ":", "if", "(", "request", ".", "headers", "[", "'X-AppEngine-Country'", "]", "in", "pytz", ".", "country_timezones", ")", ":", "re...
country code based on iso 3166-1 .
train
false
29,944
def configure_before_handlers(app): @app.before_request def update_lastseen(): 'Updates `lastseen` before every reguest if the user is\n authenticated.' if current_user.is_authenticated: current_user.lastseen = time_utcnow() db.session.add(current_user) db.session.commit() if app.config['REDIS_ENABLED']: @app.before_request def mark_current_user_online(): if current_user.is_authenticated: mark_online(current_user.username) else: mark_online(request.remote_addr, guest=True)
[ "def", "configure_before_handlers", "(", "app", ")", ":", "@", "app", ".", "before_request", "def", "update_lastseen", "(", ")", ":", "if", "current_user", ".", "is_authenticated", ":", "current_user", ".", "lastseen", "=", "time_utcnow", "(", ")", "db", ".", ...
configures the before request handlers .
train
false
29,945
def unconvert_coords(col, row): return (((col - row) / 2), ((col + row) / 2))
[ "def", "unconvert_coords", "(", "col", ",", "row", ")", ":", "return", "(", "(", "(", "col", "-", "row", ")", "/", "2", ")", ",", "(", "(", "col", "+", "row", ")", "/", "2", ")", ")" ]
undoes what convert_coords does .
train
false
29,946
def _AddClearMethod(message_descriptor, cls): def Clear(self): self._fields = {} self._unknown_fields = () self._Modified() cls.Clear = Clear
[ "def", "_AddClearMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "Clear", "(", "self", ")", ":", "self", ".", "_fields", "=", "{", "}", "self", ".", "_unknown_fields", "=", "(", ")", "self", ".", "_Modified", "(", ")", "cls", ".", "C...
helper for _addmessagemethods() .
train
false
29,947
def _strftime(d): return d.strftime('%Y-%m-%dT%H:%M:%SZ%z')
[ "def", "_strftime", "(", "d", ")", ":", "return", "d", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%SZ%z'", ")" ]
format a date the way atom likes it .
train
false
29,948
def _add_doc(func, doc): func.__doc__ = doc
[ "def", "_add_doc", "(", "func", ",", "doc", ")", ":", "func", ".", "__doc__", "=", "doc" ]
add documentation to a function .
train
false
29,949
def _fastq_solexa_convert_fastq_illumina(in_handle, out_handle, alphabet=None): from Bio.SeqIO.QualityIO import phred_quality_from_solexa mapping = ''.join((([chr(0) for ascii in range(0, 59)] + [chr((64 + int(round(phred_quality_from_solexa(q))))) for q in range((-5), (62 + 1))]) + [chr(0) for ascii in range(127, 256)])) assert (len(mapping) == 256) return _fastq_generic(in_handle, out_handle, mapping)
[ "def", "_fastq_solexa_convert_fastq_illumina", "(", "in_handle", ",", "out_handle", ",", "alphabet", "=", "None", ")", ":", "from", "Bio", ".", "SeqIO", ".", "QualityIO", "import", "phred_quality_from_solexa", "mapping", "=", "''", ".", "join", "(", "(", "(", ...
fast solexa fastq to illumina 1 .
train
false
29,950
def package_file_exists(package, relative_path): if (relative_path is None): return False package_dir = _get_package_dir(package) if os.path.exists(package_dir): result = _regular_file_exists(package, relative_path) if result: return result if (int(sublime.version()) >= 3000): return _zip_file_exists(package, relative_path) return False
[ "def", "package_file_exists", "(", "package", ",", "relative_path", ")", ":", "if", "(", "relative_path", "is", "None", ")", ":", "return", "False", "package_dir", "=", "_get_package_dir", "(", "package", ")", "if", "os", ".", "path", ".", "exists", "(", "...
determines if a file exists inside of the package specified .
train
false
29,951
def _update_image_flash_params(esp, address, flash_params, image): if ((address == esp.FLASH_HEADER_OFFSET) and ((image[0] == '\xe9') or (image[0] == 233))): print(('Flash params set to 0x%04x' % struct.unpack('>H', flash_params))) image = ((image[0:2] + flash_params) + image[4:]) return image
[ "def", "_update_image_flash_params", "(", "esp", ",", "address", ",", "flash_params", ",", "image", ")", ":", "if", "(", "(", "address", "==", "esp", ".", "FLASH_HEADER_OFFSET", ")", "and", "(", "(", "image", "[", "0", "]", "==", "'\\xe9'", ")", "or", ...
modify the flash mode & size bytes if this looks like an executable image .
train
false
29,953
def find_address(ec2, public_ip, device_id, isinstance=True): if public_ip: return _find_address_by_ip(ec2, public_ip) elif (device_id and isinstance): return _find_address_by_device_id(ec2, device_id) elif device_id: return _find_address_by_device_id(ec2, device_id, isinstance=False)
[ "def", "find_address", "(", "ec2", ",", "public_ip", ",", "device_id", ",", "isinstance", "=", "True", ")", ":", "if", "public_ip", ":", "return", "_find_address_by_ip", "(", "ec2", ",", "public_ip", ")", "elif", "(", "device_id", "and", "isinstance", ")", ...
find an existing elastic ip address .
train
false
29,954
def add_glacier_checksums(params, **kwargs): request_dict = params headers = request_dict['headers'] body = request_dict['body'] if isinstance(body, six.binary_type): body = six.BytesIO(body) starting_position = body.tell() if ('x-amz-content-sha256' not in headers): headers['x-amz-content-sha256'] = utils.calculate_sha256(body, as_hex=True) body.seek(starting_position) if ('x-amz-sha256-tree-hash' not in headers): headers['x-amz-sha256-tree-hash'] = utils.calculate_tree_hash(body) body.seek(starting_position)
[ "def", "add_glacier_checksums", "(", "params", ",", "**", "kwargs", ")", ":", "request_dict", "=", "params", "headers", "=", "request_dict", "[", "'headers'", "]", "body", "=", "request_dict", "[", "'body'", "]", "if", "isinstance", "(", "body", ",", "six", ...
add glacier checksums to the http request .
train
false
29,955
def _is_step_running(step): return ((getattr(step.status, 'state', None) not in ('CANCELLED', 'INTERRUPTED')) and hasattr(step.status.timeline, 'startdatetime') and (not hasattr(step.status.timeline, 'enddatetime')))
[ "def", "_is_step_running", "(", "step", ")", ":", "return", "(", "(", "getattr", "(", "step", ".", "status", ",", "'state'", ",", "None", ")", "not", "in", "(", "'CANCELLED'", ",", "'INTERRUPTED'", ")", ")", "and", "hasattr", "(", "step", ".", "status"...
return true if the given step is currently running .
train
false
29,957
def check_pkgconfig(): pcfg = None zmq_config = None try: check_call(['pkg-config', '--exists', 'libzmq']) pcfg = Popen(['pkg-config', '--libs', '--cflags', 'libzmq'], stdout=subprocess.PIPE) except OSError as osexception: if (osexception.errno == errno.ENOENT): info('pkg-config not found') else: warn(('Running pkg-config failed - %s.' % osexception)) except CalledProcessError: info('Did not find libzmq via pkg-config.') if (pcfg is not None): (output, _) = pcfg.communicate() output = output.decode('utf8', 'replace') bits = output.strip().split() zmq_config = {'library_dirs': [], 'include_dirs': [], 'libraries': []} for tok in bits: if tok.startswith('-L'): zmq_config['library_dirs'].append(tok[2:]) if tok.startswith('-I'): zmq_config['include_dirs'].append(tok[2:]) if tok.startswith('-l'): zmq_config['libraries'].append(tok[2:]) info(('Settings obtained from pkg-config: %r' % zmq_config)) return zmq_config
[ "def", "check_pkgconfig", "(", ")", ":", "pcfg", "=", "None", "zmq_config", "=", "None", "try", ":", "check_call", "(", "[", "'pkg-config'", ",", "'--exists'", ",", "'libzmq'", "]", ")", "pcfg", "=", "Popen", "(", "[", "'pkg-config'", ",", "'--libs'", ",...
pull compile / link flags from pkg-config if present .
train
false
29,958
def get_all_roles(exclude_system=False): if exclude_system: result = Role.query(system=False) else: result = Role.get_all() return result
[ "def", "get_all_roles", "(", "exclude_system", "=", "False", ")", ":", "if", "exclude_system", ":", "result", "=", "Role", ".", "query", "(", "system", "=", "False", ")", "else", ":", "result", "=", "Role", ".", "get_all", "(", ")", "return", "result" ]
return all roles .
train
false
29,959
def list_scripts(default=False, none=True): lst = [] path = cfg.script_dir.get_path() if (path and os.access(path, os.R_OK)): for script in globber_full(path): if os.path.isfile(script): if ((sabnzbd.WIN32 and (os.path.splitext(script)[1].lower() in PATHEXT) and (not (win32api.GetFileAttributes(script) & win32file.FILE_ATTRIBUTE_HIDDEN))) or script.endswith('.py') or ((not sabnzbd.WIN32) and os.access(script, os.X_OK) and (not os.path.basename(script).startswith('.')))): lst.append(os.path.basename(script)) if none: lst.insert(0, 'None') if default: lst.insert(0, 'Default') return lst
[ "def", "list_scripts", "(", "default", "=", "False", ",", "none", "=", "True", ")", ":", "lst", "=", "[", "]", "path", "=", "cfg", ".", "script_dir", ".", "get_path", "(", ")", "if", "(", "path", "and", "os", ".", "access", "(", "path", ",", "os"...
return a list of script names .
train
false
29,961
def system_controls(attrs=None, where=None): return _osquery_cmd(table='system_controls', attrs=attrs, where=where)
[ "def", "system_controls", "(", "attrs", "=", "None", ",", "where", "=", "None", ")", ":", "return", "_osquery_cmd", "(", "table", "=", "'system_controls'", ",", "attrs", "=", "attrs", ",", "where", "=", "where", ")" ]
return system_controls information from osquery cli example: .
train
false
29,962
def iplot_mpl(mpl_fig, resize=False, strip_style=False, verbose=False, show_link=True, link_text='Export to plot.ly', validate=True, image=None, image_filename='plot_image', image_height=600, image_width=800): plotly_plot = tools.mpl_to_plotly(mpl_fig, resize, strip_style, verbose) return iplot(plotly_plot, show_link, link_text, validate, image=image, filename=image_filename, image_height=image_height, image_width=image_width)
[ "def", "iplot_mpl", "(", "mpl_fig", ",", "resize", "=", "False", ",", "strip_style", "=", "False", ",", "verbose", "=", "False", ",", "show_link", "=", "True", ",", "link_text", "=", "'Export to plot.ly'", ",", "validate", "=", "True", ",", "image", "=", ...
convert a matplotlib figure to a plotly graph and plot inside an ipython notebook without connecting to an external server .
train
false
29,963
def get_pgroup(path, follow_symlinks=True): return uid_to_user(get_pgid(path, follow_symlinks))
[ "def", "get_pgroup", "(", "path", ",", "follow_symlinks", "=", "True", ")", ":", "return", "uid_to_user", "(", "get_pgid", "(", "path", ",", "follow_symlinks", ")", ")" ]
return the name of the primary group that owns a given file this function will return the rarely used primary group of a file .
train
false
29,965
def stub_out_https_backend(stubs): class FakeHTTPResponse(object, ): def read(self): return DATA def fake_do_request(self, *args, **kwargs): return (httplib.OK, FakeHTTPResponse())
[ "def", "stub_out_https_backend", "(", "stubs", ")", ":", "class", "FakeHTTPResponse", "(", "object", ",", ")", ":", "def", "read", "(", "self", ")", ":", "return", "DATA", "def", "fake_do_request", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")",...
stubs out the httplib .
train
false
29,966
def thishost(): global _thishost if (_thishost is None): try: _thishost = socket.gethostbyname(socket.gethostname()) except socket.gaierror: _thishost = socket.gethostbyname('localhost') return _thishost
[ "def", "thishost", "(", ")", ":", "global", "_thishost", "if", "(", "_thishost", "is", "None", ")", ":", "try", ":", "_thishost", "=", "socket", ".", "gethostbyname", "(", "socket", ".", "gethostname", "(", ")", ")", "except", "socket", ".", "gaierror", ...
return the ip address of the current host .
train
false
29,967
def fix_bad_data(django_obj, dirty): if isinstance(django_obj, models.Node): if (django_obj.title.strip() == u''): django_obj.title = u'Blank Title' dirty = True if isinstance(django_obj, models.Embargo): if (django_obj.state == u'active'): django_obj.state = u'completed' dirty = True elif (django_obj.state == u'cancelled'): django_obj.state = u'rejected' dirty = True if isinstance(django_obj, models.Retraction): if (django_obj.state == u'cancelled'): django_obj.state = u'rejected' dirty = True if (django_obj.state == u'retracted'): django_obj.state = u'completed' dirty = True if (django_obj.state == u'pending'): django_obj.state = u'unapproved' dirty = True return (django_obj, dirty)
[ "def", "fix_bad_data", "(", "django_obj", ",", "dirty", ")", ":", "if", "isinstance", "(", "django_obj", ",", "models", ".", "Node", ")", ":", "if", "(", "django_obj", ".", "title", ".", "strip", "(", ")", "==", "u''", ")", ":", "django_obj", ".", "t...
this fixes a bunch of validation errors that happen during the migration .
train
false
29,969
def getHorizontalSegmentListsFromLoopLists(alreadyFilledArounds, front, numberOfLines, rotatedFillLoops, width): xIntersectionIndexLists = [] yList = [] frontOverWidth = getFrontOverWidthAddXListYList(front, alreadyFilledArounds, numberOfLines, xIntersectionIndexLists, width, yList) addXIntersectionIndexesFromLoops(frontOverWidth, rotatedFillLoops, (-1), xIntersectionIndexLists, width, yList) horizontalSegmentLists = [] for xIntersectionIndexListIndex in xrange(len(xIntersectionIndexLists)): xIntersectionIndexList = xIntersectionIndexLists[xIntersectionIndexListIndex] lineSegments = getSegmentsFromXIntersectionIndexes(xIntersectionIndexList, yList[xIntersectionIndexListIndex]) horizontalSegmentLists.append(lineSegments) return horizontalSegmentLists
[ "def", "getHorizontalSegmentListsFromLoopLists", "(", "alreadyFilledArounds", ",", "front", ",", "numberOfLines", ",", "rotatedFillLoops", ",", "width", ")", ":", "xIntersectionIndexLists", "=", "[", "]", "yList", "=", "[", "]", "frontOverWidth", "=", "getFrontOverWid...
get horizontal segment lists inside loops .
train
false
29,971
def fakeBootStrapper(n): if (n == 1): med = 0.1 CI = ((-0.25), 0.25) else: med = 0.2 CI = ((-0.35), 0.5) return (med, CI)
[ "def", "fakeBootStrapper", "(", "n", ")", ":", "if", "(", "n", "==", "1", ")", ":", "med", "=", "0.1", "CI", "=", "(", "(", "-", "0.25", ")", ",", "0.25", ")", "else", ":", "med", "=", "0.2", "CI", "=", "(", "(", "-", "0.35", ")", ",", "0...
this is just a placeholder for the users method of bootstrapping the median and its confidence intervals .
train
false
29,974
def test_slice_delslice_forbidden(): global setVal class foo: def __delslice__(self, i, j, value): global setVal setVal = (i, j, value) def __delitem__(self, index): global setVal setVal = index del foo()[::None] AreEqual(setVal, slice(None, None, None)) del foo()[::None] AreEqual(setVal, slice(None, None, None))
[ "def", "test_slice_delslice_forbidden", "(", ")", ":", "global", "setVal", "class", "foo", ":", "def", "__delslice__", "(", "self", ",", "i", ",", "j", ",", "value", ")", ":", "global", "setVal", "setVal", "=", "(", "i", ",", "j", ",", "value", ")", ...
providing no value for step forbids calling __delslice__ .
train
false
29,975
def option_chooser(options, attr=None): for (num, option) in enumerate(options): if attr: print(('%s: %s' % (num, getattr(option, attr)))) else: print(('%s: %s' % (num, option))) escape_opt = (num + 1) print(('%s: I want to exit!' % escape_opt)) choice = six.moves.input('Selection: ') try: ichoice = int(choice) if (ichoice > escape_opt): raise ValueError except ValueError: print(("Valid entries are the numbers 0-%s. Received '%s'." % (escape_opt, choice))) sys.exit() if (ichoice == escape_opt): print('Bye!') sys.exit() return ichoice
[ "def", "option_chooser", "(", "options", ",", "attr", "=", "None", ")", ":", "for", "(", "num", ",", "option", ")", "in", "enumerate", "(", "options", ")", ":", "if", "attr", ":", "print", "(", "(", "'%s: %s'", "%", "(", "num", ",", "getattr", "(",...
given an iterable .
train
true
29,976
def randomRotation(dim): return orth(random.random((dim, dim)))
[ "def", "randomRotation", "(", "dim", ")", ":", "return", "orth", "(", "random", ".", "random", "(", "(", "dim", ",", "dim", ")", ")", ")" ]
return a random rotation matrix of rank dim .
train
false
29,978
def profile_decorator(**options): if options.get('no_profile'): def decorator(func): return func return decorator def decorator(func): def replacement(*args, **kw): return DecoratedProfile(func, **options)(*args, **kw) return replacement return decorator
[ "def", "profile_decorator", "(", "**", "options", ")", ":", "if", "options", ".", "get", "(", "'no_profile'", ")", ":", "def", "decorator", "(", "func", ")", ":", "return", "func", "return", "decorator", "def", "decorator", "(", "func", ")", ":", "def", ...
profile a single function call .
train
false
29,979
def make_get_service_account_name_call(rpc): request = app_identity_service_pb.GetServiceAccountNameRequest() response = app_identity_service_pb.GetServiceAccountNameResponse() if (rpc.deadline is not None): request.set_deadline(rpc.deadline) def get_service_account_name_result(rpc): 'Check success, handle exceptions, and return converted RPC result.\n\n This method waits for the RPC if it has not yet finished, and calls the\n post-call hooks on the first invocation.\n\n Args:\n rpc: A UserRPC object.\n\n Returns:\n A string which is service account name of the app.\n ' assert (rpc.service == _APP_IDENTITY_SERVICE_NAME), repr(rpc.service) assert (rpc.method == _GET_SERVICE_ACCOUNT_NAME_METHOD_NAME), repr(rpc.method) try: rpc.check_success() except apiproxy_errors.ApplicationError as err: raise _to_app_identity_error(err) return response.service_account_name() rpc.make_call(_GET_SERVICE_ACCOUNT_NAME_METHOD_NAME, request, response, get_service_account_name_result)
[ "def", "make_get_service_account_name_call", "(", "rpc", ")", ":", "request", "=", "app_identity_service_pb", ".", "GetServiceAccountNameRequest", "(", ")", "response", "=", "app_identity_service_pb", ".", "GetServiceAccountNameResponse", "(", ")", "if", "(", "rpc", "."...
get service account name of the app .
train
false
29,980
def stack2params(stack): params = [] for s in stack: params.append(s['w'].flatten()) params.append(s['b'].flatten()) params = np.concatenate(params) net_config = {} if (len(stack) == 0): net_config['input_size'] = 0 net_config['layer_sizes'] = [] else: net_config['input_size'] = stack[0]['w'].shape[1] net_config['layer_sizes'] = [] for s in stack: net_config['layer_sizes'].append(s['w'].shape[0]) return (params, net_config)
[ "def", "stack2params", "(", "stack", ")", ":", "params", "=", "[", "]", "for", "s", "in", "stack", ":", "params", ".", "append", "(", "s", "[", "'w'", "]", ".", "flatten", "(", ")", ")", "params", ".", "append", "(", "s", "[", "'b'", "]", ".", ...
converts a "stack" structure into a flattened parameter vector and also stores the network configuration .
train
false
29,981
def make_edge_table(bt): data = asarray([d for d in bt.iter_data(axis='observation', dense=True)]) oids = asarray(bt.ids(axis='observation')) header = '#Sample DCTB OTU DCTB Abundance' lines = [header] for sample in bt.ids(): sample_ind = bt.index(sample, 'sample') otu_ids = oids[data[:, sample_ind].nonzero()[0]] otu_abs = data[:, sample_ind][data[:, sample_ind].nonzero()[0]] connections = [('%s DCTB %s DCTB %s' % (sample, otu, ab)) for (otu, ab) in zip(otu_ids, otu_abs)] lines.extend(connections) return lines
[ "def", "make_edge_table", "(", "bt", ")", ":", "data", "=", "asarray", "(", "[", "d", "for", "d", "in", "bt", ".", "iter_data", "(", "axis", "=", "'observation'", ",", "dense", "=", "True", ")", "]", ")", "oids", "=", "asarray", "(", "bt", ".", "...
make edge table where each sample is connected to the otus found in it .
train
false
29,983
def makeMnistDataSets(path): test = SupervisedDataSet((28 * 28), 10) test_image_file = os.path.join(path, 't10k-images-idx3-ubyte') test_label_file = os.path.join(path, 't10k-labels-idx1-ubyte') test_images = images(test_image_file) test_labels = (flaggedArrayByIndex(l, 10) for l in labels(test_label_file)) for (image, label) in zip(test_images, test_labels): test.addSample(image, label) train = SupervisedDataSet((28 * 28), 10) train_image_file = os.path.join(path, 'train-images-idx3-ubyte') train_label_file = os.path.join(path, 'train-labels-idx1-ubyte') train_images = images(train_image_file) train_labels = (flaggedArrayByIndex(l, 10) for l in labels(train_label_file)) for (image, label) in zip(train_images, train_labels): train.addSample(image, label) return (train, test)
[ "def", "makeMnistDataSets", "(", "path", ")", ":", "test", "=", "SupervisedDataSet", "(", "(", "28", "*", "28", ")", ",", "10", ")", "test_image_file", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'t10k-images-idx3-ubyte'", ")", "test_label_file...
return a pair consisting of two datasets .
train
false
29,984
def _parse_error(hstore_str, pos): ctx = 20 hslen = len(hstore_str) parsed_tail = hstore_str[max(((pos - ctx) - 1), 0):min(pos, hslen)] residual = hstore_str[min(pos, hslen):min(((pos + ctx) + 1), hslen)] if (len(parsed_tail) > ctx): parsed_tail = ('[...]' + parsed_tail[1:]) if (len(residual) > ctx): residual = (residual[:(-1)] + '[...]') return ('After %r, could not parse residual at position %d: %r' % (parsed_tail, pos, residual))
[ "def", "_parse_error", "(", "hstore_str", ",", "pos", ")", ":", "ctx", "=", "20", "hslen", "=", "len", "(", "hstore_str", ")", "parsed_tail", "=", "hstore_str", "[", "max", "(", "(", "(", "pos", "-", "ctx", ")", "-", "1", ")", ",", "0", ")", ":",...
format an unmarshalling error .
train
false
29,985
def has_write_permission(fileName): return os.access(fileName, os.W_OK)
[ "def", "has_write_permission", "(", "fileName", ")", ":", "return", "os", ".", "access", "(", "fileName", ",", "os", ".", "W_OK", ")" ]
check if the file has writing permissions .
train
false
29,988
def get_min_ncut(ev, d, w, num_cuts): mcut = np.inf mn = ev.min() mx = ev.max() min_mask = np.zeros_like(ev, dtype=np.bool) if np.allclose(mn, mx): return (min_mask, mcut) for t in np.linspace(mn, mx, num_cuts, endpoint=False): mask = (ev > t) cost = _ncut.ncut_cost(mask, d, w) if (cost < mcut): min_mask = mask mcut = cost return (min_mask, mcut)
[ "def", "get_min_ncut", "(", "ev", ",", "d", ",", "w", ",", "num_cuts", ")", ":", "mcut", "=", "np", ".", "inf", "mn", "=", "ev", ".", "min", "(", ")", "mx", "=", "ev", ".", "max", "(", ")", "min_mask", "=", "np", ".", "zeros_like", "(", "ev",...
threshold an eigenvector evenly .
train
false
29,989
def xldate_from_datetime_tuple(datetime_tuple, datemode): return (xldate_from_date_tuple(datetime_tuple[:3], datemode) + xldate_from_time_tuple(datetime_tuple[3:]))
[ "def", "xldate_from_datetime_tuple", "(", "datetime_tuple", ",", "datemode", ")", ":", "return", "(", "xldate_from_date_tuple", "(", "datetime_tuple", "[", ":", "3", "]", ",", "datemode", ")", "+", "xldate_from_time_tuple", "(", "datetime_tuple", "[", "3", ":", ...
convert a datetime tuple to an excel date value .
train
false
29,990
def get_patched_ast(source, sorted_children=False): return patch_ast(ast.parse(source), source, sorted_children)
[ "def", "get_patched_ast", "(", "source", ",", "sorted_children", "=", "False", ")", ":", "return", "patch_ast", "(", "ast", ".", "parse", "(", "source", ")", ",", "source", ",", "sorted_children", ")" ]
adds region and sorted_children fields to nodes adds sorted_children field only if sorted_children is true .
train
true
29,991
def getTetragridA(elementNode, prefix, tetragrid): keysA = getKeysA(prefix) evaluatedDictionary = evaluate.getEvaluatedDictionaryByEvaluationKeys(elementNode, keysA) if (len(evaluatedDictionary.keys()) < 1): return tetragrid for row in xrange(4): for column in xrange(4): key = getKeyA(row, column, prefix) if (key in evaluatedDictionary): value = evaluatedDictionary[key] if ((value == None) or (value == 'None')): print 'Warning, value in getTetragridA in matrix is None for key for dictionary:' print key print evaluatedDictionary else: tetragrid = getIdentityTetragrid(tetragrid) tetragrid[row][column] = float(value) euclidean.removeElementsFromDictionary(elementNode.attributes, keysA) return tetragrid
[ "def", "getTetragridA", "(", "elementNode", ",", "prefix", ",", "tetragrid", ")", ":", "keysA", "=", "getKeysA", "(", "prefix", ")", "evaluatedDictionary", "=", "evaluate", ".", "getEvaluatedDictionaryByEvaluationKeys", "(", "elementNode", ",", "keysA", ")", "if",...
get the tetragrid from the elementnode letter a values .
train
false
29,992
def wait_read(fileno, timeout=None, timeout_exc=timeout('timed out')): io = get_hub().loop.io(fileno, 1) return wait(io, timeout, timeout_exc)
[ "def", "wait_read", "(", "fileno", ",", "timeout", "=", "None", ",", "timeout_exc", "=", "timeout", "(", "'timed out'", ")", ")", ":", "io", "=", "get_hub", "(", ")", ".", "loop", ".", "io", "(", "fileno", ",", "1", ")", "return", "wait", "(", "io"...
block the current greenlet until *fileno* is ready to read .
train
false
29,993
def test_context_config(): default_config = get_default_config() c = GLContext(default_config) assert_equal(c.config, default_config) c.config['double_buffer'] = False assert_not_equal(c.config, default_config) c = GLContext() assert_equal(c.config, default_config) c.config['double_buffer'] = False assert_not_equal(c.config, default_config) c = GLContext({'red_size': 4, 'double_buffer': False}) assert_equal(c.config.keys(), default_config.keys()) assert_raises(KeyError, GLContext, {'foo': 3}) assert_raises(TypeError, GLContext, {'double_buffer': 'not_bool'}) assert ('gl_version' in c.capabilities)
[ "def", "test_context_config", "(", ")", ":", "default_config", "=", "get_default_config", "(", ")", "c", "=", "GLContext", "(", "default_config", ")", "assert_equal", "(", "c", ".", "config", ",", "default_config", ")", "c", ".", "config", "[", "'double_buffer...
test glcontext handling of config dict .
train
false
29,994
def getScrollbarCanvasPortion(scrollbar): scrollbarBeginEnd = scrollbar.get() return (scrollbarBeginEnd[1] - scrollbarBeginEnd[0])
[ "def", "getScrollbarCanvasPortion", "(", "scrollbar", ")", ":", "scrollbarBeginEnd", "=", "scrollbar", ".", "get", "(", ")", "return", "(", "scrollbarBeginEnd", "[", "1", "]", "-", "scrollbarBeginEnd", "[", "0", "]", ")" ]
get the canvas portion of the scrollbar .
train
false
29,995
def Bail_Out(browserhost, cherryport, err=''): logging.error(((T('Failed to start web-interface') + ' : ') + str(err))) if (not sabnzbd.DAEMON): if ('13' in err): panic_xport(browserhost, cherryport) elif ('49' in err): panic_host(browserhost, cherryport) else: panic_port(browserhost, cherryport) sabnzbd.halt() exit_sab(2)
[ "def", "Bail_Out", "(", "browserhost", ",", "cherryport", ",", "err", "=", "''", ")", ":", "logging", ".", "error", "(", "(", "(", "T", "(", "'Failed to start web-interface'", ")", "+", "' : '", ")", "+", "str", "(", "err", ")", ")", ")", "if", "(", ...
abort program because of cherrypy troubles .
train
false