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,170
def load_all_models(): s3db.load_all_models() return 'ok'
[ "def", "load_all_models", "(", ")", ":", "s3db", ".", "load_all_models", "(", ")", "return", "'ok'" ]
controller to load all models in web browser - to make it easy to debug in eclipse .
train
false
34,172
def p_statement_assign_2(t): names[t[1]] = t[3]
[ "def", "p_statement_assign_2", "(", "t", ")", ":", "names", "[", "t", "[", "1", "]", "]", "=", "t", "[", "3", "]" ]
statement : name equals number .
train
false
34,173
def isString(s): try: return (isinstance(s, unicode) or isintance(s, basestring)) except NameError: return isinstance(s, str)
[ "def", "isString", "(", "s", ")", ":", "try", ":", "return", "(", "isinstance", "(", "s", ",", "unicode", ")", "or", "isintance", "(", "s", ",", "basestring", ")", ")", "except", "NameError", ":", "return", "isinstance", "(", "s", ",", "str", ")" ]
convenience method that works with all 2 .
train
true
34,174
def mock_factory(r): mocked = mock_obj_to_dict(r) mocked.configure_mock(**r) return mocked
[ "def", "mock_factory", "(", "r", ")", ":", "mocked", "=", "mock_obj_to_dict", "(", "r", ")", "mocked", ".", "configure_mock", "(", "**", "r", ")", "return", "mocked" ]
mocks all the attributes as well as the to_dict .
train
false
34,175
def getlogin(): if (sys.platform != 'win32'): import pwd return pwd.getpwuid(os.getuid())[0] else: return os.environ['USERNAME']
[ "def", "getlogin", "(", ")", ":", "if", "(", "sys", ".", "platform", "!=", "'win32'", ")", ":", "import", "pwd", "return", "pwd", ".", "getpwuid", "(", "os", ".", "getuid", "(", ")", ")", "[", "0", "]", "else", ":", "return", "os", ".", "environ"...
avoid using os .
train
false
34,180
def updating(name, jail=None, chroot=None, root=None, filedate=None, filename=None): opts = '' if filedate: opts += 'd {0}'.format(filedate) if filename: opts += 'f {0}'.format(filename) cmd = _pkg(jail, chroot, root) cmd.append('updating') if opts: cmd.append(('-' + opts)) cmd.append(name) return __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
[ "def", "updating", "(", "name", ",", "jail", "=", "None", ",", "chroot", "=", "None", ",", "root", "=", "None", ",", "filedate", "=", "None", ",", "filename", "=", "None", ")", ":", "opts", "=", "''", "if", "filedate", ":", "opts", "+=", "'d {0}'",...
displays updating entries of software packages cli example: .
train
true
34,181
def migrate_node(node): for (key, file_id) in node.files_current.iteritems(): if (key not in node.files_versions): node.files_versions[key] = [file_id] elif (file_id not in node.files_versions[key]): node.files_versions[key].append(file_id) node.save()
[ "def", "migrate_node", "(", "node", ")", ":", "for", "(", "key", ",", "file_id", ")", "in", "node", ".", "files_current", ".", "iteritems", "(", ")", ":", "if", "(", "key", "not", "in", "node", ".", "files_versions", ")", ":", "node", ".", "files_ver...
ensure that all keys present in files_current are also present in files_versions .
train
false
34,183
def _accumulate_normals(tris, tri_nn, npts): nn = np.zeros((npts, 3)) for verts in tris.T: for idx in range(3): nn[:, idx] += np.bincount(verts, weights=tri_nn[:, idx], minlength=npts) return nn
[ "def", "_accumulate_normals", "(", "tris", ",", "tri_nn", ",", "npts", ")", ":", "nn", "=", "np", ".", "zeros", "(", "(", "npts", ",", "3", ")", ")", "for", "verts", "in", "tris", ".", "T", ":", "for", "idx", "in", "range", "(", "3", ")", ":", ...
efficiently accumulate triangle normals .
train
false
34,185
def get_neg_detection_mode(): raise NotImplementedError('TODO: implement this function.')
[ "def", "get_neg_detection_mode", "(", ")", ":", "raise", "NotImplementedError", "(", "'TODO: implement this function.'", ")" ]
returns a theano mode that detects if any negative value occurs in the evaluation of a theano function .
train
false
34,187
def test_cat_to_polor(test_data, polar_cats): level_0 = len(test_data.auto_data[['cyl']].drop_duplicates()) level_1 = len(test_data.auto_data[['cyl', 'origin']].drop_duplicates()) num_groups = (level_0 + level_1) assert (len(polar_cats) == num_groups)
[ "def", "test_cat_to_polor", "(", "test_data", ",", "polar_cats", ")", ":", "level_0", "=", "len", "(", "test_data", ".", "auto_data", "[", "[", "'cyl'", "]", "]", ".", "drop_duplicates", "(", ")", ")", "level_1", "=", "len", "(", "test_data", ".", "auto_...
check known example for how many rows should exist based on columns .
train
false
34,188
def deploy_index(): response = current.response def prep(r): default_url = URL(f='mission', args='summary', vars={}) return current.s3db.cms_documentation(r, 'RDRT', default_url) response.s3.prep = prep output = current.rest_controller('cms', 'post') view = path.join(current.request.folder, 'modules', 'templates', THEME, 'views', 'deploy', 'index.html') try: response.view = open(view, 'rb') except IOError: from gluon.http import HTTP raise HTTP(404, ('Unable to open Custom View: %s' % view)) return output
[ "def", "deploy_index", "(", ")", ":", "response", "=", "current", ".", "response", "def", "prep", "(", "r", ")", ":", "default_url", "=", "URL", "(", "f", "=", "'mission'", ",", "args", "=", "'summary'", ",", "vars", "=", "{", "}", ")", "return", "...
custom module homepage for deploy to display online documentation for the module .
train
false
34,189
def ofs_nbits(start, end): return ((start << 6) + (end - start))
[ "def", "ofs_nbits", "(", "start", ",", "end", ")", ":", "return", "(", "(", "start", "<<", "6", ")", "+", "(", "end", "-", "start", ")", ")" ]
the utility method for ofs_nbits this method is used in the class to set the ofs_nbits .
train
false
34,190
def appstats_wsgi_middleware(app): def appstats_wsgi_wrapper(environ, start_response): 'Outer wrapper function around the WSGI protocol.\n\n The top-level appstats_wsgi_middleware() function returns this\n function to the caller instead of the app class or function passed\n in. When the caller calls this function (which may happen\n multiple times, to handle multiple requests) this function\n instantiates the app class (or calls the app function), sandwiched\n between calls to start_recording() and end_recording() which\n manipulate the recording state.\n\n The signature is determined by the WSGI protocol.\n ' start_recording(environ) save_status = [None] datamodel_pb.AggregateRpcStatsProto.total_billed_ops_str = total_billed_ops_to_str datamodel_pb.IndividualRpcStatsProto.billed_ops_str = individual_billed_ops_to_str def appstats_start_response(status, headers, exc_info=None): "Inner wrapper function for the start_response() function argument.\n\n The purpose of this wrapper is save the HTTP status (which the\n WSGI protocol only makes available through the start_response()\n function) into the surrounding scope. This is done through a\n hack because Python 2.x doesn't support assignment to nonlocal\n variables. If this function is called more than once, the last\n status value will be used.\n\n The signature is determined by the WSGI protocol.\n " save_status.append(status) return start_response(status, headers, exc_info) try: result = app(environ, appstats_start_response) except Exception: end_recording(500) raise if (result is not None): for value in result: (yield value) status = save_status[(-1)] if (status is not None): status = status[:3] end_recording(status) return appstats_wsgi_wrapper
[ "def", "appstats_wsgi_middleware", "(", "app", ")", ":", "def", "appstats_wsgi_wrapper", "(", "environ", ",", "start_response", ")", ":", "start_recording", "(", "environ", ")", "save_status", "=", "[", "None", "]", "datamodel_pb", ".", "AggregateRpcStatsProto", "...
wsgi middleware to install the instrumentation .
train
false
34,191
def recommend_for_user(user): return recommend_for_brands(brandsfor.get(user, set()))
[ "def", "recommend_for_user", "(", "user", ")", ":", "return", "recommend_for_brands", "(", "brandsfor", ".", "get", "(", "user", ",", "set", "(", ")", ")", ")" ]
get a users brands and recommend based on them .
train
false
34,192
def dictify(entries): result = {} for entry in entries: result[entry.path] = entry.weight return result
[ "def", "dictify", "(", "entries", ")", ":", "result", "=", "{", "}", "for", "entry", "in", "entries", ":", "result", "[", "entry", ".", "path", "]", "=", "entry", ".", "weight", "return", "result" ]
converts a list of entries into a dictionary where key = path value = weight .
train
false
34,193
def _ParseManifestSection(section, jar_file_name): section = section.replace('\n ', '').rstrip('\n') if (not section): return {} try: return dict((line.split(': ', 1) for line in section.split('\n'))) except ValueError: raise InvalidJarError(('%s: Invalid manifest %r' % (jar_file_name, section)))
[ "def", "_ParseManifestSection", "(", "section", ",", "jar_file_name", ")", ":", "section", "=", "section", ".", "replace", "(", "'\\n '", ",", "''", ")", ".", "rstrip", "(", "'\\n'", ")", "if", "(", "not", "section", ")", ":", "return", "{", "}", "try"...
parse a dict out of the given manifest section string .
train
false
34,196
def as2d(ar): if (ar.ndim == 2): return ar else: aux = np.array(ar, copy=False) aux.shape = (ar.shape[0], 1) return aux
[ "def", "as2d", "(", "ar", ")", ":", "if", "(", "ar", ".", "ndim", "==", "2", ")", ":", "return", "ar", "else", ":", "aux", "=", "np", ".", "array", "(", "ar", ",", "copy", "=", "False", ")", "aux", ".", "shape", "=", "(", "ar", ".", "shape"...
if the input array is 2d return it .
train
false
34,197
def add_instance_type_access(flavorid, projectid, ctxt=None): if (ctxt is None): ctxt = context.get_admin_context() return db.instance_type_access_add(ctxt, flavorid, projectid)
[ "def", "add_instance_type_access", "(", "flavorid", ",", "projectid", ",", "ctxt", "=", "None", ")", ":", "if", "(", "ctxt", "is", "None", ")", ":", "ctxt", "=", "context", ".", "get_admin_context", "(", ")", "return", "db", ".", "instance_type_access_add", ...
add instance type access for project .
train
false
34,198
def format_labels_string(header, labels): if (header in SPACE_SEPARATED_LABEL_HEADERS): sep = ' ' else: sep = ',' return sep.join(labels)
[ "def", "format_labels_string", "(", "header", ",", "labels", ")", ":", "if", "(", "header", "in", "SPACE_SEPARATED_LABEL_HEADERS", ")", ":", "sep", "=", "' '", "else", ":", "sep", "=", "','", "return", "sep", ".", "join", "(", "labels", ")" ]
formats labels for embedding into a message .
train
false
34,200
def import_no_virt_driver_config_deps(physical_line, filename): thisdriver = _get_virt_name(virt_file_re, filename) thatdriver = _get_virt_name(virt_config_re, physical_line) if ((thatdriver is not None) and (thisdriver is not None) and (thisdriver != thatdriver)): return (0, 'N312: using config vars from other virt drivers forbidden')
[ "def", "import_no_virt_driver_config_deps", "(", "physical_line", ",", "filename", ")", ":", "thisdriver", "=", "_get_virt_name", "(", "virt_file_re", ",", "filename", ")", "thatdriver", "=", "_get_virt_name", "(", "virt_config_re", ",", "physical_line", ")", "if", ...
check virt drivers config vars arent used by other drivers modules under each virt drivers directory are considered private to that virt driver .
train
false
34,201
def text_remove_empty_lines(text): lines = [line.rstrip() for line in text.splitlines() if line.strip()] return '\n'.join(lines)
[ "def", "text_remove_empty_lines", "(", "text", ")", ":", "lines", "=", "[", "line", ".", "rstrip", "(", ")", "for", "line", "in", "text", ".", "splitlines", "(", ")", "if", "line", ".", "strip", "(", ")", "]", "return", "'\\n'", ".", "join", "(", "...
whitespace normalization: - strip empty lines - strip trailing whitespace .
train
true
34,202
def normalize_mode(mode): if (mode is None): return None if (not isinstance(mode, six.string_types)): mode = str(mode) return mode.strip('"').strip("'").lstrip('0').zfill(4)
[ "def", "normalize_mode", "(", "mode", ")", ":", "if", "(", "mode", "is", "None", ")", ":", "return", "None", "if", "(", "not", "isinstance", "(", "mode", ",", "six", ".", "string_types", ")", ")", ":", "mode", "=", "str", "(", "mode", ")", "return"...
return a mode value .
train
false
34,203
def get_programs_credentials(user): programs_credentials = get_user_program_credentials(user) credentials_data = [] for program in programs_credentials: try: program_data = {u'display_name': program[u'title'], u'subtitle': program[u'subtitle'], u'credential_url': program[u'credential_url']} credentials_data.append(program_data) except KeyError: log.warning(u'Program structure is invalid: %r', program) return credentials_data
[ "def", "get_programs_credentials", "(", "user", ")", ":", "programs_credentials", "=", "get_user_program_credentials", "(", "user", ")", "credentials_data", "=", "[", "]", "for", "program", "in", "programs_credentials", ":", "try", ":", "program_data", "=", "{", "...
return program credentials data required for display .
train
false
34,204
def _fix_user_options(options): def to_str_or_none(x): if (x is None): return None return str(x) return [tuple((to_str_or_none(x) for x in y)) for y in options]
[ "def", "_fix_user_options", "(", "options", ")", ":", "def", "to_str_or_none", "(", "x", ")", ":", "if", "(", "x", "is", "None", ")", ":", "return", "None", "return", "str", "(", "x", ")", "return", "[", "tuple", "(", "(", "to_str_or_none", "(", "x",...
this is for python 2 .
train
false
34,205
def unload_metadefs(): return get_backend().db_unload_metadefs(engine=db_api.get_engine())
[ "def", "unload_metadefs", "(", ")", ":", "return", "get_backend", "(", ")", ".", "db_unload_metadefs", "(", "engine", "=", "db_api", ".", "get_engine", "(", ")", ")" ]
unload metadefinitions from database .
train
false
34,206
def vt_get_volume_type_by_name(context, name): if (name == fake_vt['name']): return fake_vt raise exception.VolumeTypeNotFoundByName(volume_type_name=name)
[ "def", "vt_get_volume_type_by_name", "(", "context", ",", "name", ")", ":", "if", "(", "name", "==", "fake_vt", "[", "'name'", "]", ")", ":", "return", "fake_vt", "raise", "exception", ".", "VolumeTypeNotFoundByName", "(", "volume_type_name", "=", "name", ")" ...
replacement for cinder .
train
false
34,207
def getDisplayedDialogFromPath(path): pluginModule = archive.getModuleWithPath(path) if (pluginModule == None): return None return getDisplayedDialogFromConstructor(pluginModule.getNewRepository())
[ "def", "getDisplayedDialogFromPath", "(", "path", ")", ":", "pluginModule", "=", "archive", ".", "getModuleWithPath", "(", "path", ")", "if", "(", "pluginModule", "==", "None", ")", ":", "return", "None", "return", "getDisplayedDialogFromConstructor", "(", "plugin...
display the repository dialog .
train
false
34,208
def setTracebackClearing(clear=True): global clear_tracebacks clear_tracebacks = clear
[ "def", "setTracebackClearing", "(", "clear", "=", "True", ")", ":", "global", "clear_tracebacks", "clear_tracebacks", "=", "clear" ]
enable or disable traceback clearing .
train
false
34,209
def get_arg_spec(func, debug=True): (allargs, varargs, keywords, defaults) = inspect.getargspec(func) if ('self' in allargs): allargs.remove('self') nargs = len(allargs) ndefaults = 0 if defaults: ndefaults = len(defaults) nrequired = (nargs - ndefaults) args = allargs[:nrequired] kwargs = allargs[nrequired:] if debug: log.debug(('nargs = %s' % nargs)) log.debug(('ndefaults = %s' % ndefaults)) log.debug(('nrequired = %s' % nrequired)) log.debug(('args = %s' % args)) log.debug(('kwargs = %s' % kwargs)) log.debug(('defaults = %s' % str(defaults))) return (args, kwargs)
[ "def", "get_arg_spec", "(", "func", ",", "debug", "=", "True", ")", ":", "(", "allargs", ",", "varargs", ",", "keywords", ",", "defaults", ")", "=", "inspect", ".", "getargspec", "(", "func", ")", "if", "(", "'self'", "in", "allargs", ")", ":", "alla...
convenience wrapper around inspect .
train
false
34,211
def easyxf(strg_to_parse='', num_format_str=None, field_sep=',', line_sep=';', intro_sep=':', esc_char='\\', debug=False): xfobj = XFStyle() if (num_format_str is not None): xfobj.num_format_str = num_format_str if strg_to_parse: _parse_strg_to_obj(strg_to_parse, xfobj, xf_dict, field_sep=field_sep, line_sep=line_sep, intro_sep=intro_sep, esc_char=esc_char, debug=debug) return xfobj
[ "def", "easyxf", "(", "strg_to_parse", "=", "''", ",", "num_format_str", "=", "None", ",", "field_sep", "=", "','", ",", "line_sep", "=", "';'", ",", "intro_sep", "=", "':'", ",", "esc_char", "=", "'\\\\'", ",", "debug", "=", "False", ")", ":", "xfobj"...
this function is used to create and configure :class:xfstyle objects for use with the :meth:worksheet .
train
false
34,212
def decode_image_data(data): try: return data.split(',')[1].decode('base64') except (IndexError, UnicodeEncodeError): log.exception('Could not decode image data') raise InvalidImageData
[ "def", "decode_image_data", "(", "data", ")", ":", "try", ":", "return", "data", ".", "split", "(", "','", ")", "[", "1", "]", ".", "decode", "(", "'base64'", ")", "except", "(", "IndexError", ",", "UnicodeEncodeError", ")", ":", "log", ".", "exception...
decode base64-encoded image data .
train
false
34,213
def libvlc_video_set_track(p_mi, i_track): f = (_Cfunctions.get('libvlc_video_set_track', None) or _Cfunction('libvlc_video_set_track', ((1,), (1,)), None, ctypes.c_int, MediaPlayer, ctypes.c_int)) return f(p_mi, i_track)
[ "def", "libvlc_video_set_track", "(", "p_mi", ",", "i_track", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_video_set_track'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_video_set_track'", ",", "(", "(", "1", ",", ")", ",", "("...
set video track .
train
true
34,214
def _removeReceiver(receiver): if (not sendersBack): return False backKey = id(receiver) for senderkey in sendersBack.get(backKey, ()): try: signals = connections[senderkey].keys() except KeyError as err: pass else: for signal in signals: try: receivers = connections[senderkey][signal] except KeyError: pass else: try: receivers.remove(receiver) except Exception as err: pass _cleanupConnections(senderkey, signal) try: del sendersBack[backKey] except KeyError: pass
[ "def", "_removeReceiver", "(", "receiver", ")", ":", "if", "(", "not", "sendersBack", ")", ":", "return", "False", "backKey", "=", "id", "(", "receiver", ")", "for", "senderkey", "in", "sendersBack", ".", "get", "(", "backKey", ",", "(", ")", ")", ":",...
remove receiver from connections .
train
false
34,215
def list_returner_functions(*args, **kwargs): returners_ = salt.loader.returners(__opts__, []) if (not args): return sorted(returners_) names = set() for module in args: if (('*' in module) or ('.' in module)): for func in fnmatch.filter(returners_, module): names.add(func) else: moduledot = (module + '.') for func in returners_: if func.startswith(moduledot): names.add(func) return sorted(names)
[ "def", "list_returner_functions", "(", "*", "args", ",", "**", "kwargs", ")", ":", "returners_", "=", "salt", ".", "loader", ".", "returners", "(", "__opts__", ",", "[", "]", ")", "if", "(", "not", "args", ")", ":", "return", "sorted", "(", "returners_...
list the functions for all returner modules .
train
true
34,216
def start_event_loop_wx(app=None): if (app is None): app = get_app_wx() if (not is_event_loop_running_wx(app)): app._in_event_loop = True app.MainLoop() app._in_event_loop = False else: app._in_event_loop = True
[ "def", "start_event_loop_wx", "(", "app", "=", "None", ")", ":", "if", "(", "app", "is", "None", ")", ":", "app", "=", "get_app_wx", "(", ")", "if", "(", "not", "is_event_loop_running_wx", "(", "app", ")", ")", ":", "app", ".", "_in_event_loop", "=", ...
start the wx event loop in a consistent manner .
train
true
34,217
def _check_dipole(dip, n_dipoles): assert_equal(len(dip), n_dipoles) assert_equal(dip.pos.shape, (n_dipoles, 3)) assert_equal(dip.ori.shape, (n_dipoles, 3)) assert_equal(dip.gof.shape, (n_dipoles,)) assert_equal(dip.amplitude.shape, (n_dipoles,))
[ "def", "_check_dipole", "(", "dip", ",", "n_dipoles", ")", ":", "assert_equal", "(", "len", "(", "dip", ")", ",", "n_dipoles", ")", "assert_equal", "(", "dip", ".", "pos", ".", "shape", ",", "(", "n_dipoles", ",", "3", ")", ")", "assert_equal", "(", ...
check dipole sizes .
train
false
34,218
def get_readable_ctx_date(ctx): (t, tz) = ctx.date() date = datetime(*gmtime((float(t) - tz))[:6]) ctx_date = date.strftime('%Y-%m-%d') return ctx_date
[ "def", "get_readable_ctx_date", "(", "ctx", ")", ":", "(", "t", ",", "tz", ")", "=", "ctx", ".", "date", "(", ")", "date", "=", "datetime", "(", "*", "gmtime", "(", "(", "float", "(", "t", ")", "-", "tz", ")", ")", "[", ":", "6", "]", ")", ...
convert the date of the changeset to a human-readable date .
train
false
34,219
def free_slave(**connection_args): slave_db = _connect(**connection_args) if (slave_db is None): return '' slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor) slave_cur.execute('show slave status') slave_status = slave_cur.fetchone() master = {'host': slave_status['Master_Host']} try: master_db = _connect(**master) if (master_db is None): return '' master_cur = master_db.cursor() master_cur.execute('flush logs') master_db.close() except MySQLdb.OperationalError: pass slave_cur.execute('stop slave') slave_cur.execute('reset master') slave_cur.execute('change master to MASTER_HOST=') slave_cur.execute('show slave status') results = slave_cur.fetchone() if (results is None): return 'promoted' else: return 'failed'
[ "def", "free_slave", "(", "**", "connection_args", ")", ":", "slave_db", "=", "_connect", "(", "**", "connection_args", ")", "if", "(", "slave_db", "is", "None", ")", ":", "return", "''", "slave_cur", "=", "slave_db", ".", "cursor", "(", "MySQLdb", ".", ...
frees a slave from its master .
train
true
34,220
def get_network_device(hardware_devices, mac_address): if (hardware_devices.__class__.__name__ == 'ArrayOfVirtualDevice'): hardware_devices = hardware_devices.VirtualDevice for device in hardware_devices: if (device.__class__.__name__ in vm_util.ALL_SUPPORTED_NETWORK_DEVICES): if hasattr(device, 'macAddress'): if (device.macAddress == mac_address): return device
[ "def", "get_network_device", "(", "hardware_devices", ",", "mac_address", ")", ":", "if", "(", "hardware_devices", ".", "__class__", ".", "__name__", "==", "'ArrayOfVirtualDevice'", ")", ":", "hardware_devices", "=", "hardware_devices", ".", "VirtualDevice", "for", ...
return the network device with mac mac_address .
train
false
34,221
def cached_download(url): cache_root = os.path.join(_dataset_root, '_dl_cache') try: os.makedirs(cache_root) except OSError: if (not os.path.exists(cache_root)): raise RuntimeError('cannot create download cache directory') lock_path = os.path.join(cache_root, '_dl_lock') urlhash = hashlib.md5(url.encode('utf-8')).hexdigest() cache_path = os.path.join(cache_root, urlhash) with filelock.FileLock(lock_path): if os.path.exists(cache_path): return cache_path temp_root = tempfile.mkdtemp(dir=cache_root) try: temp_path = os.path.join(temp_root, 'dl') print('Downloading from {}...'.format(url)) request.urlretrieve(url, temp_path) with filelock.FileLock(lock_path): shutil.move(temp_path, cache_path) finally: shutil.rmtree(temp_root) return cache_path
[ "def", "cached_download", "(", "url", ")", ":", "cache_root", "=", "os", ".", "path", ".", "join", "(", "_dataset_root", ",", "'_dl_cache'", ")", "try", ":", "os", ".", "makedirs", "(", "cache_root", ")", "except", "OSError", ":", "if", "(", "not", "os...
downloads a file and caches it .
train
false
34,222
def _volume_get(context, volume_id): return TEST_VOLUME[int(volume_id.replace('-', ''))]
[ "def", "_volume_get", "(", "context", ",", "volume_id", ")", ":", "return", "TEST_VOLUME", "[", "int", "(", "volume_id", ".", "replace", "(", "'-'", ",", "''", ")", ")", "]" ]
return predefined volume info .
train
false
34,223
def sorted_dict(data): if (type(data) == OrderedDict): data = dict(data) if (type(data) == dict): data = OrderedDict(sorted(data.items(), key=(lambda t: t[0]))) elif (type(data) == list): for count in range(len(data)): data[count] = OrderedDict(sorted(data[count].items(), key=(lambda t: t[0]))) return data
[ "def", "sorted_dict", "(", "data", ")", ":", "if", "(", "type", "(", "data", ")", "==", "OrderedDict", ")", ":", "data", "=", "dict", "(", "data", ")", "if", "(", "type", "(", "data", ")", "==", "dict", ")", ":", "data", "=", "OrderedDict", "(", ...
sorts a json and returns ordereddict .
train
false
34,224
def show_conf(conf_file=default_conf): return _parse_conf(conf_file)
[ "def", "show_conf", "(", "conf_file", "=", "default_conf", ")", ":", "return", "_parse_conf", "(", "conf_file", ")" ]
show parsed configuration cli example: .
train
false
34,225
def discrete_attributes(domain): return [attr for attr in (domain.variables + domain.metas) if attr.is_discrete]
[ "def", "discrete_attributes", "(", "domain", ")", ":", "return", "[", "attr", "for", "attr", "in", "(", "domain", ".", "variables", "+", "domain", ".", "metas", ")", "if", "attr", ".", "is_discrete", "]" ]
return all discrete attributes from the domain .
train
false
34,226
def assert_ok_response(response): nose.tools.assert_true(200, response.status_code) return response
[ "def", "assert_ok_response", "(", "response", ")", ":", "nose", ".", "tools", ".", "assert_true", "(", "200", ",", "response", ".", "status_code", ")", "return", "response" ]
checks that the response returned successfully .
train
false
34,227
@xmlrpc_func(returns='struct[]', args=['string', 'string', 'string']) def get_categories(blog_id, username, password): authenticate(username, password) site = Site.objects.get_current() return [category_structure(category, site) for category in Category.objects.all()]
[ "@", "xmlrpc_func", "(", "returns", "=", "'struct[]'", ",", "args", "=", "[", "'string'", ",", "'string'", ",", "'string'", "]", ")", "def", "get_categories", "(", "blog_id", ",", "username", ",", "password", ")", ":", "authenticate", "(", "username", ",",...
return the published categories .
train
true
34,228
def _check_density(density, n_features): if (density == 'auto'): density = (1 / np.sqrt(n_features)) elif ((density <= 0) or (density > 1)): raise ValueError(('Expected density in range ]0, 1], got: %r' % density)) return density
[ "def", "_check_density", "(", "density", ",", "n_features", ")", ":", "if", "(", "density", "==", "'auto'", ")", ":", "density", "=", "(", "1", "/", "np", ".", "sqrt", "(", "n_features", ")", ")", "elif", "(", "(", "density", "<=", "0", ")", "or", ...
factorize density check according to li et al .
train
false
34,229
def get_input_format_for_book(db, book_id, pref): if (pref is None): pref = get_preferred_input_format_for_book(db, book_id) if hasattr(pref, 'lower'): pref = pref.lower() input_formats = get_supported_input_formats_for_book(db, book_id) input_format = (pref if (pref in input_formats) else sort_formats_by_preference(input_formats, prefs['input_format_order'])[0]) return (input_format, input_formats)
[ "def", "get_input_format_for_book", "(", "db", ",", "book_id", ",", "pref", ")", ":", "if", "(", "pref", "is", "None", ")", ":", "pref", "=", "get_preferred_input_format_for_book", "(", "db", ",", "book_id", ")", "if", "hasattr", "(", "pref", ",", "'lower'...
return for the book identified by book_id .
train
false
34,230
def run_group_significance_test(data_generator, test, test_choices, reps=1000): (pvals, test_stats, means) = ([], [], []) for row in data_generator: if (test == 'nonparametric_t_test'): (test_stat, _, _, pval) = test_choices[test](row[0], row[1], permutations=reps) elif (test == 'bootstrap_mann_whitney_u'): (test_stat, pval) = test_choices[test](row[0], row[1], num_reps=reps) elif (test in ['parametric_t_test', 'mann_whitney_u']): (test_stat, pval) = test_choices[test](row[0], row[1]) else: try: (test_stat, pval) = test_choices[test](row) except ValueError: test_stat = nan pval = nan test_stats.append(test_stat) pvals.append(pval) means.append([i.mean() for i in row]) return (test_stats, pvals, means)
[ "def", "run_group_significance_test", "(", "data_generator", ",", "test", ",", "test_choices", ",", "reps", "=", "1000", ")", ":", "(", "pvals", ",", "test_stats", ",", "means", ")", "=", "(", "[", "]", ",", "[", "]", ",", "[", "]", ")", "for", "row"...
run any of the group significance tests .
train
false
34,234
def test_serie_precedence_over_global_config(): chart = Line(stroke=False) chart.add('1', s1, stroke=True) chart.add('2', s2) q = chart.render_pyquery() assert (len(q('.serie-0 .line')) == 1) assert (len(q('.serie-1 .line')) == 0) assert (len(q('.serie-0 .dot')) == 5) assert (len(q('.serie-1 .dot')) == 6)
[ "def", "test_serie_precedence_over_global_config", "(", ")", ":", "chart", "=", "Line", "(", "stroke", "=", "False", ")", "chart", ".", "add", "(", "'1'", ",", "s1", ",", "stroke", "=", "True", ")", "chart", ".", "add", "(", "'2'", ",", "s2", ")", "q...
test that per serie configuration overide global configuration .
train
false
34,235
def check_action_access_permission(view_func): def decorate(request, *args, **kwargs): action_id = kwargs.get('action') action = Node.objects.get(id=action_id).get_full_node() Job.objects.can_read_or_exception(request, action.workflow.id) kwargs['action'] = action return view_func(request, *args, **kwargs) return wraps(view_func)(decorate)
[ "def", "check_action_access_permission", "(", "view_func", ")", ":", "def", "decorate", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "action_id", "=", "kwargs", ".", "get", "(", "'action'", ")", "action", "=", "Node", ".", "objects", ...
decorator ensuring that the user has access to the workflow action .
train
false
34,237
def CAN_DELETE(article, user): return _is_staff_for_article(article, user)
[ "def", "CAN_DELETE", "(", "article", ",", "user", ")", ":", "return", "_is_staff_for_article", "(", "article", ",", "user", ")" ]
is user allowed to soft-delete article? .
train
false
34,238
def process_text(text, dic, r, grams): X = lil_matrix((len(text), len(dic))) for (i, l) in enumerate(text): tokens = tokenize(l, grams) indexes = [] for t in tokens: try: indexes += [dic[t]] except KeyError: pass indexes = list(set(indexes)) indexes.sort() for j in indexes: X[(i, j)] = r[j] return csr_matrix(X)
[ "def", "process_text", "(", "text", ",", "dic", ",", "r", ",", "grams", ")", ":", "X", "=", "lil_matrix", "(", "(", "len", "(", "text", ")", ",", "len", "(", "dic", ")", ")", ")", "for", "(", "i", ",", "l", ")", "in", "enumerate", "(", "text"...
return sparse feature matrix .
train
false
34,239
def ynp_zeros(n, nt): return jnyn_zeros(n, nt)[3]
[ "def", "ynp_zeros", "(", "n", ",", "nt", ")", ":", "return", "jnyn_zeros", "(", "n", ",", "nt", ")", "[", "3", "]" ]
compute zeros of integer-order bessel function derivative yn(x) .
train
false
34,240
def make_field_formatter(attr, filters=None): filter_ = None if filters: filter_ = filters.get(attr) def get_field(obj): field = getattr(obj, attr, '') if (field and filter_): field = filter_(field) return field name = _format_field_name(attr) formatter = get_field return (name, formatter)
[ "def", "make_field_formatter", "(", "attr", ",", "filters", "=", "None", ")", ":", "filter_", "=", "None", "if", "filters", ":", "filter_", "=", "filters", ".", "get", "(", "attr", ")", "def", "get_field", "(", "obj", ")", ":", "field", "=", "getattr",...
given an object attribute .
train
false
34,242
def set_permission_cache(user, key, value): from django.core.cache import cache cache_key = get_cache_key(user, key) cache.set(cache_key, value, get_cms_setting('CACHE_DURATIONS')['permissions'], version=get_cache_permission_version())
[ "def", "set_permission_cache", "(", "user", ",", "key", ",", "value", ")", ":", "from", "django", ".", "core", ".", "cache", "import", "cache", "cache_key", "=", "get_cache_key", "(", "user", ",", "key", ")", "cache", ".", "set", "(", "cache_key", ",", ...
helper method for storing values in cache .
train
false
34,243
def getGearPaths(derivation, pitchRadius, teeth, toothProfile): if (teeth < 0): return getGearProfileAnnulus(derivation, pitchRadius, teeth, toothProfile) if (teeth == 0): return [getGearProfileRack(derivation, toothProfile)] return [getGearProfileCylinder(teeth, toothProfile)]
[ "def", "getGearPaths", "(", "derivation", ",", "pitchRadius", ",", "teeth", ",", "toothProfile", ")", ":", "if", "(", "teeth", "<", "0", ")", ":", "return", "getGearProfileAnnulus", "(", "derivation", ",", "pitchRadius", ",", "teeth", ",", "toothProfile", ")...
get gear paths .
train
false
34,245
def set_remote_branch(git_path, module, dest, remote, version, depth): branchref = ('+refs/heads/%s:refs/heads/%s' % (version, version)) branchref += (' +refs/heads/%s:refs/remotes/%s/%s' % (version, remote, version)) cmd = ('%s fetch --depth=%s %s %s' % (git_path, depth, remote, branchref)) (rc, out, err) = module.run_command(cmd, cwd=dest) if (rc != 0): module.fail_json(msg=('Failed to fetch branch from remote: %s' % version), stdout=out, stderr=err, rc=rc)
[ "def", "set_remote_branch", "(", "git_path", ",", "module", ",", "dest", ",", "remote", ",", "version", ",", "depth", ")", ":", "branchref", "=", "(", "'+refs/heads/%s:refs/heads/%s'", "%", "(", "version", ",", "version", ")", ")", "branchref", "+=", "(", ...
set refs for the remote branch version this assumes the branch does not yet exist locally and is therefore also not checked out .
train
false
34,246
def _nameToLabels(name): if (name in ('', '.')): return [''] labels = name.split('.') if (labels[(-1)] != ''): labels.append('') return labels
[ "def", "_nameToLabels", "(", "name", ")", ":", "if", "(", "name", "in", "(", "''", ",", "'.'", ")", ")", ":", "return", "[", "''", "]", "labels", "=", "name", ".", "split", "(", "'.'", ")", "if", "(", "labels", "[", "(", "-", "1", ")", "]", ...
split a domain name into its constituent labels .
train
false
34,247
def plugin_is_enabled(name, runas=None): if ((runas is None) and (not salt.utils.is_windows())): runas = salt.utils.get_user() return (name in list_enabled_plugins(runas))
[ "def", "plugin_is_enabled", "(", "name", ",", "runas", "=", "None", ")", ":", "if", "(", "(", "runas", "is", "None", ")", "and", "(", "not", "salt", ".", "utils", ".", "is_windows", "(", ")", ")", ")", ":", "runas", "=", "salt", ".", "utils", "."...
return whether the plugin is enabled .
train
true
34,248
def ma_rep(coefs, maxn=10): (p, k, k) = coefs.shape phis = np.zeros(((maxn + 1), k, k)) phis[0] = np.eye(k) for i in range(1, (maxn + 1)): for j in range(1, (i + 1)): if (j > p): break phis[i] += np.dot(phis[(i - j)], coefs[(j - 1)]) return phis
[ "def", "ma_rep", "(", "coefs", ",", "maxn", "=", "10", ")", ":", "(", "p", ",", "k", ",", "k", ")", "=", "coefs", ".", "shape", "phis", "=", "np", ".", "zeros", "(", "(", "(", "maxn", "+", "1", ")", ",", "k", ",", "k", ")", ")", "phis", ...
ma representation of var(p) process parameters coefs : ndarray maxn : int number of ma matrices to compute notes var(p) process as .
train
false
34,250
def has_duplicates(l): return (len(set(l)) < len(l))
[ "def", "has_duplicates", "(", "l", ")", ":", "return", "(", "len", "(", "set", "(", "l", ")", ")", "<", "len", "(", "l", ")", ")" ]
returns true if l has any duplicates .
train
false
34,251
def getLineDictionary(line): lineDictionary = {} splitLine = line.split(' DCTB ') for splitLineIndex in xrange(len(splitLine)): word = splitLine[splitLineIndex] if (word != ''): lineDictionary[splitLineIndex] = word return lineDictionary
[ "def", "getLineDictionary", "(", "line", ")", ":", "lineDictionary", "=", "{", "}", "splitLine", "=", "line", ".", "split", "(", "' DCTB '", ")", "for", "splitLineIndex", "in", "xrange", "(", "len", "(", "splitLine", ")", ")", ":", "word", "=", "splitLin...
get the line dictionary .
train
false
34,252
def camel_case_to_spaces(value): return re_camel_case.sub(' \\1', value).strip().lower()
[ "def", "camel_case_to_spaces", "(", "value", ")", ":", "return", "re_camel_case", ".", "sub", "(", "' \\\\1'", ",", "value", ")", ".", "strip", "(", ")", ".", "lower", "(", ")" ]
splits camelcase and converts to lower case .
train
false
34,253
@frappe.whitelist() def get_variant(template, args, variant=None): if isinstance(args, basestring): args = json.loads(args) if (not args): frappe.throw(_(u'Please specify at least one attribute in the Attributes table')) return find_variant(template, args, variant)
[ "@", "frappe", ".", "whitelist", "(", ")", "def", "get_variant", "(", "template", ",", "args", ",", "variant", "=", "None", ")", ":", "if", "isinstance", "(", "args", ",", "basestring", ")", ":", "args", "=", "json", ".", "loads", "(", "args", ")", ...
validates attributes and their values .
train
false
34,255
def convert_template(template): template['annotated_body'] = html4annotation(template['annotated_body'], template['url'], proxy_resources=True)
[ "def", "convert_template", "(", "template", ")", ":", "template", "[", "'annotated_body'", "]", "=", "html4annotation", "(", "template", "[", "'annotated_body'", "]", ",", "template", "[", "'url'", "]", ",", "proxy_resources", "=", "True", ")" ]
converts the template annotated body for being used in the ui .
train
false
34,256
def getInitVersion(pkgroot): path = os.getcwd() initfile = os.path.join(path, pkgroot, '__init__.py') init = open(initfile).read() m = re.search('__version__ = (\\S+)\\n', init) if ((m is None) or (len(m.groups()) != 1)): raise Exception(("Cannot determine __version__ from init file: '%s'!" % initfile)) version = m.group(1).strip('\'"') return version
[ "def", "getInitVersion", "(", "pkgroot", ")", ":", "path", "=", "os", ".", "getcwd", "(", ")", "initfile", "=", "os", ".", "path", ".", "join", "(", "path", ",", "pkgroot", ",", "'__init__.py'", ")", "init", "=", "open", "(", "initfile", ")", ".", ...
return the version string defined in __init__ .
train
false
34,257
def _PadLabels2d(logits_size, labels): pad = (logits_size - tf.shape(labels)[1]) def _PadFn(): return tf.pad(labels, [[0, 0], [0, pad]]) def _SliceFn(): return tf.slice(labels, [0, 0], [(-1), logits_size]) return tf.cond(tf.greater(pad, 0), _PadFn, _SliceFn)
[ "def", "_PadLabels2d", "(", "logits_size", ",", "labels", ")", ":", "pad", "=", "(", "logits_size", "-", "tf", ".", "shape", "(", "labels", ")", "[", "1", "]", ")", "def", "_PadFn", "(", ")", ":", "return", "tf", ".", "pad", "(", "labels", ",", "...
pads or slices the 2nd dimension of 2-d labels to match logits_size .
train
false
34,258
def _get_or_create_user_list(sailthru_client, list_name): sailthru_list_cache = cache.get(SAILTHRU_LIST_CACHE_KEY) is_cache_updated = False if (not sailthru_list_cache): sailthru_list_cache = _get_list_from_email_marketing_provider(sailthru_client) is_cache_updated = True sailthru_list = sailthru_list_cache.get(list_name) if (not sailthru_list): is_created = _create_user_list(sailthru_client, list_name) if is_created: sailthru_list_cache = _get_list_from_email_marketing_provider(sailthru_client) is_cache_updated = True sailthru_list = sailthru_list_cache.get(list_name) if is_cache_updated: cache.set(SAILTHRU_LIST_CACHE_KEY, sailthru_list_cache) return sailthru_list
[ "def", "_get_or_create_user_list", "(", "sailthru_client", ",", "list_name", ")", ":", "sailthru_list_cache", "=", "cache", ".", "get", "(", "SAILTHRU_LIST_CACHE_KEY", ")", "is_cache_updated", "=", "False", "if", "(", "not", "sailthru_list_cache", ")", ":", "sailthr...
get list from sailthru and return if list_name exists else create a new one and return list data for all lists .
train
false
34,259
def tagToKey(tag): keyAttr = tag.get('key') if keyAttr: if (tag.get('keytype') == 'int'): keyAttr = int(keyAttr) return keyAttr return tag.name
[ "def", "tagToKey", "(", "tag", ")", ":", "keyAttr", "=", "tag", ".", "get", "(", "'key'", ")", "if", "keyAttr", ":", "if", "(", "tag", ".", "get", "(", "'keytype'", ")", "==", "'int'", ")", ":", "keyAttr", "=", "int", "(", "keyAttr", ")", "return...
return the name of the tag .
train
false
34,260
def image_to_column(images, filter_shape, stride, padding): (n_images, n_channels, height, width) = images.shape (f_height, f_width) = filter_shape (out_height, out_width) = convoltuion_shape(height, width, (f_height, f_width), stride, padding) images = np.pad(images, ((0, 0), (0, 0), padding, padding), mode='constant') col = np.zeros((n_images, n_channels, f_height, f_width, out_height, out_width)) for y in range(f_height): y_bound = (y + (stride[0] * out_height)) for x in range(f_width): x_bound = (x + (stride[1] * out_width)) col[:, :, y, x, :, :] = images[:, :, y:y_bound:stride[0], x:x_bound:stride[1]] col = col.transpose(0, 4, 5, 1, 2, 3).reshape(((n_images * out_height) * out_width), (-1)) return col
[ "def", "image_to_column", "(", "images", ",", "filter_shape", ",", "stride", ",", "padding", ")", ":", "(", "n_images", ",", "n_channels", ",", "height", ",", "width", ")", "=", "images", ".", "shape", "(", "f_height", ",", "f_width", ")", "=", "filter_s...
rearrange image blocks into columns .
train
false
34,261
def _organize_states_for_delete(base_mapper, states, uowtransaction): for (state, dict_, mapper, connection) in _connections_for_states(base_mapper, uowtransaction, states): mapper.dispatch.before_delete(mapper, connection, state) if (mapper.version_id_col is not None): update_version_id = mapper._get_committed_state_attr_by_column(state, dict_, mapper.version_id_col) else: update_version_id = None (yield (state, dict_, mapper, connection, update_version_id))
[ "def", "_organize_states_for_delete", "(", "base_mapper", ",", "states", ",", "uowtransaction", ")", ":", "for", "(", "state", ",", "dict_", ",", "mapper", ",", "connection", ")", "in", "_connections_for_states", "(", "base_mapper", ",", "uowtransaction", ",", "...
make an initial pass across a set of states for delete .
train
false
34,262
def interlink_static_files(generator): if (generator.settings['STATIC_PATHS'] != []): return filenames = generator.context['filenames'] relpath = relpath_to_site(generator.settings['DEFAULT_LANG'], _MAIN_LANG) for staticfile in _MAIN_STATIC_FILES: if (staticfile.get_relative_source_path() not in filenames): staticfile = copy(staticfile) staticfile.override_url = posixpath.join(relpath, staticfile.url) generator.add_source_path(staticfile)
[ "def", "interlink_static_files", "(", "generator", ")", ":", "if", "(", "generator", ".", "settings", "[", "'STATIC_PATHS'", "]", "!=", "[", "]", ")", ":", "return", "filenames", "=", "generator", ".", "context", "[", "'filenames'", "]", "relpath", "=", "r...
add links to static files in the main site if necessary .
train
false
34,263
def recover_all(lbn, profile='default'): ret = {} config = get_running(profile) try: workers_ = config['worker.{0}.balance_workers'.format(lbn)].split(',') except KeyError: return ret for worker in workers_: curr_state = worker_status(worker, profile) if (curr_state['activation'] != 'ACT'): worker_activate(worker, lbn, profile) if (not curr_state['state'].startswith('OK')): worker_recover(worker, lbn, profile) ret[worker] = worker_status(worker, profile) return ret
[ "def", "recover_all", "(", "lbn", ",", "profile", "=", "'default'", ")", ":", "ret", "=", "{", "}", "config", "=", "get_running", "(", "profile", ")", "try", ":", "workers_", "=", "config", "[", "'worker.{0}.balance_workers'", ".", "format", "(", "lbn", ...
set the all the workers in lbn to recover and activate them if they are not cli examples: .
train
true
34,264
def plot_2D_boundary(plot_range, points, decisionfcn, labels, values=[0]): clist = ['b', 'r', 'g', 'k', 'm', 'y'] x = arange(plot_range[0], plot_range[1], 0.1) y = arange(plot_range[2], plot_range[3], 0.1) (xx, yy) = meshgrid(x, y) (xxx, yyy) = (xx.flatten(), yy.flatten()) zz = array(decisionfcn(xxx, yyy)) zz = zz.reshape(xx.shape) contour(xx, yy, zz, values) for i in range(len(points)): d = decisionfcn(points[i][:, 0], points[i][:, 1]) correct_ndx = (labels[i] == d) incorrect_ndx = (labels[i] != d) plot(points[i][(correct_ndx, 0)], points[i][(correct_ndx, 1)], '*', color=clist[i]) plot(points[i][(incorrect_ndx, 0)], points[i][(incorrect_ndx, 1)], 'o', color=clist[i]) axis('equal')
[ "def", "plot_2D_boundary", "(", "plot_range", ",", "points", ",", "decisionfcn", ",", "labels", ",", "values", "=", "[", "0", "]", ")", ":", "clist", "=", "[", "'b'", ",", "'r'", ",", "'g'", ",", "'k'", ",", "'m'", ",", "'y'", "]", "x", "=", "ara...
plot_range is .
train
false
34,267
def render_genshi_tmpl(tmplstr, context, tmplpath=None): method = context.get('method', 'xml') if ((method == 'text') or (method == 'newtext')): from genshi.template import NewTextTemplate tmpl = NewTextTemplate(tmplstr) elif (method == 'oldtext'): from genshi.template import OldTextTemplate tmpl = OldTextTemplate(tmplstr) else: from genshi.template import MarkupTemplate tmpl = MarkupTemplate(tmplstr) return tmpl.generate(**context).render(method)
[ "def", "render_genshi_tmpl", "(", "tmplstr", ",", "context", ",", "tmplpath", "=", "None", ")", ":", "method", "=", "context", ".", "get", "(", "'method'", ",", "'xml'", ")", "if", "(", "(", "method", "==", "'text'", ")", "or", "(", "method", "==", "...
render a genshi template .
train
true
34,268
def get_net_iface(): internet_ip = get_local_ip() ifname = 'eth0' if (os.name == 'nt'): pass else: import fcntl import struct interfaces = ['eth0', 'eth1', 'eth2', 'wlan0', 'wlan1', 'wifi0', 'ath0', 'ath1', 'ppp0'] for ifname in interfaces: try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) interface_ip = socket.inet_ntoa(fcntl.ioctl(s.fileno(), 35093, struct.pack('256s', ifname[:15]))[20:24]) except IOError: pass else: if (internet_ip == interface_ip): break return ifname
[ "def", "get_net_iface", "(", ")", ":", "internet_ip", "=", "get_local_ip", "(", ")", "ifname", "=", "'eth0'", "if", "(", "os", ".", "name", "==", "'nt'", ")", ":", "pass", "else", ":", "import", "fcntl", "import", "struct", "interfaces", "=", "[", "'et...
this function is very os dependant .
train
false
34,269
def add_ui_controllers(webapp, app): from galaxy.web.base.controller import BaseUIController import galaxy.webapps.reports.controllers controller_dir = galaxy.webapps.reports.controllers.__path__[0] for fname in os.listdir(controller_dir): if ((not fname.startswith('_')) and fname.endswith('.py')): name = fname[:(-3)] module_name = ('galaxy.webapps.reports.controllers.' + name) module = __import__(module_name) for comp in module_name.split('.')[1:]: module = getattr(module, comp) for key in dir(module): T = getattr(module, key) if (isclass(T) and (T is not BaseUIController) and issubclass(T, BaseUIController)): webapp.add_ui_controller(name, T(app))
[ "def", "add_ui_controllers", "(", "webapp", ",", "app", ")", ":", "from", "galaxy", ".", "web", ".", "base", ".", "controller", "import", "BaseUIController", "import", "galaxy", ".", "webapps", ".", "reports", ".", "controllers", "controller_dir", "=", "galaxy...
search for controllers in the galaxy .
train
false
34,271
def qualified_name(obj): if (obj.__name__ == '__builtin__'): return obj.__name__ else: return ('%s.%s' % (obj.__module__, obj.__name__))
[ "def", "qualified_name", "(", "obj", ")", ":", "if", "(", "obj", ".", "__name__", "==", "'__builtin__'", ")", ":", "return", "obj", ".", "__name__", "else", ":", "return", "(", "'%s.%s'", "%", "(", "obj", ".", "__module__", ",", "obj", ".", "__name__",...
return a qualified name for obj .
train
false
34,273
def _parse_openssh_output(lines): for line in lines: if line.startswith('#'): continue try: (hostname, enc, key) = line.split() except ValueError: continue fingerprint = _fingerprint(key) if (not fingerprint): continue (yield {'hostname': hostname, 'key': key, 'enc': enc, 'fingerprint': fingerprint})
[ "def", "_parse_openssh_output", "(", "lines", ")", ":", "for", "line", "in", "lines", ":", "if", "line", ".", "startswith", "(", "'#'", ")", ":", "continue", "try", ":", "(", "hostname", ",", "enc", ",", "key", ")", "=", "line", ".", "split", "(", ...
helper function which parses ssh-keygen -f and ssh-keyscan function output and yield dict with keys information .
train
true
34,274
def delete_logger(logger_name): logging_client = logging.Client() logger = logging_client.logger(logger_name) logger.delete() print 'Deleted all logging entries for {}'.format(logger.name)
[ "def", "delete_logger", "(", "logger_name", ")", ":", "logging_client", "=", "logging", ".", "Client", "(", ")", "logger", "=", "logging_client", ".", "logger", "(", "logger_name", ")", "logger", ".", "delete", "(", ")", "print", "'Deleted all logging entries fo...
deletes a logger and all its entries .
train
false
34,276
def mark_online(user_id, guest=False): now = int(time.time()) expires = ((now + (flaskbb_config['ONLINE_LAST_MINUTES'] * 60)) + 10) if guest: all_users_key = ('online-guests/%d' % (now // 60)) user_key = ('guest-activity/%s' % user_id) else: all_users_key = ('online-users/%d' % (now // 60)) user_key = ('user-activity/%s' % user_id) p = redis_store.pipeline() p.sadd(all_users_key, user_id) p.set(user_key, now) p.expireat(all_users_key, expires) p.expireat(user_key, expires) p.execute()
[ "def", "mark_online", "(", "user_id", ",", "guest", "=", "False", ")", ":", "now", "=", "int", "(", "time", ".", "time", "(", ")", ")", "expires", "=", "(", "(", "now", "+", "(", "flaskbb_config", "[", "'ONLINE_LAST_MINUTES'", "]", "*", "60", ")", ...
marks a user as online .
train
false
34,277
def _create_cbc_cipher(factory, **kwargs): cipher_state = factory._create_base_cipher(kwargs) iv = kwargs.pop('IV', None) IV = kwargs.pop('iv', None) if ((None, None) == (iv, IV)): iv = get_random_bytes(factory.block_size) if (iv is not None): if (IV is not None): raise TypeError("You must either use 'iv' or 'IV', not both") else: iv = IV if kwargs: raise TypeError(('Unknown parameters for CBC: %s' % str(kwargs))) return CbcMode(cipher_state, iv)
[ "def", "_create_cbc_cipher", "(", "factory", ",", "**", "kwargs", ")", ":", "cipher_state", "=", "factory", ".", "_create_base_cipher", "(", "kwargs", ")", "iv", "=", "kwargs", ".", "pop", "(", "'IV'", ",", "None", ")", "IV", "=", "kwargs", ".", "pop", ...
instantiate a cipher object that performs cbc encryption/decryption .
train
false
34,278
def clean_tmp(): import config def file_in_use(fname): in_use = False for proc in psutil.process_iter(): try: open_files = proc.open_files() in_use = (in_use or any([(open_file.path == fname) for open_file in open_files])) if in_use: break except psutil.NoSuchProcess: pass return in_use def listdir_fullpath(d): return [os.path.join(d, f) for f in os.listdir(d)] for path in listdir_fullpath(config.TEMP_DIR): if (not file_in_use(path)): os.remove(path)
[ "def", "clean_tmp", "(", ")", ":", "import", "config", "def", "file_in_use", "(", "fname", ")", ":", "in_use", "=", "False", "for", "proc", "in", "psutil", ".", "process_iter", "(", ")", ":", "try", ":", "open_files", "=", "proc", ".", "open_files", "(...
cleanup the securedrop temp directory .
train
false
34,280
@after.each_scenario def clear_alerts(_scenario): try: with world.browser.get_alert() as alert: alert.dismiss() except NoAlertPresentException: pass
[ "@", "after", ".", "each_scenario", "def", "clear_alerts", "(", "_scenario", ")", ":", "try", ":", "with", "world", ".", "browser", ".", "get_alert", "(", ")", "as", "alert", ":", "alert", ".", "dismiss", "(", ")", "except", "NoAlertPresentException", ":",...
clear any alerts that might still exist .
train
false
34,282
def log_helper(all=False, extra_args=None): revs = [] summaries = [] args = [] if extra_args: args = extra_args output = log(git, pretty=u'oneline', all=all, *args) for line in output.splitlines(): match = REV_LIST_REGEX.match(line) if match: revs.append(match.group(1)) summaries.append(match.group(2)) return (revs, summaries)
[ "def", "log_helper", "(", "all", "=", "False", ",", "extra_args", "=", "None", ")", ":", "revs", "=", "[", "]", "summaries", "=", "[", "]", "args", "=", "[", "]", "if", "extra_args", ":", "args", "=", "extra_args", "output", "=", "log", "(", "git",...
return parallel arrays containing oids and summaries .
train
false
34,283
@permission_required('customercare.ban_account') def moderate(request): return render(request, 'customercare/moderate.html')
[ "@", "permission_required", "(", "'customercare.ban_account'", ")", "def", "moderate", "(", "request", ")", ":", "return", "render", "(", "request", ",", "'customercare/moderate.html'", ")" ]
moderate banned aoa twitter handles .
train
false
34,284
@pytest.fixture def keyparser(): kp = basekeyparser.BaseKeyParser(0, supports_count=True, supports_chains=True) kp.execute = mock.Mock() (yield kp) assert (not kp._ambiguous_timer.isActive())
[ "@", "pytest", ".", "fixture", "def", "keyparser", "(", ")", ":", "kp", "=", "basekeyparser", ".", "BaseKeyParser", "(", "0", ",", "supports_count", "=", "True", ",", "supports_chains", "=", "True", ")", "kp", ".", "execute", "=", "mock", ".", "Mock", ...
fixture providing a basekeyparser supporting count/chains .
train
false
34,285
def escapestr(text, ampm): new_text = re.escape(text) new_text = new_text.replace(re.escape(ampm), ampm) new_text = new_text.replace('\\%', '%') new_text = new_text.replace('\\:', ':') new_text = new_text.replace('\\?', '?') return new_text
[ "def", "escapestr", "(", "text", ",", "ampm", ")", ":", "new_text", "=", "re", ".", "escape", "(", "text", ")", "new_text", "=", "new_text", ".", "replace", "(", "re", ".", "escape", "(", "ampm", ")", ",", "ampm", ")", "new_text", "=", "new_text", ...
escape text to deal with possible locale values that have regex syntax while allowing regex syntax used for comparison .
train
false
34,286
def delete_collection_summary(collection_id): collection_models.CollectionSummaryModel.get(collection_id).delete()
[ "def", "delete_collection_summary", "(", "collection_id", ")", ":", "collection_models", ".", "CollectionSummaryModel", ".", "get", "(", "collection_id", ")", ".", "delete", "(", ")" ]
delete a collection summary model .
train
false
34,287
def find_hook(hook_name, hooks_dir='hooks'): logger.debug('hooks_dir is {}'.format(os.path.abspath(hooks_dir))) if (not os.path.isdir(hooks_dir)): logger.debug('No hooks/ dir in template_dir') return None for hook_file in os.listdir(hooks_dir): if valid_hook(hook_file, hook_name): return os.path.abspath(os.path.join(hooks_dir, hook_file)) return None
[ "def", "find_hook", "(", "hook_name", ",", "hooks_dir", "=", "'hooks'", ")", ":", "logger", ".", "debug", "(", "'hooks_dir is {}'", ".", "format", "(", "os", ".", "path", ".", "abspath", "(", "hooks_dir", ")", ")", ")", "if", "(", "not", "os", ".", "...
return a dict of all hook scripts provided .
train
true
34,288
def cuda_shared_constructor(value, name=None, strict=False, allow_downcast=None, borrow=False, broadcastable=None, target='gpu'): if (target != 'gpu'): raise TypeError('not for gpu') if strict: _value = value else: _value = theano._asarray(value, dtype='float32') if (not isinstance(_value, numpy.ndarray)): raise TypeError('ndarray required') if (_value.dtype.num != CudaNdarrayType.typenum): raise TypeError('float32 ndarray required') if (broadcastable is None): broadcastable = ((False,) * len(value.shape)) type = CudaNdarrayType(broadcastable=broadcastable) print('trying to return?') try: rval = CudaNdarraySharedVariable(type=type, value=_value, name=name, strict=strict) except Exception as e: print('ERROR', e) raise return rval
[ "def", "cuda_shared_constructor", "(", "value", ",", "name", "=", "None", ",", "strict", "=", "False", ",", "allow_downcast", "=", "None", ",", "borrow", "=", "False", ",", "broadcastable", "=", "None", ",", "target", "=", "'gpu'", ")", ":", "if", "(", ...
sharedvariable constructor for cudandarraytype .
train
false
34,290
def smooth_with_function_and_mask(image, function, mask): bleed_over = function(mask.astype(float)) masked_image = np.zeros(image.shape, image.dtype) masked_image[mask] = image[mask] smoothed_image = function(masked_image) output_image = (smoothed_image / (bleed_over + np.finfo(float).eps)) return output_image
[ "def", "smooth_with_function_and_mask", "(", "image", ",", "function", ",", "mask", ")", ":", "bleed_over", "=", "function", "(", "mask", ".", "astype", "(", "float", ")", ")", "masked_image", "=", "np", ".", "zeros", "(", "image", ".", "shape", ",", "im...
smooth an image with a linear function .
train
true
34,291
def eqs_to_matrix(eqs, ring): xs = ring.gens M = zeros(len(eqs), (len(xs) + 1), cls=RawMatrix) for (j, e_j) in enumerate(eqs): for (i, x_i) in enumerate(xs): M[(j, i)] = e_j.coeff(x_i) M[(j, (-1))] = (- e_j.coeff(1)) return M
[ "def", "eqs_to_matrix", "(", "eqs", ",", "ring", ")", ":", "xs", "=", "ring", ".", "gens", "M", "=", "zeros", "(", "len", "(", "eqs", ")", ",", "(", "len", "(", "xs", ")", "+", "1", ")", ",", "cls", "=", "RawMatrix", ")", "for", "(", "j", "...
transform from equations to matrix form .
train
false
34,292
def buildSequencePool(numSequences=10, seqLen=[2, 3, 4], numPatterns=5, numOnBitsPerPattern=3, patternOverlap=0, **kwargs): patterns = getSimplePatterns(numOnBitsPerPattern, numPatterns, patternOverlap) numCols = len(patterns[0]) trainingSequences = [] for _ in xrange(numSequences): sequence = [] length = random.choice(seqLen) for _ in xrange(length): patIdx = random.choice(xrange(numPatterns)) sequence.append(patterns[patIdx]) trainingSequences.append(sequence) if (VERBOSITY >= 3): print '\nTraining sequences' printAllTrainingSequences(trainingSequences) return (numCols, trainingSequences)
[ "def", "buildSequencePool", "(", "numSequences", "=", "10", ",", "seqLen", "=", "[", "2", ",", "3", ",", "4", "]", ",", "numPatterns", "=", "5", ",", "numOnBitsPerPattern", "=", "3", ",", "patternOverlap", "=", "0", ",", "**", "kwargs", ")", ":", "pa...
create a bunch of sequences of various lengths .
train
true
34,293
def read_and_write_file(json_file_path, csv_file_path, column_names): with open(csv_file_path, 'wb+') as fout: csv_file = csv.writer(fout) csv_file.writerow(list(column_names)) with open(json_file_path) as fin: for line in fin: line_contents = json.loads(line) csv_file.writerow(get_row(line_contents, column_names))
[ "def", "read_and_write_file", "(", "json_file_path", ",", "csv_file_path", ",", "column_names", ")", ":", "with", "open", "(", "csv_file_path", ",", "'wb+'", ")", "as", "fout", ":", "csv_file", "=", "csv", ".", "writer", "(", "fout", ")", "csv_file", ".", ...
read in the json dataset file and write it out to a csv file .
train
false
34,294
def _cull(potential, matches, verbose=0): for match in matches: if _samefile(potential[0], match[0]): if verbose: sys.stderr.write(('duplicate: %s (%s)\n' % potential)) return None else: if (not stat.S_ISREG(os.stat(potential[0]).st_mode)): if verbose: sys.stderr.write(('not a regular file: %s (%s)\n' % potential)) elif ((sys.platform != 'win32') and (not os.access(potential[0], os.X_OK))): if verbose: sys.stderr.write(('no executable access: %s (%s)\n' % potential)) else: matches.append(potential) return potential
[ "def", "_cull", "(", "potential", ",", "matches", ",", "verbose", "=", "0", ")", ":", "for", "match", "in", "matches", ":", "if", "_samefile", "(", "potential", "[", "0", "]", ",", "match", "[", "0", "]", ")", ":", "if", "verbose", ":", "sys", "....
cull inappropriate matches .
train
true
34,297
def state_class_str(state): if (state is None): return 'None' else: return ('<%s>' % (state.class_.__name__,))
[ "def", "state_class_str", "(", "state", ")", ":", "if", "(", "state", "is", "None", ")", ":", "return", "'None'", "else", ":", "return", "(", "'<%s>'", "%", "(", "state", ".", "class_", ".", "__name__", ",", ")", ")" ]
return a string describing an instances class via its instancestate .
train
false
34,298
def sharedX(value, name=None, borrow=False, dtype=None): if (dtype is None): dtype = theano.config.floatX return theano.shared(theano._asarray(value, dtype=dtype), name=name, borrow=borrow)
[ "def", "sharedX", "(", "value", ",", "name", "=", "None", ",", "borrow", "=", "False", ",", "dtype", "=", "None", ")", ":", "if", "(", "dtype", "is", "None", ")", ":", "dtype", "=", "theano", ".", "config", ".", "floatX", "return", "theano", ".", ...
transform value into a shared variable of type floatx parameters value : writeme name : writeme borrow : writeme dtype : str .
train
false
34,299
def TR7(rv): def f(rv): if (not (rv.is_Pow and (rv.base.func == cos) and (rv.exp == 2))): return rv return ((1 + cos((2 * rv.base.args[0]))) / 2) return bottom_up(rv, f)
[ "def", "TR7", "(", "rv", ")", ":", "def", "f", "(", "rv", ")", ":", "if", "(", "not", "(", "rv", ".", "is_Pow", "and", "(", "rv", ".", "base", ".", "func", "==", "cos", ")", "and", "(", "rv", ".", "exp", "==", "2", ")", ")", ")", ":", "...
lowering the degree of cos(x)**2 examples .
train
false