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
45,028
@testing.requires_testing_data def test_plot_dipole_amplitudes(): dipoles = read_dipole(dip_fname) dipoles.plot_amplitudes(show=False)
[ "@", "testing", ".", "requires_testing_data", "def", "test_plot_dipole_amplitudes", "(", ")", ":", "dipoles", "=", "read_dipole", "(", "dip_fname", ")", "dipoles", ".", "plot_amplitudes", "(", "show", "=", "False", ")" ]
test plotting dipole amplitudes .
train
false
45,029
def call_xenapi(xenapi, method, *args): return xenapi._session.call_xenapi(method, *args)
[ "def", "call_xenapi", "(", "xenapi", ",", "method", ",", "*", "args", ")", ":", "return", "xenapi", ".", "_session", ".", "call_xenapi", "(", "method", ",", "*", "args", ")" ]
make a call to xapi .
train
false
45,030
@contextfunction def get_pagination_variables(context, objects, limit): variables = {'objects': objects} variables['paginator'] = paginator = Paginator(objects, limit) variables['is_paginated'] = (paginator.num_pages > 1) try: current_page = int((context['request'].GET.get('page') or 0)) except ValueError: current_page = 1 page = paginator.page(min((current_page or 1), paginator.num_pages)) variables['page'] = page variables['page_range'] = _get_page_range(current_page, paginator.num_pages) variables['objects'] = page.object_list return variables
[ "@", "contextfunction", "def", "get_pagination_variables", "(", "context", ",", "objects", ",", "limit", ")", ":", "variables", "=", "{", "'objects'", ":", "objects", "}", "variables", "[", "'paginator'", "]", "=", "paginator", "=", "Paginator", "(", "objects", ",", "limit", ")", "variables", "[", "'is_paginated'", "]", "=", "(", "paginator", ".", "num_pages", ">", "1", ")", "try", ":", "current_page", "=", "int", "(", "(", "context", "[", "'request'", "]", ".", "GET", ".", "get", "(", "'page'", ")", "or", "0", ")", ")", "except", "ValueError", ":", "current_page", "=", "1", "page", "=", "paginator", ".", "page", "(", "min", "(", "(", "current_page", "or", "1", ")", ",", "paginator", ".", "num_pages", ")", ")", "variables", "[", "'page'", "]", "=", "page", "variables", "[", "'page_range'", "]", "=", "_get_page_range", "(", "current_page", ",", "paginator", ".", "num_pages", ")", "variables", "[", "'objects'", "]", "=", "page", ".", "object_list", "return", "variables" ]
get pagination variables for template .
train
false
45,031
def is_regressor(estimator): return (getattr(estimator, '_estimator_type', None) == 'regressor')
[ "def", "is_regressor", "(", "estimator", ")", ":", "return", "(", "getattr", "(", "estimator", ",", "'_estimator_type'", ",", "None", ")", "==", "'regressor'", ")" ]
returns true if the given estimator is a regressor .
train
false
45,032
def get_hg_revision(repopath): try: assert osp.isdir(osp.join(repopath, '.hg')) proc = programs.run_program('hg', ['id', '-nib', repopath]) (output, _err) = proc.communicate() return tuple(output.decode().strip().split(None, 2)) except (subprocess.CalledProcessError, AssertionError, AttributeError): return (None, None, None)
[ "def", "get_hg_revision", "(", "repopath", ")", ":", "try", ":", "assert", "osp", ".", "isdir", "(", "osp", ".", "join", "(", "repopath", ",", "'.hg'", ")", ")", "proc", "=", "programs", ".", "run_program", "(", "'hg'", ",", "[", "'id'", ",", "'-nib'", ",", "repopath", "]", ")", "(", "output", ",", "_err", ")", "=", "proc", ".", "communicate", "(", ")", "return", "tuple", "(", "output", ".", "decode", "(", ")", ".", "strip", "(", ")", ".", "split", "(", "None", ",", "2", ")", ")", "except", "(", "subprocess", ".", "CalledProcessError", ",", "AssertionError", ",", "AttributeError", ")", ":", "return", "(", "None", ",", "None", ",", "None", ")" ]
return mercurial revision for the repository located at repopath result is a tuple .
train
true
45,033
def exe_exists(exe): def is_exe(path): 'Determine if path is an exe.' return (os.path.isfile(path) and os.access(path, os.X_OK)) (path, _) = os.path.split(exe) if path: return is_exe(exe) else: for path in os.environ['PATH'].split(os.pathsep): if is_exe(os.path.join(path, exe)): return True return False
[ "def", "exe_exists", "(", "exe", ")", ":", "def", "is_exe", "(", "path", ")", ":", "return", "(", "os", ".", "path", ".", "isfile", "(", "path", ")", "and", "os", ".", "access", "(", "path", ",", "os", ".", "X_OK", ")", ")", "(", "path", ",", "_", ")", "=", "os", ".", "path", ".", "split", "(", "exe", ")", "if", "path", ":", "return", "is_exe", "(", "exe", ")", "else", ":", "for", "path", "in", "os", ".", "environ", "[", "'PATH'", "]", ".", "split", "(", "os", ".", "pathsep", ")", ":", "if", "is_exe", "(", "os", ".", "path", ".", "join", "(", "path", ",", "exe", ")", ")", ":", "return", "True", "return", "False" ]
determine whether path/name refers to an executable .
train
false
45,035
def summarize_markdown(md): (first_graf, sep, rest) = md.partition('\n\n') return first_graf[:500]
[ "def", "summarize_markdown", "(", "md", ")", ":", "(", "first_graf", ",", "sep", ",", "rest", ")", "=", "md", ".", "partition", "(", "'\\n\\n'", ")", "return", "first_graf", "[", ":", "500", "]" ]
get the first paragraph of some markdown text .
train
false
45,036
def ParseFileEx(file, base_uri, select_default=False, form_parser_class=FormParser, request_class=_request.Request, entitydefs=None, encoding=DEFAULT_ENCODING, _urljoin=urlparse.urljoin, _urlparse=urlparse.urlparse, _urlunparse=urlparse.urlunparse): return _ParseFileEx(file, base_uri, select_default, False, form_parser_class, request_class, entitydefs, False, encoding, _urljoin=_urljoin, _urlparse=_urlparse, _urlunparse=_urlunparse)
[ "def", "ParseFileEx", "(", "file", ",", "base_uri", ",", "select_default", "=", "False", ",", "form_parser_class", "=", "FormParser", ",", "request_class", "=", "_request", ".", "Request", ",", "entitydefs", "=", "None", ",", "encoding", "=", "DEFAULT_ENCODING", ",", "_urljoin", "=", "urlparse", ".", "urljoin", ",", "_urlparse", "=", "urlparse", ".", "urlparse", ",", "_urlunparse", "=", "urlparse", ".", "urlunparse", ")", ":", "return", "_ParseFileEx", "(", "file", ",", "base_uri", ",", "select_default", ",", "False", ",", "form_parser_class", ",", "request_class", ",", "entitydefs", ",", "False", ",", "encoding", ",", "_urljoin", "=", "_urljoin", ",", "_urlparse", "=", "_urlparse", ",", "_urlunparse", "=", "_urlunparse", ")" ]
identical to parsefile .
train
false
45,037
def load_fol(s): statements = [] for (linenum, line) in enumerate(s.splitlines()): line = line.strip() if (line.startswith('#') or (line == '')): continue try: statements.append(Expression.fromstring(line)) except Exception: raise ValueError(('Unable to parse line %s: %s' % (linenum, line))) return statements
[ "def", "load_fol", "(", "s", ")", ":", "statements", "=", "[", "]", "for", "(", "linenum", ",", "line", ")", "in", "enumerate", "(", "s", ".", "splitlines", "(", ")", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "(", "line", ".", "startswith", "(", "'#'", ")", "or", "(", "line", "==", "''", ")", ")", ":", "continue", "try", ":", "statements", ".", "append", "(", "Expression", ".", "fromstring", "(", "line", ")", ")", "except", "Exception", ":", "raise", "ValueError", "(", "(", "'Unable to parse line %s: %s'", "%", "(", "linenum", ",", "line", ")", ")", ")", "return", "statements" ]
temporarily duplicated from nltk .
train
false
45,038
def create_modules_toc_file(master_package, modules, opts, name='modules'): text = format_heading(1, ('%s Modules' % opts.header)) text += '.. toctree::\n' text += (' :maxdepth: %s\n\n' % opts.maxdepth) modules.sort() prev_module = '' for module in modules: if module.startswith((prev_module + '.')): continue prev_module = module text += (' %s\n' % module) write_file(name, text, opts)
[ "def", "create_modules_toc_file", "(", "master_package", ",", "modules", ",", "opts", ",", "name", "=", "'modules'", ")", ":", "text", "=", "format_heading", "(", "1", ",", "(", "'%s Modules'", "%", "opts", ".", "header", ")", ")", "text", "+=", "'.. toctree::\\n'", "text", "+=", "(", "' :maxdepth: %s\\n\\n'", "%", "opts", ".", "maxdepth", ")", "modules", ".", "sort", "(", ")", "prev_module", "=", "''", "for", "module", "in", "modules", ":", "if", "module", ".", "startswith", "(", "(", "prev_module", "+", "'.'", ")", ")", ":", "continue", "prev_module", "=", "module", "text", "+=", "(", "' %s\\n'", "%", "module", ")", "write_file", "(", "name", ",", "text", ",", "opts", ")" ]
create the modules index .
train
true
45,040
def enqueue_task(url, params, countdown): taskqueue.add(queue_name=QUEUE_NAME_EMAILS, url=url, payload=json.dumps(params), countdown=countdown, target=taskqueue.DEFAULT_APP_VERSION)
[ "def", "enqueue_task", "(", "url", ",", "params", ",", "countdown", ")", ":", "taskqueue", ".", "add", "(", "queue_name", "=", "QUEUE_NAME_EMAILS", ",", "url", "=", "url", ",", "payload", "=", "json", ".", "dumps", "(", "params", ")", ",", "countdown", "=", "countdown", ",", "target", "=", "taskqueue", ".", "DEFAULT_APP_VERSION", ")" ]
adds a new task for sending email .
train
false
45,042
def construct_came_from(environ): came_from = environ.get('PATH_INFO') qstr = environ.get('QUERY_STRING', '') if qstr: came_from += ('?' + qstr) return came_from
[ "def", "construct_came_from", "(", "environ", ")", ":", "came_from", "=", "environ", ".", "get", "(", "'PATH_INFO'", ")", "qstr", "=", "environ", ".", "get", "(", "'QUERY_STRING'", ",", "''", ")", "if", "qstr", ":", "came_from", "+=", "(", "'?'", "+", "qstr", ")", "return", "came_from" ]
the url that the user used when the process where interupted for single-sign-on processing .
train
true
45,044
@task.task(ignore_result=True) def get_and_store_likes(user, facebook): try: logger.info('attempting to get and store friends for %s', user.id) stored_likes = facebook._get_and_store_likes(user) logger.info('celery is storing %s likes', len(stored_likes)) return stored_likes except IntegrityError as e: logger.warn('get_and_store_likes failed for %s with error %s', user.id, e)
[ "@", "task", ".", "task", "(", "ignore_result", "=", "True", ")", "def", "get_and_store_likes", "(", "user", ",", "facebook", ")", ":", "try", ":", "logger", ".", "info", "(", "'attempting to get and store friends for %s'", ",", "user", ".", "id", ")", "stored_likes", "=", "facebook", ".", "_get_and_store_likes", "(", "user", ")", "logger", ".", "info", "(", "'celery is storing %s likes'", ",", "len", "(", "stored_likes", ")", ")", "return", "stored_likes", "except", "IntegrityError", "as", "e", ":", "logger", ".", "warn", "(", "'get_and_store_likes failed for %s with error %s'", ",", "user", ".", "id", ",", "e", ")" ]
since facebook is quite slow this version also runs the get on the background inserting again will not cause any errors .
train
false
45,045
@testing.requires_testing_data def test_head(): surf_1 = get_head_surf('sample', subjects_dir=subjects_dir) surf_2 = get_head_surf('sample', 'head', subjects_dir=subjects_dir) assert_true((len(surf_1['rr']) < len(surf_2['rr']))) assert_raises(TypeError, get_head_surf, subject=None, subjects_dir=subjects_dir)
[ "@", "testing", ".", "requires_testing_data", "def", "test_head", "(", ")", ":", "surf_1", "=", "get_head_surf", "(", "'sample'", ",", "subjects_dir", "=", "subjects_dir", ")", "surf_2", "=", "get_head_surf", "(", "'sample'", ",", "'head'", ",", "subjects_dir", "=", "subjects_dir", ")", "assert_true", "(", "(", "len", "(", "surf_1", "[", "'rr'", "]", ")", "<", "len", "(", "surf_2", "[", "'rr'", "]", ")", ")", ")", "assert_raises", "(", "TypeError", ",", "get_head_surf", ",", "subject", "=", "None", ",", "subjects_dir", "=", "subjects_dir", ")" ]
test loading the head surface .
train
false
45,046
def data_sharing_consent_required_at_login(request): if (not enterprise_enabled()): return False return active_provider_enforces_data_sharing(request, EnterpriseCustomer.AT_LOGIN)
[ "def", "data_sharing_consent_required_at_login", "(", "request", ")", ":", "if", "(", "not", "enterprise_enabled", "(", ")", ")", ":", "return", "False", "return", "active_provider_enforces_data_sharing", "(", "request", ",", "EnterpriseCustomer", ".", "AT_LOGIN", ")" ]
determines if data sharing consent is required at a given location .
train
false
45,047
def provider_xrds(request): response = render_to_response('xrds.xml', {'url': get_xrds_url('login', request)}, content_type='text/xml') response['X-XRDS-Location'] = get_xrds_url('xrds', request) return response
[ "def", "provider_xrds", "(", "request", ")", ":", "response", "=", "render_to_response", "(", "'xrds.xml'", ",", "{", "'url'", ":", "get_xrds_url", "(", "'login'", ",", "request", ")", "}", ",", "content_type", "=", "'text/xml'", ")", "response", "[", "'X-XRDS-Location'", "]", "=", "get_xrds_url", "(", "'xrds'", ",", "request", ")", "return", "response" ]
xrds for endpoint discovery .
train
false
45,048
def get_vmdk_detach_config_spec(client_factory, device): config_spec = client_factory.create('ns0:VirtualMachineConfigSpec') device_config_spec = [] virtual_device_config_spec = delete_virtual_disk_spec(client_factory, device) device_config_spec.append(virtual_device_config_spec) config_spec.deviceChange = device_config_spec return config_spec
[ "def", "get_vmdk_detach_config_spec", "(", "client_factory", ",", "device", ")", ":", "config_spec", "=", "client_factory", ".", "create", "(", "'ns0:VirtualMachineConfigSpec'", ")", "device_config_spec", "=", "[", "]", "virtual_device_config_spec", "=", "delete_virtual_disk_spec", "(", "client_factory", ",", "device", ")", "device_config_spec", ".", "append", "(", "virtual_device_config_spec", ")", "config_spec", ".", "deviceChange", "=", "device_config_spec", "return", "config_spec" ]
builds the vmdk detach config spec .
train
false
45,052
def validate_params(module, aws): function_name = module.params['function_name'] if (not re.search('^[\\w\\-:]+$', function_name)): module.fail_json(msg='Function name {0} is invalid. Names must contain only alphanumeric characters and hyphens.'.format(function_name)) if (len(function_name) > 64): module.fail_json(msg='Function name "{0}" exceeds 64 character limit'.format(function_name)) if (module.params['function_version'] == 0): module.params['function_version'] = '$LATEST' else: module.params['function_version'] = str(module.params['function_version']) return
[ "def", "validate_params", "(", "module", ",", "aws", ")", ":", "function_name", "=", "module", ".", "params", "[", "'function_name'", "]", "if", "(", "not", "re", ".", "search", "(", "'^[\\\\w\\\\-:]+$'", ",", "function_name", ")", ")", ":", "module", ".", "fail_json", "(", "msg", "=", "'Function name {0} is invalid. Names must contain only alphanumeric characters and hyphens.'", ".", "format", "(", "function_name", ")", ")", "if", "(", "len", "(", "function_name", ")", ">", "64", ")", ":", "module", ".", "fail_json", "(", "msg", "=", "'Function name \"{0}\" exceeds 64 character limit'", ".", "format", "(", "function_name", ")", ")", "if", "(", "module", ".", "params", "[", "'function_version'", "]", "==", "0", ")", ":", "module", ".", "params", "[", "'function_version'", "]", "=", "'$LATEST'", "else", ":", "module", ".", "params", "[", "'function_version'", "]", "=", "str", "(", "module", ".", "params", "[", "'function_version'", "]", ")", "return" ]
performs basic parameter validation .
train
false
45,053
def preview_parse(scheme_file): parser = make_parser() handler = PreviewHandler() parser.setContentHandler(handler) parser.parse(scheme_file) name_data = (handler.title or '') description_data = (handler.description or '') svg_data = ''.join(handler.thumbnail_data) return (saxutils.unescape(name_data), saxutils.unescape(description_data), saxutils.unescape(svg_data))
[ "def", "preview_parse", "(", "scheme_file", ")", ":", "parser", "=", "make_parser", "(", ")", "handler", "=", "PreviewHandler", "(", ")", "parser", ".", "setContentHandler", "(", "handler", ")", "parser", ".", "parse", "(", "scheme_file", ")", "name_data", "=", "(", "handler", ".", "title", "or", "''", ")", "description_data", "=", "(", "handler", ".", "description", "or", "''", ")", "svg_data", "=", "''", ".", "join", "(", "handler", ".", "thumbnail_data", ")", "return", "(", "saxutils", ".", "unescape", "(", "name_data", ")", ",", "saxutils", ".", "unescape", "(", "description_data", ")", ",", "saxutils", ".", "unescape", "(", "svg_data", ")", ")" ]
return the title .
train
false
45,054
def process_initializer(app, hostname): _set_task_join_will_block(True) platforms.signals.reset(*WORKER_SIGRESET) platforms.signals.ignore(*WORKER_SIGIGNORE) platforms.set_mp_process_title(u'celeryd', hostname=hostname) app.loader.init_worker() app.loader.init_worker_process() logfile = (os.environ.get(u'CELERY_LOG_FILE') or None) if (logfile and (u'%i' in logfile.lower())): app.log.already_setup = False app.log.setup(int((os.environ.get(u'CELERY_LOG_LEVEL', 0) or 0)), logfile, bool(os.environ.get(u'CELERY_LOG_REDIRECT', False)), str(os.environ.get(u'CELERY_LOG_REDIRECT_LEVEL')), hostname=hostname) if os.environ.get(u'FORKED_BY_MULTIPROCESSING'): trace.setup_worker_optimizations(app, hostname) else: app.set_current() set_default_app(app) app.finalize() trace._tasks = app._tasks from celery.app.trace import build_tracer for (name, task) in items(app.tasks): task.__trace__ = build_tracer(name, task, app.loader, hostname, app=app) from celery.worker import state as worker_state worker_state.reset_state() signals.worker_process_init.send(sender=None)
[ "def", "process_initializer", "(", "app", ",", "hostname", ")", ":", "_set_task_join_will_block", "(", "True", ")", "platforms", ".", "signals", ".", "reset", "(", "*", "WORKER_SIGRESET", ")", "platforms", ".", "signals", ".", "ignore", "(", "*", "WORKER_SIGIGNORE", ")", "platforms", ".", "set_mp_process_title", "(", "u'celeryd'", ",", "hostname", "=", "hostname", ")", "app", ".", "loader", ".", "init_worker", "(", ")", "app", ".", "loader", ".", "init_worker_process", "(", ")", "logfile", "=", "(", "os", ".", "environ", ".", "get", "(", "u'CELERY_LOG_FILE'", ")", "or", "None", ")", "if", "(", "logfile", "and", "(", "u'%i'", "in", "logfile", ".", "lower", "(", ")", ")", ")", ":", "app", ".", "log", ".", "already_setup", "=", "False", "app", ".", "log", ".", "setup", "(", "int", "(", "(", "os", ".", "environ", ".", "get", "(", "u'CELERY_LOG_LEVEL'", ",", "0", ")", "or", "0", ")", ")", ",", "logfile", ",", "bool", "(", "os", ".", "environ", ".", "get", "(", "u'CELERY_LOG_REDIRECT'", ",", "False", ")", ")", ",", "str", "(", "os", ".", "environ", ".", "get", "(", "u'CELERY_LOG_REDIRECT_LEVEL'", ")", ")", ",", "hostname", "=", "hostname", ")", "if", "os", ".", "environ", ".", "get", "(", "u'FORKED_BY_MULTIPROCESSING'", ")", ":", "trace", ".", "setup_worker_optimizations", "(", "app", ",", "hostname", ")", "else", ":", "app", ".", "set_current", "(", ")", "set_default_app", "(", "app", ")", "app", ".", "finalize", "(", ")", "trace", ".", "_tasks", "=", "app", ".", "_tasks", "from", "celery", ".", "app", ".", "trace", "import", "build_tracer", "for", "(", "name", ",", "task", ")", "in", "items", "(", "app", ".", "tasks", ")", ":", "task", ".", "__trace__", "=", "build_tracer", "(", "name", ",", "task", ",", "app", ".", "loader", ",", "hostname", ",", "app", "=", "app", ")", "from", "celery", ".", "worker", "import", "state", "as", "worker_state", "worker_state", ".", "reset_state", "(", ")", "signals", ".", "worker_process_init", ".", "send", "(", "sender", "=", "None", ")" ]
initializes the process so it can be used to process tasks .
train
false
45,055
def getDistanceToLineByPath(begin, end, path): distanceToLine = (-987654321.0) for point in path: distanceToLine = max(getDistanceToLine(begin, end, point), distanceToLine) return distanceToLine
[ "def", "getDistanceToLineByPath", "(", "begin", ",", "end", ",", "path", ")", ":", "distanceToLine", "=", "(", "-", "987654321.0", ")", "for", "point", "in", "path", ":", "distanceToLine", "=", "max", "(", "getDistanceToLine", "(", "begin", ",", "end", ",", "point", ")", ",", "distanceToLine", ")", "return", "distanceToLine" ]
get the maximum distance from a path to an infinite line .
train
false
45,057
def _mask_for_bits(i): return ((1 << i) - 1)
[ "def", "_mask_for_bits", "(", "i", ")", ":", "return", "(", "(", "1", "<<", "i", ")", "-", "1", ")" ]
generate a mask to grab i bits from an int value .
train
false
45,058
@when(u'we connect to postgres') def step_db_connect_postgres(context): context.cli.sendline(u'\\connect postgres')
[ "@", "when", "(", "u'we connect to postgres'", ")", "def", "step_db_connect_postgres", "(", "context", ")", ":", "context", ".", "cli", ".", "sendline", "(", "u'\\\\connect postgres'", ")" ]
send connect to database .
train
false
45,060
def binomial_coefficients(n): d = {(0, n): 1, (n, 0): 1} a = 1 for k in range(1, ((n // 2) + 1)): a = ((a * ((n - k) + 1)) // k) d[(k, (n - k))] = d[((n - k), k)] = a return d
[ "def", "binomial_coefficients", "(", "n", ")", ":", "d", "=", "{", "(", "0", ",", "n", ")", ":", "1", ",", "(", "n", ",", "0", ")", ":", "1", "}", "a", "=", "1", "for", "k", "in", "range", "(", "1", ",", "(", "(", "n", "//", "2", ")", "+", "1", ")", ")", ":", "a", "=", "(", "(", "a", "*", "(", "(", "n", "-", "k", ")", "+", "1", ")", ")", "//", "k", ")", "d", "[", "(", "k", ",", "(", "n", "-", "k", ")", ")", "]", "=", "d", "[", "(", "(", "n", "-", "k", ")", ",", "k", ")", "]", "=", "a", "return", "d" ]
return a dictionary containing pairs :math:{ : c_kn} where :math:c_kn are binomial coefficients and :math:n=k1+k2 .
train
false
45,061
def map_from_coords(coords): result = [['SampleID', 'Sample']] for i in range(len(data['coord'][0])): data['map'].append([data['coord'][0][i], 'Sample'])
[ "def", "map_from_coords", "(", "coords", ")", ":", "result", "=", "[", "[", "'SampleID'", ",", "'Sample'", "]", "]", "for", "i", "in", "range", "(", "len", "(", "data", "[", "'coord'", "]", "[", "0", "]", ")", ")", ":", "data", "[", "'map'", "]", ".", "append", "(", "[", "data", "[", "'coord'", "]", "[", "0", "]", "[", "i", "]", ",", "'Sample'", "]", ")" ]
makes pseudo mapping file from coords .
train
false
45,062
def BuildTargetsDict(data): targets = {} for build_file in data['target_build_files']: for target in data[build_file].get('targets', []): target_name = gyp.common.QualifiedTarget(build_file, target['target_name'], target['toolset']) if (target_name in targets): raise GypError(('Duplicate target definitions for ' + target_name)) targets[target_name] = target return targets
[ "def", "BuildTargetsDict", "(", "data", ")", ":", "targets", "=", "{", "}", "for", "build_file", "in", "data", "[", "'target_build_files'", "]", ":", "for", "target", "in", "data", "[", "build_file", "]", ".", "get", "(", "'targets'", ",", "[", "]", ")", ":", "target_name", "=", "gyp", ".", "common", ".", "QualifiedTarget", "(", "build_file", ",", "target", "[", "'target_name'", "]", ",", "target", "[", "'toolset'", "]", ")", "if", "(", "target_name", "in", "targets", ")", ":", "raise", "GypError", "(", "(", "'Duplicate target definitions for '", "+", "target_name", ")", ")", "targets", "[", "target_name", "]", "=", "target", "return", "targets" ]
builds a dict mapping fully-qualified target names to their target dicts .
train
false
45,063
@with_setup(prepare_stdout) def test_simple_behave_as_feature(): Runner(path_to_feature('1st_normal_steps'), verbosity=3, no_color=True).run() assert_stdout_lines('\nFeature: Multiplication # tests/functional/behave_as_features/1st_normal_steps/1st_normal_steps.feature:2\n In order to avoid silly mistakes # tests/functional/behave_as_features/1st_normal_steps/1st_normal_steps.feature:3\n Cashiers must be able to multiplicate numbers :) # tests/functional/behave_as_features/1st_normal_steps/1st_normal_steps.feature:4\n\n Scenario: Regular numbers # tests/functional/behave_as_features/1st_normal_steps/1st_normal_steps.feature:6\n Given I have entered 10 into the calculator # tests/functional/behave_as_features/1st_normal_steps/simple_step_definitions.py:11\n And I have entered 4 into the calculator # tests/functional/behave_as_features/1st_normal_steps/simple_step_definitions.py:11\n When I press multiply # tests/functional/behave_as_features/1st_normal_steps/simple_step_definitions.py:15\n Then the result should be 40 on the screen # tests/functional/behave_as_features/1st_normal_steps/simple_step_definitions.py:19\n\n Scenario: Shorter version of the scenario above # tests/functional/behave_as_features/1st_normal_steps/1st_normal_steps.feature:12\n Given I multiply 10 and 4 into the calculator # tests/functional/behave_as_features/1st_normal_steps/simple_step_definitions.py:23\n Then the result should be 40 on the screen # tests/functional/behave_as_features/1st_normal_steps/simple_step_definitions.py:19\n\n1 feature (1 passed)\n2 scenarios (2 passed)\n6 steps (6 passed)\n')
[ "@", "with_setup", "(", "prepare_stdout", ")", "def", "test_simple_behave_as_feature", "(", ")", ":", "Runner", "(", "path_to_feature", "(", "'1st_normal_steps'", ")", ",", "verbosity", "=", "3", ",", "no_color", "=", "True", ")", ".", "run", "(", ")", "assert_stdout_lines", "(", "'\\nFeature: Multiplication # tests/functional/behave_as_features/1st_normal_steps/1st_normal_steps.feature:2\\n In order to avoid silly mistakes # tests/functional/behave_as_features/1st_normal_steps/1st_normal_steps.feature:3\\n Cashiers must be able to multiplicate numbers :) # tests/functional/behave_as_features/1st_normal_steps/1st_normal_steps.feature:4\\n\\n Scenario: Regular numbers # tests/functional/behave_as_features/1st_normal_steps/1st_normal_steps.feature:6\\n Given I have entered 10 into the calculator # tests/functional/behave_as_features/1st_normal_steps/simple_step_definitions.py:11\\n And I have entered 4 into the calculator # tests/functional/behave_as_features/1st_normal_steps/simple_step_definitions.py:11\\n When I press multiply # tests/functional/behave_as_features/1st_normal_steps/simple_step_definitions.py:15\\n Then the result should be 40 on the screen # tests/functional/behave_as_features/1st_normal_steps/simple_step_definitions.py:19\\n\\n Scenario: Shorter version of the scenario above # tests/functional/behave_as_features/1st_normal_steps/1st_normal_steps.feature:12\\n Given I multiply 10 and 4 into the calculator # tests/functional/behave_as_features/1st_normal_steps/simple_step_definitions.py:23\\n Then the result should be 40 on the screen # tests/functional/behave_as_features/1st_normal_steps/simple_step_definitions.py:19\\n\\n1 feature (1 passed)\\n2 scenarios (2 passed)\\n6 steps (6 passed)\\n'", ")" ]
basic step .
train
false
45,065
def p_cast_expression_1(t): pass
[ "def", "p_cast_expression_1", "(", "t", ")", ":", "pass" ]
cast_expression : unary_expression .
train
false
45,068
def msgexit(msg, code=0): util.xprint(msg) sys.exit(code)
[ "def", "msgexit", "(", "msg", ",", "code", "=", "0", ")", ":", "util", ".", "xprint", "(", "msg", ")", "sys", ".", "exit", "(", "code", ")" ]
print a message and exit .
train
false
45,069
def is_credit_course(course_key): return CreditCourse.is_credit_course(course_key=course_key)
[ "def", "is_credit_course", "(", "course_key", ")", ":", "return", "CreditCourse", ".", "is_credit_course", "(", "course_key", "=", "course_key", ")" ]
check whether the course has been configured for credit .
train
false
45,070
def _coerce_to_dtype(dtype): if is_categorical_dtype(dtype): dtype = CategoricalDtype() elif is_datetime64tz_dtype(dtype): dtype = DatetimeTZDtype(dtype) elif is_period_dtype(dtype): dtype = PeriodDtype(dtype) else: dtype = np.dtype(dtype) return dtype
[ "def", "_coerce_to_dtype", "(", "dtype", ")", ":", "if", "is_categorical_dtype", "(", "dtype", ")", ":", "dtype", "=", "CategoricalDtype", "(", ")", "elif", "is_datetime64tz_dtype", "(", "dtype", ")", ":", "dtype", "=", "DatetimeTZDtype", "(", "dtype", ")", "elif", "is_period_dtype", "(", "dtype", ")", ":", "dtype", "=", "PeriodDtype", "(", "dtype", ")", "else", ":", "dtype", "=", "np", ".", "dtype", "(", "dtype", ")", "return", "dtype" ]
coerce a string / np .
train
false
45,071
def traverse_data(obj, is_numpy=is_numpy, use_numpy=True): is_numpy = (is_numpy and use_numpy) if (is_numpy and all((isinstance(el, np.ndarray) for el in obj))): return [transform_array(el) for el in obj] obj_copy = [] for item in obj: if isinstance(item, (list, tuple)): obj_copy.append(traverse_data(item)) elif isinstance(item, float): if np.isnan(item): item = 'NaN' elif np.isposinf(item): item = 'Infinity' elif np.isneginf(item): item = '-Infinity' obj_copy.append(item) else: obj_copy.append(item) return obj_copy
[ "def", "traverse_data", "(", "obj", ",", "is_numpy", "=", "is_numpy", ",", "use_numpy", "=", "True", ")", ":", "is_numpy", "=", "(", "is_numpy", "and", "use_numpy", ")", "if", "(", "is_numpy", "and", "all", "(", "(", "isinstance", "(", "el", ",", "np", ".", "ndarray", ")", "for", "el", "in", "obj", ")", ")", ")", ":", "return", "[", "transform_array", "(", "el", ")", "for", "el", "in", "obj", "]", "obj_copy", "=", "[", "]", "for", "item", "in", "obj", ":", "if", "isinstance", "(", "item", ",", "(", "list", ",", "tuple", ")", ")", ":", "obj_copy", ".", "append", "(", "traverse_data", "(", "item", ")", ")", "elif", "isinstance", "(", "item", ",", "float", ")", ":", "if", "np", ".", "isnan", "(", "item", ")", ":", "item", "=", "'NaN'", "elif", "np", ".", "isposinf", "(", "item", ")", ":", "item", "=", "'Infinity'", "elif", "np", ".", "isneginf", "(", "item", ")", ":", "item", "=", "'-Infinity'", "obj_copy", ".", "append", "(", "item", ")", "else", ":", "obj_copy", ".", "append", "(", "item", ")", "return", "obj_copy" ]
recursively traverse an object until a flat list is found .
train
false
45,072
def _group_changes(cur, wanted, remove=False): old = set(cur) new = set(wanted) if ((remove and (old != new)) or ((not remove) and (not new.issubset(old)))): return True return False
[ "def", "_group_changes", "(", "cur", ",", "wanted", ",", "remove", "=", "False", ")", ":", "old", "=", "set", "(", "cur", ")", "new", "=", "set", "(", "wanted", ")", "if", "(", "(", "remove", "and", "(", "old", "!=", "new", ")", ")", "or", "(", "(", "not", "remove", ")", "and", "(", "not", "new", ".", "issubset", "(", "old", ")", ")", ")", ")", ":", "return", "True", "return", "False" ]
determine if the groups need to be changed .
train
true
45,073
def to_dense(tensor): if is_sparse(tensor): return tf.sparse_tensor_to_dense(tensor) else: return tensor
[ "def", "to_dense", "(", "tensor", ")", ":", "if", "is_sparse", "(", "tensor", ")", ":", "return", "tf", ".", "sparse_tensor_to_dense", "(", "tensor", ")", "else", ":", "return", "tensor" ]
converts a sparse tensor into a dense tensor and returns it .
train
false
45,076
@register.inclusion_tag('inclusion.html') def inclusion_unlimited_args_kwargs(one, two='hi', *args, **kwargs): sorted_kwarg = sorted(six.iteritems(kwargs), key=operator.itemgetter(0)) return {'result': ('inclusion_unlimited_args_kwargs - Expected result: %s / %s' % (', '.join([six.text_type(arg) for arg in ([one, two] + list(args))]), ', '.join([('%s=%s' % (k, v)) for (k, v) in sorted_kwarg])))}
[ "@", "register", ".", "inclusion_tag", "(", "'inclusion.html'", ")", "def", "inclusion_unlimited_args_kwargs", "(", "one", ",", "two", "=", "'hi'", ",", "*", "args", ",", "**", "kwargs", ")", ":", "sorted_kwarg", "=", "sorted", "(", "six", ".", "iteritems", "(", "kwargs", ")", ",", "key", "=", "operator", ".", "itemgetter", "(", "0", ")", ")", "return", "{", "'result'", ":", "(", "'inclusion_unlimited_args_kwargs - Expected result: %s / %s'", "%", "(", "', '", ".", "join", "(", "[", "six", ".", "text_type", "(", "arg", ")", "for", "arg", "in", "(", "[", "one", ",", "two", "]", "+", "list", "(", "args", ")", ")", "]", ")", ",", "', '", ".", "join", "(", "[", "(", "'%s=%s'", "%", "(", "k", ",", "v", ")", ")", "for", "(", "k", ",", "v", ")", "in", "sorted_kwarg", "]", ")", ")", ")", "}" ]
expected inclusion_unlimited_args_kwargs __doc__ .
train
false
45,077
def get_security_groups(conn, vm_): return config.get_cloud_config_value('securitygroup', vm_, __opts__, default=['default'])
[ "def", "get_security_groups", "(", "conn", ",", "vm_", ")", ":", "return", "config", ".", "get_cloud_config_value", "(", "'securitygroup'", ",", "vm_", ",", "__opts__", ",", "default", "=", "[", "'default'", "]", ")" ]
return a list of security groups to use .
train
false
45,078
def fixed_ip_bulk_create(context, ips): return IMPL.fixed_ip_bulk_create(context, ips)
[ "def", "fixed_ip_bulk_create", "(", "context", ",", "ips", ")", ":", "return", "IMPL", ".", "fixed_ip_bulk_create", "(", "context", ",", "ips", ")" ]
create a lot of fixed ips from the values dictionary .
train
false
45,079
@pytest.mark.parametrize('fast_reader', [True, False, {'use_fast_converter': False}, {'use_fast_converter': True}, 'force']) def test_convert_overflow(fast_reader): expected_kind = ('S', 'U') dat = ascii.read(['a', ('1' * 10000)], format='basic', fast_reader=fast_reader, guess=False) assert (dat['a'].dtype.kind in expected_kind)
[ "@", "pytest", ".", "mark", ".", "parametrize", "(", "'fast_reader'", ",", "[", "True", ",", "False", ",", "{", "'use_fast_converter'", ":", "False", "}", ",", "{", "'use_fast_converter'", ":", "True", "}", ",", "'force'", "]", ")", "def", "test_convert_overflow", "(", "fast_reader", ")", ":", "expected_kind", "=", "(", "'S'", ",", "'U'", ")", "dat", "=", "ascii", ".", "read", "(", "[", "'a'", ",", "(", "'1'", "*", "10000", ")", "]", ",", "format", "=", "'basic'", ",", "fast_reader", "=", "fast_reader", ",", "guess", "=", "False", ")", "assert", "(", "dat", "[", "'a'", "]", ".", "dtype", ".", "kind", "in", "expected_kind", ")" ]
test reading an extremely large integer .
train
false
45,080
@not_implemented_for('directed') def local_efficiency(G): return (sum((global_efficiency(nx.ego_graph(G, v)) for v in G)) / len(G))
[ "@", "not_implemented_for", "(", "'directed'", ")", "def", "local_efficiency", "(", "G", ")", ":", "return", "(", "sum", "(", "(", "global_efficiency", "(", "nx", ".", "ego_graph", "(", "G", ",", "v", ")", ")", "for", "v", "in", "G", ")", ")", "/", "len", "(", "G", ")", ")" ]
returns the average local efficiency of the graph .
train
false
45,081
def groupstatsbin(factors, values): n = len(factors) (ix, rind) = np.unique(factors, return_inverse=1) gcount = np.bincount(rind) gmean = (np.bincount(rind, weights=values) / (1.0 * gcount)) meanarr = gmean[rind] withinvar = (np.bincount(rind, weights=((values - meanarr) ** 2)) / (1.0 * gcount)) withinvararr = withinvar[rind] return (gcount, gmean, meanarr, withinvar, withinvararr)
[ "def", "groupstatsbin", "(", "factors", ",", "values", ")", ":", "n", "=", "len", "(", "factors", ")", "(", "ix", ",", "rind", ")", "=", "np", ".", "unique", "(", "factors", ",", "return_inverse", "=", "1", ")", "gcount", "=", "np", ".", "bincount", "(", "rind", ")", "gmean", "=", "(", "np", ".", "bincount", "(", "rind", ",", "weights", "=", "values", ")", "/", "(", "1.0", "*", "gcount", ")", ")", "meanarr", "=", "gmean", "[", "rind", "]", "withinvar", "=", "(", "np", ".", "bincount", "(", "rind", ",", "weights", "=", "(", "(", "values", "-", "meanarr", ")", "**", "2", ")", ")", "/", "(", "1.0", "*", "gcount", ")", ")", "withinvararr", "=", "withinvar", "[", "rind", "]", "return", "(", "gcount", ",", "gmean", ",", "meanarr", ",", "withinvar", ",", "withinvararr", ")" ]
uses np .
train
false
45,082
def __parse_roman(value): if (not __romanNumeralPattern.search(value)): raise ValueError(('Invalid Roman numeral: %s' % value)) result = 0 index = 0 for (num, integer) in __romanNumeralMap: while (value[index:(index + len(num))] == num): result += integer index += len(num) return result
[ "def", "__parse_roman", "(", "value", ")", ":", "if", "(", "not", "__romanNumeralPattern", ".", "search", "(", "value", ")", ")", ":", "raise", "ValueError", "(", "(", "'Invalid Roman numeral: %s'", "%", "value", ")", ")", "result", "=", "0", "index", "=", "0", "for", "(", "num", ",", "integer", ")", "in", "__romanNumeralMap", ":", "while", "(", "value", "[", "index", ":", "(", "index", "+", "len", "(", "num", ")", ")", "]", "==", "num", ")", ":", "result", "+=", "integer", "index", "+=", "len", "(", "num", ")", "return", "result" ]
convert roman numeral to integer .
train
false
45,083
def update_tr_radius(Delta, actual_reduction, predicted_reduction, step_norm, bound_hit): if (predicted_reduction > 0): ratio = (actual_reduction / predicted_reduction) else: ratio = 0 if (ratio < 0.25): Delta = (0.25 * step_norm) elif ((ratio > 0.75) and bound_hit): Delta *= 2.0 return (Delta, ratio)
[ "def", "update_tr_radius", "(", "Delta", ",", "actual_reduction", ",", "predicted_reduction", ",", "step_norm", ",", "bound_hit", ")", ":", "if", "(", "predicted_reduction", ">", "0", ")", ":", "ratio", "=", "(", "actual_reduction", "/", "predicted_reduction", ")", "else", ":", "ratio", "=", "0", "if", "(", "ratio", "<", "0.25", ")", ":", "Delta", "=", "(", "0.25", "*", "step_norm", ")", "elif", "(", "(", "ratio", ">", "0.75", ")", "and", "bound_hit", ")", ":", "Delta", "*=", "2.0", "return", "(", "Delta", ",", "ratio", ")" ]
update the radius of a trust region based on the cost reduction .
train
false
45,084
def ensemble_preds(dataset, nb_teachers, stdnt_data): result_shape = (nb_teachers, len(stdnt_data), FLAGS.nb_labels) result = np.zeros(result_shape, dtype=np.float32) for teacher_id in xrange(nb_teachers): if FLAGS.deeper: ckpt_path = ((((((((FLAGS.teachers_dir + '/') + str(dataset)) + '_') + str(nb_teachers)) + '_teachers_') + str(teacher_id)) + '_deep.ckpt-') + str((FLAGS.teachers_max_steps - 1))) else: ckpt_path = ((((((((FLAGS.teachers_dir + '/') + str(dataset)) + '_') + str(nb_teachers)) + '_teachers_') + str(teacher_id)) + '.ckpt-') + str((FLAGS.teachers_max_steps - 1))) result[teacher_id] = deep_cnn.softmax_preds(stdnt_data, ckpt_path) print((('Computed Teacher ' + str(teacher_id)) + ' softmax predictions')) return result
[ "def", "ensemble_preds", "(", "dataset", ",", "nb_teachers", ",", "stdnt_data", ")", ":", "result_shape", "=", "(", "nb_teachers", ",", "len", "(", "stdnt_data", ")", ",", "FLAGS", ".", "nb_labels", ")", "result", "=", "np", ".", "zeros", "(", "result_shape", ",", "dtype", "=", "np", ".", "float32", ")", "for", "teacher_id", "in", "xrange", "(", "nb_teachers", ")", ":", "if", "FLAGS", ".", "deeper", ":", "ckpt_path", "=", "(", "(", "(", "(", "(", "(", "(", "(", "FLAGS", ".", "teachers_dir", "+", "'/'", ")", "+", "str", "(", "dataset", ")", ")", "+", "'_'", ")", "+", "str", "(", "nb_teachers", ")", ")", "+", "'_teachers_'", ")", "+", "str", "(", "teacher_id", ")", ")", "+", "'_deep.ckpt-'", ")", "+", "str", "(", "(", "FLAGS", ".", "teachers_max_steps", "-", "1", ")", ")", ")", "else", ":", "ckpt_path", "=", "(", "(", "(", "(", "(", "(", "(", "(", "FLAGS", ".", "teachers_dir", "+", "'/'", ")", "+", "str", "(", "dataset", ")", ")", "+", "'_'", ")", "+", "str", "(", "nb_teachers", ")", ")", "+", "'_teachers_'", ")", "+", "str", "(", "teacher_id", ")", ")", "+", "'.ckpt-'", ")", "+", "str", "(", "(", "FLAGS", ".", "teachers_max_steps", "-", "1", ")", ")", ")", "result", "[", "teacher_id", "]", "=", "deep_cnn", ".", "softmax_preds", "(", "stdnt_data", ",", "ckpt_path", ")", "print", "(", "(", "(", "'Computed Teacher '", "+", "str", "(", "teacher_id", ")", ")", "+", "' softmax predictions'", ")", ")", "return", "result" ]
given a dataset .
train
false
45,085
def maybe_iso8601(dt): if (not dt): return if isinstance(dt, datetime): return dt return parse_iso8601(dt)
[ "def", "maybe_iso8601", "(", "dt", ")", ":", "if", "(", "not", "dt", ")", ":", "return", "if", "isinstance", "(", "dt", ",", "datetime", ")", ":", "return", "dt", "return", "parse_iso8601", "(", "dt", ")" ]
either datetime | str -> datetime or none -> none .
train
false
45,087
def process_parallel(callbacks, input, *a, **kw): dfds = [defer.succeed(input).addCallback(x, *a, **kw) for x in callbacks] d = defer.DeferredList(dfds, fireOnOneErrback=1, consumeErrors=1) d.addCallbacks((lambda r: [x[1] for x in r]), (lambda f: f.value.subFailure)) return d
[ "def", "process_parallel", "(", "callbacks", ",", "input", ",", "*", "a", ",", "**", "kw", ")", ":", "dfds", "=", "[", "defer", ".", "succeed", "(", "input", ")", ".", "addCallback", "(", "x", ",", "*", "a", ",", "**", "kw", ")", "for", "x", "in", "callbacks", "]", "d", "=", "defer", ".", "DeferredList", "(", "dfds", ",", "fireOnOneErrback", "=", "1", ",", "consumeErrors", "=", "1", ")", "d", ".", "addCallbacks", "(", "(", "lambda", "r", ":", "[", "x", "[", "1", "]", "for", "x", "in", "r", "]", ")", ",", "(", "lambda", "f", ":", "f", ".", "value", ".", "subFailure", ")", ")", "return", "d" ]
return a deferred with the output of all successful calls to the given callbacks .
train
false
45,088
def datetime_format_to_js_date_format(format): format = format.split()[0] return datetime_format_to_js_datetime_format(format)
[ "def", "datetime_format_to_js_date_format", "(", "format", ")", ":", "format", "=", "format", ".", "split", "(", ")", "[", "0", "]", "return", "datetime_format_to_js_datetime_format", "(", "format", ")" ]
convert a python datetime format to a date format suitable for use with the js date picker we use .
train
false
45,089
def rollback(): connection._rollback() set_clean()
[ "def", "rollback", "(", ")", ":", "connection", ".", "_rollback", "(", ")", "set_clean", "(", ")" ]
to rollback the last committed configuration changes usage: .
train
false
45,090
def jbig2Decode(stream, parameters): decodedStream = '' return ((-1), 'Jbig2Decode not supported yet')
[ "def", "jbig2Decode", "(", "stream", ",", "parameters", ")", ":", "decodedStream", "=", "''", "return", "(", "(", "-", "1", ")", ",", "'Jbig2Decode not supported yet'", ")" ]
method to decode streams using the jbig2 standard .
train
false
45,091
@handle_response_format @treeio_login_required def set_view(request, set_id, response_format='html'): changeset = get_object_or_404(ChangeSet, pk=set_id) if ((not request.user.profile.has_permission(changeset.object)) and (not request.user.profile.is_admin('treeio.changes'))): return user_denied(request, "You don't have access to this Change Set.", response_format=response_format) context = _get_default_context(request) context.update({'changeset': changeset}) return render_to_response('changes/set_view', context, context_instance=RequestContext(request), response_format=response_format)
[ "@", "handle_response_format", "@", "treeio_login_required", "def", "set_view", "(", "request", ",", "set_id", ",", "response_format", "=", "'html'", ")", ":", "changeset", "=", "get_object_or_404", "(", "ChangeSet", ",", "pk", "=", "set_id", ")", "if", "(", "(", "not", "request", ".", "user", ".", "profile", ".", "has_permission", "(", "changeset", ".", "object", ")", ")", "and", "(", "not", "request", ".", "user", ".", "profile", ".", "is_admin", "(", "'treeio.changes'", ")", ")", ")", ":", "return", "user_denied", "(", "request", ",", "\"You don't have access to this Change Set.\"", ",", "response_format", "=", "response_format", ")", "context", "=", "_get_default_context", "(", "request", ")", "context", ".", "update", "(", "{", "'changeset'", ":", "changeset", "}", ")", "return", "render_to_response", "(", "'changes/set_view'", ",", "context", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ",", "response_format", "=", "response_format", ")" ]
changeset view .
train
false
45,092
def _integrate_plugins(): from airflow.plugins_manager import hooks_modules for hooks_module in hooks_modules: sys.modules[hooks_module.__name__] = hooks_module globals()[hooks_module._name] = hooks_module if (not _os.environ.get('AIRFLOW_USE_NEW_IMPORTS', False)): from zope.deprecation import deprecated as _deprecated for _hook in hooks_module._objects: hook_name = _hook.__name__ globals()[hook_name] = _hook _deprecated(hook_name, "Importing plugin hook '{i}' directly from 'airflow.hooks' has been deprecated. Please import from 'airflow.hooks.[plugin_module]' instead. Support for direct imports will be dropped entirely in Airflow 2.0.".format(i=hook_name))
[ "def", "_integrate_plugins", "(", ")", ":", "from", "airflow", ".", "plugins_manager", "import", "hooks_modules", "for", "hooks_module", "in", "hooks_modules", ":", "sys", ".", "modules", "[", "hooks_module", ".", "__name__", "]", "=", "hooks_module", "globals", "(", ")", "[", "hooks_module", ".", "_name", "]", "=", "hooks_module", "if", "(", "not", "_os", ".", "environ", ".", "get", "(", "'AIRFLOW_USE_NEW_IMPORTS'", ",", "False", ")", ")", ":", "from", "zope", ".", "deprecation", "import", "deprecated", "as", "_deprecated", "for", "_hook", "in", "hooks_module", ".", "_objects", ":", "hook_name", "=", "_hook", ".", "__name__", "globals", "(", ")", "[", "hook_name", "]", "=", "_hook", "_deprecated", "(", "hook_name", ",", "\"Importing plugin hook '{i}' directly from 'airflow.hooks' has been deprecated. Please import from 'airflow.hooks.[plugin_module]' instead. Support for direct imports will be dropped entirely in Airflow 2.0.\"", ".", "format", "(", "i", "=", "hook_name", ")", ")" ]
integrate plugins to the context .
train
false
45,093
def CreateWindowsRegistryExecutablePathsDetector(vars_map=None): return core.Detector(extractors=[RunDllExtractor(), ExecutableExtractor()], post_processors=[EnvVarsPostProcessor((vars_map or {}))])
[ "def", "CreateWindowsRegistryExecutablePathsDetector", "(", "vars_map", "=", "None", ")", ":", "return", "core", ".", "Detector", "(", "extractors", "=", "[", "RunDllExtractor", "(", ")", ",", "ExecutableExtractor", "(", ")", "]", ",", "post_processors", "=", "[", "EnvVarsPostProcessor", "(", "(", "vars_map", "or", "{", "}", ")", ")", "]", ")" ]
creates windows paths detector .
train
true
45,094
def save_password(password, port): password_file = abspath(('parameters_%i.py' % port)) if (password == '<random>'): chars = (string.letters + string.digits) password = ''.join([random.choice(chars) for _ in range(8)]) cpassword = CRYPT()(password)[0] print('******************* IMPORTANT!!! ************************') print(('your admin password is "%s"' % password)) print('*********************************************************') elif (password == '<recycle>'): if exists(password_file): return else: password = '' elif password.startswith('<pam_user:'): cpassword = password[1:(-1)] else: cpassword = CRYPT()(password)[0] fp = open(password_file, 'w') if password: fp.write(('password="%s"\n' % cpassword)) else: fp.write('password=None\n') fp.close()
[ "def", "save_password", "(", "password", ",", "port", ")", ":", "password_file", "=", "abspath", "(", "(", "'parameters_%i.py'", "%", "port", ")", ")", "if", "(", "password", "==", "'<random>'", ")", ":", "chars", "=", "(", "string", ".", "letters", "+", "string", ".", "digits", ")", "password", "=", "''", ".", "join", "(", "[", "random", ".", "choice", "(", "chars", ")", "for", "_", "in", "range", "(", "8", ")", "]", ")", "cpassword", "=", "CRYPT", "(", ")", "(", "password", ")", "[", "0", "]", "print", "(", "'******************* IMPORTANT!!! ************************'", ")", "print", "(", "(", "'your admin password is \"%s\"'", "%", "password", ")", ")", "print", "(", "'*********************************************************'", ")", "elif", "(", "password", "==", "'<recycle>'", ")", ":", "if", "exists", "(", "password_file", ")", ":", "return", "else", ":", "password", "=", "''", "elif", "password", ".", "startswith", "(", "'<pam_user:'", ")", ":", "cpassword", "=", "password", "[", "1", ":", "(", "-", "1", ")", "]", "else", ":", "cpassword", "=", "CRYPT", "(", ")", "(", "password", ")", "[", "0", "]", "fp", "=", "open", "(", "password_file", ",", "'w'", ")", "if", "password", ":", "fp", ".", "write", "(", "(", "'password=\"%s\"\\n'", "%", "cpassword", ")", ")", "else", ":", "fp", ".", "write", "(", "'password=None\\n'", ")", "fp", ".", "close", "(", ")" ]
used by main() to save the password in the parameters_port .
train
false
45,095
def label_remove_hosts(id, hosts): host_objs = models.Host.smart_get_bulk(hosts) models.Label.smart_get(id).host_set.remove(*host_objs)
[ "def", "label_remove_hosts", "(", "id", ",", "hosts", ")", ":", "host_objs", "=", "models", ".", "Host", ".", "smart_get_bulk", "(", "hosts", ")", "models", ".", "Label", ".", "smart_get", "(", "id", ")", ".", "host_set", ".", "remove", "(", "*", "host_objs", ")" ]
remove hosts from label .
train
false
45,096
def ensure_version(min_version): if (type(min_version) == str): min_version = python_version(min_version) elif (type(min_version) == int): pass else: raise TypeError, ('version %s is not a string or an integer' % min_version) if (_sys.hexversion < min_version): raise RuntimeError, ('This program requires Python version "%s" or better, but the current Python version is "%s".' % (python_version_string(min_version), python_version_string(sys.hexversion)))
[ "def", "ensure_version", "(", "min_version", ")", ":", "if", "(", "type", "(", "min_version", ")", "==", "str", ")", ":", "min_version", "=", "python_version", "(", "min_version", ")", "elif", "(", "type", "(", "min_version", ")", "==", "int", ")", ":", "pass", "else", ":", "raise", "TypeError", ",", "(", "'version %s is not a string or an integer'", "%", "min_version", ")", "if", "(", "_sys", ".", "hexversion", "<", "min_version", ")", ":", "raise", "RuntimeError", ",", "(", "'This program requires Python version \"%s\" or better, but the current Python version is \"%s\".'", "%", "(", "python_version_string", "(", "min_version", ")", ",", "python_version_string", "(", "sys", ".", "hexversion", ")", ")", ")" ]
raise a runtimeerror if the current python version isnt at least min_version .
train
false
45,098
@pytest.fixture def requests_mock(): with _requests_mock.mock() as m: (yield m)
[ "@", "pytest", ".", "fixture", "def", "requests_mock", "(", ")", ":", "with", "_requests_mock", ".", "mock", "(", ")", "as", "m", ":", "(", "yield", "m", ")" ]
fixture to provide a requests mocker .
train
false
45,099
@with_default() def _case_insensitive_lookup(entries, key, default=UNDEFINED): if (entries is not None): if isinstance(entries, dict): for (k, v) in list(entries.items()): if (k.lower() == key.lower()): return v else: for entry in entries: if (entry.lower() == key.lower()): return entry raise ValueError(("key '%s' doesn't exist in dict: %s" % (key, entries)))
[ "@", "with_default", "(", ")", "def", "_case_insensitive_lookup", "(", "entries", ",", "key", ",", "default", "=", "UNDEFINED", ")", ":", "if", "(", "entries", "is", "not", "None", ")", ":", "if", "isinstance", "(", "entries", ",", "dict", ")", ":", "for", "(", "k", ",", "v", ")", "in", "list", "(", "entries", ".", "items", "(", ")", ")", ":", "if", "(", "k", ".", "lower", "(", ")", "==", "key", ".", "lower", "(", ")", ")", ":", "return", "v", "else", ":", "for", "entry", "in", "entries", ":", "if", "(", "entry", ".", "lower", "(", ")", "==", "key", ".", "lower", "(", ")", ")", ":", "return", "entry", "raise", "ValueError", "(", "(", "\"key '%s' doesn't exist in dict: %s\"", "%", "(", "key", ",", "entries", ")", ")", ")" ]
makes a case insensitive lookup within a list or dictionary .
train
false
45,101
def set_max_workspace_size(size): global _max_workspace_size _max_workspace_size = size
[ "def", "set_max_workspace_size", "(", "size", ")", ":", "global", "_max_workspace_size", "_max_workspace_size", "=", "size" ]
sets the workspace size for cudnn .
train
false
45,102
def tempredirect(url): return redirect(url, '307 Temporary Redirect')
[ "def", "tempredirect", "(", "url", ")", ":", "return", "redirect", "(", "url", ",", "'307 Temporary Redirect'", ")" ]
a 307 temporary redirect redirect .
train
false
45,105
def fileContents(fn): return open(fn, 'rb').read()
[ "def", "fileContents", "(", "fn", ")", ":", "return", "open", "(", "fn", ",", "'rb'", ")", ".", "read", "(", ")" ]
return the contents of the named file .
train
false
45,106
def monitorhosts(hosts=5, sched='cfs'): mytopo = SingleSwitchTopo(hosts) cpu = (0.5 / hosts) myhost = custom(CPULimitedHost, cpu=cpu, sched=sched) net = Mininet(topo=mytopo, host=myhost) net.start() popens = {} last = net.hosts[(-1)] for host in net.hosts: popens[host] = host.popen(('ping -c5 %s' % last.IP())) last = host for (host, line) in pmonitor(popens): if host: info(('<%s>: %s' % (host.name, line))) net.stop()
[ "def", "monitorhosts", "(", "hosts", "=", "5", ",", "sched", "=", "'cfs'", ")", ":", "mytopo", "=", "SingleSwitchTopo", "(", "hosts", ")", "cpu", "=", "(", "0.5", "/", "hosts", ")", "myhost", "=", "custom", "(", "CPULimitedHost", ",", "cpu", "=", "cpu", ",", "sched", "=", "sched", ")", "net", "=", "Mininet", "(", "topo", "=", "mytopo", ",", "host", "=", "myhost", ")", "net", ".", "start", "(", ")", "popens", "=", "{", "}", "last", "=", "net", ".", "hosts", "[", "(", "-", "1", ")", "]", "for", "host", "in", "net", ".", "hosts", ":", "popens", "[", "host", "]", "=", "host", ".", "popen", "(", "(", "'ping -c5 %s'", "%", "last", ".", "IP", "(", ")", ")", ")", "last", "=", "host", "for", "(", "host", ",", "line", ")", "in", "pmonitor", "(", "popens", ")", ":", "if", "host", ":", "info", "(", "(", "'<%s>: %s'", "%", "(", "host", ".", "name", ",", "line", ")", ")", ")", "net", ".", "stop", "(", ")" ]
start a bunch of pings and monitor them using popen .
train
false
45,108
def secs_from_days(_seconds, _num): return (_seconds * _num)
[ "def", "secs_from_days", "(", "_seconds", ",", "_num", ")", ":", "return", "(", "_seconds", "*", "_num", ")" ]
returns the number of seconds that are in the given number of days .
train
false
45,109
def _validate_file_roots(file_roots): if (not isinstance(file_roots, dict)): log.warning('The file_roots parameter is not properly formatted, using defaults') return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])} for (saltenv, dirs) in six.iteritems(file_roots): normalized_saltenv = six.text_type(saltenv) if (normalized_saltenv != saltenv): file_roots[normalized_saltenv] = file_roots.pop(saltenv) if (not isinstance(dirs, (list, tuple))): file_roots[normalized_saltenv] = [] file_roots[normalized_saltenv] = _expand_glob_path(file_roots[normalized_saltenv]) return file_roots
[ "def", "_validate_file_roots", "(", "file_roots", ")", ":", "if", "(", "not", "isinstance", "(", "file_roots", ",", "dict", ")", ")", ":", "log", ".", "warning", "(", "'The file_roots parameter is not properly formatted, using defaults'", ")", "return", "{", "'base'", ":", "_expand_glob_path", "(", "[", "salt", ".", "syspaths", ".", "BASE_FILE_ROOTS_DIR", "]", ")", "}", "for", "(", "saltenv", ",", "dirs", ")", "in", "six", ".", "iteritems", "(", "file_roots", ")", ":", "normalized_saltenv", "=", "six", ".", "text_type", "(", "saltenv", ")", "if", "(", "normalized_saltenv", "!=", "saltenv", ")", ":", "file_roots", "[", "normalized_saltenv", "]", "=", "file_roots", ".", "pop", "(", "saltenv", ")", "if", "(", "not", "isinstance", "(", "dirs", ",", "(", "list", ",", "tuple", ")", ")", ")", ":", "file_roots", "[", "normalized_saltenv", "]", "=", "[", "]", "file_roots", "[", "normalized_saltenv", "]", "=", "_expand_glob_path", "(", "file_roots", "[", "normalized_saltenv", "]", ")", "return", "file_roots" ]
if the file_roots option has a key that is none then we will error out .
train
false
45,110
def strip_accents_unicode(s): normalized = unicodedata.normalize(u'NFKD', s) if (normalized == s): return s else: return u''.join([c for c in normalized if (not unicodedata.combining(c))])
[ "def", "strip_accents_unicode", "(", "s", ")", ":", "normalized", "=", "unicodedata", ".", "normalize", "(", "u'NFKD'", ",", "s", ")", "if", "(", "normalized", "==", "s", ")", ":", "return", "s", "else", ":", "return", "u''", ".", "join", "(", "[", "c", "for", "c", "in", "normalized", "if", "(", "not", "unicodedata", ".", "combining", "(", "c", ")", ")", "]", ")" ]
transform accentuated unicode symbols into their simple counterpart warning: the python-level loop and join operations make this implementation 20 times slower than the strip_accents_ascii basic normalization .
train
false
45,111
def set_field_property(filters, key, value): docs = [frappe.get_doc(u'DocType', d.parent) for d in frappe.get_all(u'DocField', fields=[u'parent'], filters=filters)] for d in docs: d.get(u'fields', filters)[0].set(key, value) d.save() print u'Updated {0}'.format(d.name) frappe.db.commit()
[ "def", "set_field_property", "(", "filters", ",", "key", ",", "value", ")", ":", "docs", "=", "[", "frappe", ".", "get_doc", "(", "u'DocType'", ",", "d", ".", "parent", ")", "for", "d", "in", "frappe", ".", "get_all", "(", "u'DocField'", ",", "fields", "=", "[", "u'parent'", "]", ",", "filters", "=", "filters", ")", "]", "for", "d", "in", "docs", ":", "d", ".", "get", "(", "u'fields'", ",", "filters", ")", "[", "0", "]", ".", "set", "(", "key", ",", "value", ")", "d", ".", "save", "(", ")", "print", "u'Updated {0}'", ".", "format", "(", "d", ".", "name", ")", "frappe", ".", "db", ".", "commit", "(", ")" ]
utility set a property in all fields of a particular type .
train
false
45,112
def normalize(a, axis=None): a_sum = a.sum(axis) if (axis and (a.ndim > 1)): a_sum[(a_sum == 0)] = 1 shape = list(a.shape) shape[axis] = 1 a_sum.shape = shape a /= a_sum
[ "def", "normalize", "(", "a", ",", "axis", "=", "None", ")", ":", "a_sum", "=", "a", ".", "sum", "(", "axis", ")", "if", "(", "axis", "and", "(", "a", ".", "ndim", ">", "1", ")", ")", ":", "a_sum", "[", "(", "a_sum", "==", "0", ")", "]", "=", "1", "shape", "=", "list", "(", "a", ".", "shape", ")", "shape", "[", "axis", "]", "=", "1", "a_sum", ".", "shape", "=", "shape", "a", "/=", "a_sum" ]
normalize a string so that it can be used as an attribute to a python object .
train
true
45,113
def allow_public(function): _set_attribute_func(function, '_allow_public', True) return function
[ "def", "allow_public", "(", "function", ")", ":", "_set_attribute_func", "(", "function", ",", "'_allow_public'", ",", "True", ")", "return", "function" ]
allow view to be accessed by anonymous users .
train
false
45,116
def runAll(): suite = unittest.TestSuite() suite.addTest(unittest.TestLoader().loadTestsFromTestCase(StatsEventerTestCase)) unittest.TextTestRunner(verbosity=2).run(suite)
[ "def", "runAll", "(", ")", ":", "suite", "=", "unittest", ".", "TestSuite", "(", ")", "suite", ".", "addTest", "(", "unittest", ".", "TestLoader", "(", ")", ".", "loadTestsFromTestCase", "(", "StatsEventerTestCase", ")", ")", "unittest", ".", "TextTestRunner", "(", "verbosity", "=", "2", ")", ".", "run", "(", "suite", ")" ]
unittest runner .
train
false
45,117
def row_echelon(matlist, K): result_matlist = copy.deepcopy(matlist) nrow = len(result_matlist) for i in range(nrow): if ((result_matlist[i][i] != 1) and (result_matlist[i][i] != 0)): rowmul(result_matlist, i, (1 / result_matlist[i][i]), K) for j in range((i + 1), nrow): if (result_matlist[j][i] != 0): rowadd(result_matlist, j, i, (- result_matlist[j][i]), K) return result_matlist
[ "def", "row_echelon", "(", "matlist", ",", "K", ")", ":", "result_matlist", "=", "copy", ".", "deepcopy", "(", "matlist", ")", "nrow", "=", "len", "(", "result_matlist", ")", "for", "i", "in", "range", "(", "nrow", ")", ":", "if", "(", "(", "result_matlist", "[", "i", "]", "[", "i", "]", "!=", "1", ")", "and", "(", "result_matlist", "[", "i", "]", "[", "i", "]", "!=", "0", ")", ")", ":", "rowmul", "(", "result_matlist", ",", "i", ",", "(", "1", "/", "result_matlist", "[", "i", "]", "[", "i", "]", ")", ",", "K", ")", "for", "j", "in", "range", "(", "(", "i", "+", "1", ")", ",", "nrow", ")", ":", "if", "(", "result_matlist", "[", "j", "]", "[", "i", "]", "!=", "0", ")", ":", "rowadd", "(", "result_matlist", ",", "j", ",", "i", ",", "(", "-", "result_matlist", "[", "j", "]", "[", "i", "]", ")", ",", "K", ")", "return", "result_matlist" ]
returns the row echelon form of a matrix with diagonal elements reduced to 1 .
train
false
45,118
def getVector3FromElementNode(elementNode): vector3 = Vector3(getEvaluatedFloat(0.0, elementNode, 'x'), getEvaluatedFloat(0.0, elementNode, 'y'), getEvaluatedFloat(0.0, elementNode, 'z')) return getVector3ByPrefix(vector3, elementNode, 'cartesian')
[ "def", "getVector3FromElementNode", "(", "elementNode", ")", ":", "vector3", "=", "Vector3", "(", "getEvaluatedFloat", "(", "0.0", ",", "elementNode", ",", "'x'", ")", ",", "getEvaluatedFloat", "(", "0.0", ",", "elementNode", ",", "'y'", ")", ",", "getEvaluatedFloat", "(", "0.0", ",", "elementNode", ",", "'z'", ")", ")", "return", "getVector3ByPrefix", "(", "vector3", ",", "elementNode", ",", "'cartesian'", ")" ]
get vector3 from xml element .
train
false
45,119
def export_courses_to_output_path(output_path): content_store = contentstore() module_store = modulestore() root_dir = output_path courses = module_store.get_courses() course_ids = [x.id for x in courses] failed_export_courses = [] for course_id in course_ids: print (u'-' * 80) print u'Exporting course id = {0} to {1}'.format(course_id, output_path) try: course_dir = course_id.to_deprecated_string().replace('/', '...') export_course_to_xml(module_store, content_store, course_id, root_dir, course_dir) except Exception as err: failed_export_courses.append(unicode(course_id)) print ((u'=' * 30) + u'> Oops, failed to export {0}'.format(course_id)) print u'Error:' print err return (courses, failed_export_courses)
[ "def", "export_courses_to_output_path", "(", "output_path", ")", ":", "content_store", "=", "contentstore", "(", ")", "module_store", "=", "modulestore", "(", ")", "root_dir", "=", "output_path", "courses", "=", "module_store", ".", "get_courses", "(", ")", "course_ids", "=", "[", "x", ".", "id", "for", "x", "in", "courses", "]", "failed_export_courses", "=", "[", "]", "for", "course_id", "in", "course_ids", ":", "print", "(", "u'-'", "*", "80", ")", "print", "u'Exporting course id = {0} to {1}'", ".", "format", "(", "course_id", ",", "output_path", ")", "try", ":", "course_dir", "=", "course_id", ".", "to_deprecated_string", "(", ")", ".", "replace", "(", "'/'", ",", "'...'", ")", "export_course_to_xml", "(", "module_store", ",", "content_store", ",", "course_id", ",", "root_dir", ",", "course_dir", ")", "except", "Exception", "as", "err", ":", "failed_export_courses", ".", "append", "(", "unicode", "(", "course_id", ")", ")", "print", "(", "(", "u'='", "*", "30", ")", "+", "u'> Oops, failed to export {0}'", ".", "format", "(", "course_id", ")", ")", "print", "u'Error:'", "print", "err", "return", "(", "courses", ",", "failed_export_courses", ")" ]
export all courses to target directory and return the list of courses which failed to export .
train
false
45,120
def IconSetRule(icon_style=None, type=None, values=None, showValue=None, percent=None, reverse=None): cfvo = [] for val in values: cfvo.append(FormatObject(type, val)) icon_set = IconSet(iconSet=icon_style, cfvo=cfvo, showValue=showValue, percent=percent, reverse=reverse) rule = Rule(type='iconSet', iconSet=icon_set) return rule
[ "def", "IconSetRule", "(", "icon_style", "=", "None", ",", "type", "=", "None", ",", "values", "=", "None", ",", "showValue", "=", "None", ",", "percent", "=", "None", ",", "reverse", "=", "None", ")", ":", "cfvo", "=", "[", "]", "for", "val", "in", "values", ":", "cfvo", ".", "append", "(", "FormatObject", "(", "type", ",", "val", ")", ")", "icon_set", "=", "IconSet", "(", "iconSet", "=", "icon_style", ",", "cfvo", "=", "cfvo", ",", "showValue", "=", "showValue", ",", "percent", "=", "percent", ",", "reverse", "=", "reverse", ")", "rule", "=", "Rule", "(", "type", "=", "'iconSet'", ",", "iconSet", "=", "icon_set", ")", "return", "rule" ]
convenience function for creating icon set rules .
train
false
45,121
@profiler.trace def remove_domain_user_role(request, user, role, domain=None): manager = keystoneclient(request, admin=True).roles return manager.revoke(role, user=user, domain=domain)
[ "@", "profiler", ".", "trace", "def", "remove_domain_user_role", "(", "request", ",", "user", ",", "role", ",", "domain", "=", "None", ")", ":", "manager", "=", "keystoneclient", "(", "request", ",", "admin", "=", "True", ")", ".", "roles", "return", "manager", ".", "revoke", "(", "role", ",", "user", "=", "user", ",", "domain", "=", "domain", ")" ]
removes a given single role for a user from a domain .
train
true
45,122
def test_represent_tgate(): circuit = (TGate(0) * Qubit('01')) assert (Matrix([0, exp(((I * pi) / 4)), 0, 0]) == represent(circuit, nqubits=2))
[ "def", "test_represent_tgate", "(", ")", ":", "circuit", "=", "(", "TGate", "(", "0", ")", "*", "Qubit", "(", "'01'", ")", ")", "assert", "(", "Matrix", "(", "[", "0", ",", "exp", "(", "(", "(", "I", "*", "pi", ")", "/", "4", ")", ")", ",", "0", ",", "0", "]", ")", "==", "represent", "(", "circuit", ",", "nqubits", "=", "2", ")", ")" ]
test the representation of the t gate .
train
false
45,123
@pytest.mark.django_db def test_verify_user_duplicate_email(trans_member, member_with_email): trans_member.email = member_with_email.email with pytest.raises(ValidationError): accounts.utils.verify_user(trans_member) with pytest.raises(EmailAddress.DoesNotExist): EmailAddress.objects.get(user=trans_member, primary=True, verified=True)
[ "@", "pytest", ".", "mark", ".", "django_db", "def", "test_verify_user_duplicate_email", "(", "trans_member", ",", "member_with_email", ")", ":", "trans_member", ".", "email", "=", "member_with_email", ".", "email", "with", "pytest", ".", "raises", "(", "ValidationError", ")", ":", "accounts", ".", "utils", ".", "verify_user", "(", "trans_member", ")", "with", "pytest", ".", "raises", "(", "EmailAddress", ".", "DoesNotExist", ")", ":", "EmailAddress", ".", "objects", ".", "get", "(", "user", "=", "trans_member", ",", "primary", "=", "True", ",", "verified", "=", "True", ")" ]
test verifying user using verify_user function .
train
false
45,124
def get_key_func(key_func): if (key_func is not None): if callable(key_func): return key_func else: (key_func_module_path, key_func_name) = key_func.rsplit(u'.', 1) key_func_module = import_module(key_func_module_path) return getattr(key_func_module, key_func_name) return default_key_func
[ "def", "get_key_func", "(", "key_func", ")", ":", "if", "(", "key_func", "is", "not", "None", ")", ":", "if", "callable", "(", "key_func", ")", ":", "return", "key_func", "else", ":", "(", "key_func_module_path", ",", "key_func_name", ")", "=", "key_func", ".", "rsplit", "(", "u'.'", ",", "1", ")", "key_func_module", "=", "import_module", "(", "key_func_module_path", ")", "return", "getattr", "(", "key_func_module", ",", "key_func_name", ")", "return", "default_key_func" ]
function to decide which key function to use .
train
false
45,125
def manipulateXMLElement(target, xmlElement): translateMatrixTetragrid = matrix.getTranslateMatrixTetragrid('', xmlElement) if (translateMatrixTetragrid == None): print 'Warning, translateMatrixTetragrid was None in translate so nothing will be done for:' print xmlElement return matrix.setAttributeDictionaryToMultipliedTetragrid(translateMatrixTetragrid, target)
[ "def", "manipulateXMLElement", "(", "target", ",", "xmlElement", ")", ":", "translateMatrixTetragrid", "=", "matrix", ".", "getTranslateMatrixTetragrid", "(", "''", ",", "xmlElement", ")", "if", "(", "translateMatrixTetragrid", "==", "None", ")", ":", "print", "'Warning, translateMatrixTetragrid was None in translate so nothing will be done for:'", "print", "xmlElement", "return", "matrix", ".", "setAttributeDictionaryToMultipliedTetragrid", "(", "translateMatrixTetragrid", ",", "target", ")" ]
manipulate the xml element .
train
false
45,126
def list_public_methods(obj): return [member for member in dir(obj) if ((not member.startswith('_')) and hasattr(getattr(obj, member), '__call__'))]
[ "def", "list_public_methods", "(", "obj", ")", ":", "return", "[", "member", "for", "member", "in", "dir", "(", "obj", ")", "if", "(", "(", "not", "member", ".", "startswith", "(", "'_'", ")", ")", "and", "hasattr", "(", "getattr", "(", "obj", ",", "member", ")", ",", "'__call__'", ")", ")", "]" ]
returns a list of attribute strings .
train
false
45,127
def cem(f, th_mean, batch_size, n_iter, elite_frac, initial_std=1.0): n_elite = int(np.round((batch_size * elite_frac))) th_std = (np.ones_like(th_mean) * initial_std) for _ in range(n_iter): ths = np.array([(th_mean + dth) for dth in (th_std[None, :] * np.random.randn(batch_size, th_mean.size))]) ys = np.array([f(th) for th in ths]) elite_inds = ys.argsort()[::(-1)][:n_elite] elite_ths = ths[elite_inds] th_mean = elite_ths.mean(axis=0) th_std = elite_ths.std(axis=0) (yield {'ys': ys, 'theta_mean': th_mean, 'y_mean': ys.mean()})
[ "def", "cem", "(", "f", ",", "th_mean", ",", "batch_size", ",", "n_iter", ",", "elite_frac", ",", "initial_std", "=", "1.0", ")", ":", "n_elite", "=", "int", "(", "np", ".", "round", "(", "(", "batch_size", "*", "elite_frac", ")", ")", ")", "th_std", "=", "(", "np", ".", "ones_like", "(", "th_mean", ")", "*", "initial_std", ")", "for", "_", "in", "range", "(", "n_iter", ")", ":", "ths", "=", "np", ".", "array", "(", "[", "(", "th_mean", "+", "dth", ")", "for", "dth", "in", "(", "th_std", "[", "None", ",", ":", "]", "*", "np", ".", "random", ".", "randn", "(", "batch_size", ",", "th_mean", ".", "size", ")", ")", "]", ")", "ys", "=", "np", ".", "array", "(", "[", "f", "(", "th", ")", "for", "th", "in", "ths", "]", ")", "elite_inds", "=", "ys", ".", "argsort", "(", ")", "[", ":", ":", "(", "-", "1", ")", "]", "[", ":", "n_elite", "]", "elite_ths", "=", "ths", "[", "elite_inds", "]", "th_mean", "=", "elite_ths", ".", "mean", "(", "axis", "=", "0", ")", "th_std", "=", "elite_ths", ".", "std", "(", "axis", "=", "0", ")", "(", "yield", "{", "'ys'", ":", "ys", ",", "'theta_mean'", ":", "th_mean", ",", "'y_mean'", ":", "ys", ".", "mean", "(", ")", "}", ")" ]
generic implementation of the cross-entropy method for maximizing a black-box function f: a function mapping from vector -> scalar th_mean: initial mean over input distribution batch_size: number of samples of theta to evaluate per batch n_iter: number of batches elite_frac: each batch .
train
false
45,128
@register.tag def jstemplate(parser, token): nodelist = parser.parse(('endjstemplate',)) parser.delete_first_token() return JSTemplateNode(nodelist)
[ "@", "register", ".", "tag", "def", "jstemplate", "(", "parser", ",", "token", ")", ":", "nodelist", "=", "parser", ".", "parse", "(", "(", "'endjstemplate'", ",", ")", ")", "parser", ".", "delete_first_token", "(", ")", "return", "JSTemplateNode", "(", "nodelist", ")" ]
replaces [[[ and ]]] with {{{ and }}} .
train
false
45,129
def match_process(pid, name, cmdline, exe, cfg): if (cfg['selfmon'] and (pid == os.getpid())): return True for exe_re in cfg['exe']: if exe_re.search(exe): return True for name_re in cfg['name']: if name_re.search(name): return True for cmdline_re in cfg['cmdline']: if cmdline_re.search(' '.join(cmdline)): return True return False
[ "def", "match_process", "(", "pid", ",", "name", ",", "cmdline", ",", "exe", ",", "cfg", ")", ":", "if", "(", "cfg", "[", "'selfmon'", "]", "and", "(", "pid", "==", "os", ".", "getpid", "(", ")", ")", ")", ":", "return", "True", "for", "exe_re", "in", "cfg", "[", "'exe'", "]", ":", "if", "exe_re", ".", "search", "(", "exe", ")", ":", "return", "True", "for", "name_re", "in", "cfg", "[", "'name'", "]", ":", "if", "name_re", ".", "search", "(", "name", ")", ":", "return", "True", "for", "cmdline_re", "in", "cfg", "[", "'cmdline'", "]", ":", "if", "cmdline_re", ".", "search", "(", "' '", ".", "join", "(", "cmdline", ")", ")", ":", "return", "True", "return", "False" ]
decides whether a process matches with a given process descriptor .
train
true
45,130
@cache_control(private=True, must_revalidate=True, max_age=60) def logo_image(request, gif=False, response_format='html'): staticpath = getattr(settings, 'STATIC_DOC_ROOT', './static') logopath = (staticpath + '/logo') if gif: logopath += '.gif' mimetype = 'image/gif' else: logopath += '.png' mimetype = 'image/png' customlogo = '' try: conf = ModuleSetting.get_for_module('treeio.core', 'logopath')[0] customlogo = (getattr(settings, 'MEDIA_ROOT', './static/media') + conf.value) except: pass logofile = '' if customlogo: try: logofile = open(customlogo, 'rb') except: pass if (not logofile): try: logofile = open(logopath, 'rb') except: pass return HttpResponse(logofile.read(), content_type=mimetype)
[ "@", "cache_control", "(", "private", "=", "True", ",", "must_revalidate", "=", "True", ",", "max_age", "=", "60", ")", "def", "logo_image", "(", "request", ",", "gif", "=", "False", ",", "response_format", "=", "'html'", ")", ":", "staticpath", "=", "getattr", "(", "settings", ",", "'STATIC_DOC_ROOT'", ",", "'./static'", ")", "logopath", "=", "(", "staticpath", "+", "'/logo'", ")", "if", "gif", ":", "logopath", "+=", "'.gif'", "mimetype", "=", "'image/gif'", "else", ":", "logopath", "+=", "'.png'", "mimetype", "=", "'image/png'", "customlogo", "=", "''", "try", ":", "conf", "=", "ModuleSetting", ".", "get_for_module", "(", "'treeio.core'", ",", "'logopath'", ")", "[", "0", "]", "customlogo", "=", "(", "getattr", "(", "settings", ",", "'MEDIA_ROOT'", ",", "'./static/media'", ")", "+", "conf", ".", "value", ")", "except", ":", "pass", "logofile", "=", "''", "if", "customlogo", ":", "try", ":", "logofile", "=", "open", "(", "customlogo", ",", "'rb'", ")", "except", ":", "pass", "if", "(", "not", "logofile", ")", ":", "try", ":", "logofile", "=", "open", "(", "logopath", ",", "'rb'", ")", "except", ":", "pass", "return", "HttpResponse", "(", "logofile", ".", "read", "(", ")", ",", "content_type", "=", "mimetype", ")" ]
return current logo image .
train
false
45,132
def _can_use_numexpr(op, op_str, a, b, dtype_check): if (op_str is not None): if (np.prod(a.shape) > _MIN_ELEMENTS): dtypes = set() for o in [a, b]: if hasattr(o, 'get_dtype_counts'): s = o.get_dtype_counts() if (len(s) > 1): return False dtypes |= set(s.index) elif isinstance(o, np.ndarray): dtypes |= set([o.dtype.name]) if ((not len(dtypes)) or (_ALLOWED_DTYPES[dtype_check] >= dtypes)): return True return False
[ "def", "_can_use_numexpr", "(", "op", ",", "op_str", ",", "a", ",", "b", ",", "dtype_check", ")", ":", "if", "(", "op_str", "is", "not", "None", ")", ":", "if", "(", "np", ".", "prod", "(", "a", ".", "shape", ")", ">", "_MIN_ELEMENTS", ")", ":", "dtypes", "=", "set", "(", ")", "for", "o", "in", "[", "a", ",", "b", "]", ":", "if", "hasattr", "(", "o", ",", "'get_dtype_counts'", ")", ":", "s", "=", "o", ".", "get_dtype_counts", "(", ")", "if", "(", "len", "(", "s", ")", ">", "1", ")", ":", "return", "False", "dtypes", "|=", "set", "(", "s", ".", "index", ")", "elif", "isinstance", "(", "o", ",", "np", ".", "ndarray", ")", ":", "dtypes", "|=", "set", "(", "[", "o", ".", "dtype", ".", "name", "]", ")", "if", "(", "(", "not", "len", "(", "dtypes", ")", ")", "or", "(", "_ALLOWED_DTYPES", "[", "dtype_check", "]", ">=", "dtypes", ")", ")", ":", "return", "True", "return", "False" ]
return a boolean if we will be using numexpr .
train
true
45,133
def checking_conference(id_conference): conferences = get_memcached(get_key('conferences')) if (id_conference in conferences.keys()): return True return False
[ "def", "checking_conference", "(", "id_conference", ")", ":", "conferences", "=", "get_memcached", "(", "get_key", "(", "'conferences'", ")", ")", "if", "(", "id_conference", "in", "conferences", ".", "keys", "(", ")", ")", ":", "return", "True", "return", "False" ]
checking for the existence of the conference .
train
false
45,134
@pytest.mark.django_db def test_specialchars_can_be_blank(): form_data = {'code': 'foo', 'fullname': 'Foo', 'checkstyle': 'foo', 'nplurals': '2', 'specialchars': ''} form = LanguageForm(form_data) assert form.is_valid() assert (form.cleaned_data['specialchars'] == '')
[ "@", "pytest", ".", "mark", ".", "django_db", "def", "test_specialchars_can_be_blank", "(", ")", ":", "form_data", "=", "{", "'code'", ":", "'foo'", ",", "'fullname'", ":", "'Foo'", ",", "'checkstyle'", ":", "'foo'", ",", "'nplurals'", ":", "'2'", ",", "'specialchars'", ":", "''", "}", "form", "=", "LanguageForm", "(", "form_data", ")", "assert", "form", ".", "is_valid", "(", ")", "assert", "(", "form", ".", "cleaned_data", "[", "'specialchars'", "]", "==", "''", ")" ]
test that a blank special character field is valid .
train
false
45,137
def bartlett(M): return bartlett_(M)
[ "def", "bartlett", "(", "M", ")", ":", "return", "bartlett_", "(", "M", ")" ]
an instance of this class returns the bartlett spectral window in the time-domain .
train
false
45,138
def untracked(prefix, exclude_self_build=False): conda_files = conda_installed_files(prefix, exclude_self_build) return {path for path in (walk_prefix(prefix) - conda_files) if (not (path.endswith(u'~') or ((sys.platform == u'darwin') and path.endswith(u'.DS_Store')) or (path.endswith(u'.pyc') and (path[:(-1)] in conda_files))))}
[ "def", "untracked", "(", "prefix", ",", "exclude_self_build", "=", "False", ")", ":", "conda_files", "=", "conda_installed_files", "(", "prefix", ",", "exclude_self_build", ")", "return", "{", "path", "for", "path", "in", "(", "walk_prefix", "(", "prefix", ")", "-", "conda_files", ")", "if", "(", "not", "(", "path", ".", "endswith", "(", "u'~'", ")", "or", "(", "(", "sys", ".", "platform", "==", "u'darwin'", ")", "and", "path", ".", "endswith", "(", "u'.DS_Store'", ")", ")", "or", "(", "path", ".", "endswith", "(", "u'.pyc'", ")", "and", "(", "path", "[", ":", "(", "-", "1", ")", "]", "in", "conda_files", ")", ")", ")", ")", "}" ]
return of all untracked files for a given prefix .
train
false
45,139
def _get_thread_from_model(thread_model): return feedback_domain.FeedbackThread(thread_model.id, thread_model.exploration_id, thread_model.state_name, thread_model.original_author_id, thread_model.status, thread_model.subject, thread_model.summary, thread_model.has_suggestion, thread_model.created_on, thread_model.last_updated)
[ "def", "_get_thread_from_model", "(", "thread_model", ")", ":", "return", "feedback_domain", ".", "FeedbackThread", "(", "thread_model", ".", "id", ",", "thread_model", ".", "exploration_id", ",", "thread_model", ".", "state_name", ",", "thread_model", ".", "original_author_id", ",", "thread_model", ".", "status", ",", "thread_model", ".", "subject", ",", "thread_model", ".", "summary", ",", "thread_model", ".", "has_suggestion", ",", "thread_model", ".", "created_on", ",", "thread_model", ".", "last_updated", ")" ]
converts the given feedbackthreadmodel to a feedbackthread object .
train
false
45,140
def find_disk_dev_for_disk_bus(mapping, bus, last_device=False): dev_prefix = get_dev_prefix_for_disk_bus(bus) if (dev_prefix is None): return None max_dev = get_dev_count_for_disk_bus(bus) if last_device: devs = [(max_dev - 1)] else: devs = range(max_dev) for idx in devs: disk_dev = (dev_prefix + chr((ord('a') + idx))) if (not has_disk_dev(mapping, disk_dev)): return disk_dev raise exception.NovaException(_("No free disk device names for prefix '%s'"), dev_prefix)
[ "def", "find_disk_dev_for_disk_bus", "(", "mapping", ",", "bus", ",", "last_device", "=", "False", ")", ":", "dev_prefix", "=", "get_dev_prefix_for_disk_bus", "(", "bus", ")", "if", "(", "dev_prefix", "is", "None", ")", ":", "return", "None", "max_dev", "=", "get_dev_count_for_disk_bus", "(", "bus", ")", "if", "last_device", ":", "devs", "=", "[", "(", "max_dev", "-", "1", ")", "]", "else", ":", "devs", "=", "range", "(", "max_dev", ")", "for", "idx", "in", "devs", ":", "disk_dev", "=", "(", "dev_prefix", "+", "chr", "(", "(", "ord", "(", "'a'", ")", "+", "idx", ")", ")", ")", "if", "(", "not", "has_disk_dev", "(", "mapping", ",", "disk_dev", ")", ")", ":", "return", "disk_dev", "raise", "exception", ".", "NovaException", "(", "_", "(", "\"No free disk device names for prefix '%s'\"", ")", ",", "dev_prefix", ")" ]
identify a free disk dev name for a bus .
train
false
45,141
def RemoveSourceFromRegistry(appName, eventLogType='Application'): try: win32api.RegDeleteKey(win32con.HKEY_LOCAL_MACHINE, ('SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s' % (eventLogType, appName))) except win32api.error as (hr, fn, desc): if (hr != winerror.ERROR_FILE_NOT_FOUND): raise
[ "def", "RemoveSourceFromRegistry", "(", "appName", ",", "eventLogType", "=", "'Application'", ")", ":", "try", ":", "win32api", ".", "RegDeleteKey", "(", "win32con", ".", "HKEY_LOCAL_MACHINE", ",", "(", "'SYSTEM\\\\CurrentControlSet\\\\Services\\\\EventLog\\\\%s\\\\%s'", "%", "(", "eventLogType", ",", "appName", ")", ")", ")", "except", "win32api", ".", "error", "as", "(", "hr", ",", "fn", ",", "desc", ")", ":", "if", "(", "hr", "!=", "winerror", ".", "ERROR_FILE_NOT_FOUND", ")", ":", "raise" ]
removes a source of messages from the event log .
train
false
45,143
def conv_gru(inpts, mem, kw, kh, nmaps, cutoff, prefix): def conv_lin(args, suffix, bias_start): return conv_linear(args, kw, kh, (len(args) * nmaps), nmaps, True, bias_start, ((prefix + '/') + suffix)) reset = sigmoid_cutoff(conv_lin((inpts + [mem]), 'r', 1.0), cutoff) candidate = tf.tanh(conv_lin((inpts + [(reset * mem)]), 'c', 0.0)) gate = sigmoid_cutoff(conv_lin((inpts + [mem]), 'g', 1.0), cutoff) return ((gate * mem) + ((1 - gate) * candidate))
[ "def", "conv_gru", "(", "inpts", ",", "mem", ",", "kw", ",", "kh", ",", "nmaps", ",", "cutoff", ",", "prefix", ")", ":", "def", "conv_lin", "(", "args", ",", "suffix", ",", "bias_start", ")", ":", "return", "conv_linear", "(", "args", ",", "kw", ",", "kh", ",", "(", "len", "(", "args", ")", "*", "nmaps", ")", ",", "nmaps", ",", "True", ",", "bias_start", ",", "(", "(", "prefix", "+", "'/'", ")", "+", "suffix", ")", ")", "reset", "=", "sigmoid_cutoff", "(", "conv_lin", "(", "(", "inpts", "+", "[", "mem", "]", ")", ",", "'r'", ",", "1.0", ")", ",", "cutoff", ")", "candidate", "=", "tf", ".", "tanh", "(", "conv_lin", "(", "(", "inpts", "+", "[", "(", "reset", "*", "mem", ")", "]", ")", ",", "'c'", ",", "0.0", ")", ")", "gate", "=", "sigmoid_cutoff", "(", "conv_lin", "(", "(", "inpts", "+", "[", "mem", "]", ")", ",", "'g'", ",", "1.0", ")", ",", "cutoff", ")", "return", "(", "(", "gate", "*", "mem", ")", "+", "(", "(", "1", "-", "gate", ")", "*", "candidate", ")", ")" ]
convolutional gru .
train
false
45,146
def prepare_lookup_for_tvmaze(**lookup_params): prepared_params = {} title = None series_name = (lookup_params.get(u'series_name') or lookup_params.get(u'show_name') or lookup_params.get(u'title')) if series_name: (title, _) = split_title_year(series_name) if (not title): title = series_name prepared_params[u'tvmaze_id'] = lookup_params.get(u'tvmaze_id') prepared_params[u'thetvdb_id'] = (lookup_params.get(u'tvdb_id') or lookup_params.get(u'trakt_series_tvdb_id')) prepared_params[u'tvrage_id'] = (lookup_params.get(u'tvrage_id') or lookup_params.get(u'trakt_series_tvrage_id')) prepared_params[u'imdb_id'] = lookup_params.get(u'imdb_id') prepared_params[u'show_name'] = (native(title) if title else None) return prepared_params
[ "def", "prepare_lookup_for_tvmaze", "(", "**", "lookup_params", ")", ":", "prepared_params", "=", "{", "}", "title", "=", "None", "series_name", "=", "(", "lookup_params", ".", "get", "(", "u'series_name'", ")", "or", "lookup_params", ".", "get", "(", "u'show_name'", ")", "or", "lookup_params", ".", "get", "(", "u'title'", ")", ")", "if", "series_name", ":", "(", "title", ",", "_", ")", "=", "split_title_year", "(", "series_name", ")", "if", "(", "not", "title", ")", ":", "title", "=", "series_name", "prepared_params", "[", "u'tvmaze_id'", "]", "=", "lookup_params", ".", "get", "(", "u'tvmaze_id'", ")", "prepared_params", "[", "u'thetvdb_id'", "]", "=", "(", "lookup_params", ".", "get", "(", "u'tvdb_id'", ")", "or", "lookup_params", ".", "get", "(", "u'trakt_series_tvdb_id'", ")", ")", "prepared_params", "[", "u'tvrage_id'", "]", "=", "(", "lookup_params", ".", "get", "(", "u'tvrage_id'", ")", "or", "lookup_params", ".", "get", "(", "u'trakt_series_tvrage_id'", ")", ")", "prepared_params", "[", "u'imdb_id'", "]", "=", "lookup_params", ".", "get", "(", "u'imdb_id'", ")", "prepared_params", "[", "u'show_name'", "]", "=", "(", "native", "(", "title", ")", "if", "title", "else", "None", ")", "return", "prepared_params" ]
return a dict of params which is valid with tvmaze api lookups .
train
false
45,147
def datetime_from_iso8601(datetime_str): return aniso8601.parse_datetime(datetime_str)
[ "def", "datetime_from_iso8601", "(", "datetime_str", ")", ":", "return", "aniso8601", ".", "parse_datetime", "(", "datetime_str", ")" ]
turns an iso8601 formatted date into a datetime object .
train
false
45,148
def _get_weights(dist, weights): if (weights in (None, 'uniform')): return None elif (weights == 'distance'): if (dist.dtype is np.dtype(object)): for (point_dist_i, point_dist) in enumerate(dist): if (hasattr(point_dist, '__contains__') and (0.0 in point_dist)): dist[point_dist_i] = (point_dist == 0.0) else: dist[point_dist_i] = (1.0 / point_dist) else: with np.errstate(divide='ignore'): dist = (1.0 / dist) inf_mask = np.isinf(dist) inf_row = np.any(inf_mask, axis=1) dist[inf_row] = inf_mask[inf_row] return dist elif callable(weights): return weights(dist) else: raise ValueError("weights not recognized: should be 'uniform', 'distance', or a callable function")
[ "def", "_get_weights", "(", "dist", ",", "weights", ")", ":", "if", "(", "weights", "in", "(", "None", ",", "'uniform'", ")", ")", ":", "return", "None", "elif", "(", "weights", "==", "'distance'", ")", ":", "if", "(", "dist", ".", "dtype", "is", "np", ".", "dtype", "(", "object", ")", ")", ":", "for", "(", "point_dist_i", ",", "point_dist", ")", "in", "enumerate", "(", "dist", ")", ":", "if", "(", "hasattr", "(", "point_dist", ",", "'__contains__'", ")", "and", "(", "0.0", "in", "point_dist", ")", ")", ":", "dist", "[", "point_dist_i", "]", "=", "(", "point_dist", "==", "0.0", ")", "else", ":", "dist", "[", "point_dist_i", "]", "=", "(", "1.0", "/", "point_dist", ")", "else", ":", "with", "np", ".", "errstate", "(", "divide", "=", "'ignore'", ")", ":", "dist", "=", "(", "1.0", "/", "dist", ")", "inf_mask", "=", "np", ".", "isinf", "(", "dist", ")", "inf_row", "=", "np", ".", "any", "(", "inf_mask", ",", "axis", "=", "1", ")", "dist", "[", "inf_row", "]", "=", "inf_mask", "[", "inf_row", "]", "return", "dist", "elif", "callable", "(", "weights", ")", ":", "return", "weights", "(", "dist", ")", "else", ":", "raise", "ValueError", "(", "\"weights not recognized: should be 'uniform', 'distance', or a callable function\"", ")" ]
get the weights from an array of distances and a parameter weights parameters dist : ndarray the input distances weights : {uniform .
train
false
45,149
def disable_root_login(sshd_config='/etc/ssh/sshd_config'): _update_ssh_setting(sshd_config, 'PermitRootLogin', 'no')
[ "def", "disable_root_login", "(", "sshd_config", "=", "'/etc/ssh/sshd_config'", ")", ":", "_update_ssh_setting", "(", "sshd_config", ",", "'PermitRootLogin'", ",", "'no'", ")" ]
do not allow root to login via ssh .
train
false
45,150
@RegisterWithArgChecks(name='neighbor.in_filter.get', req_args=[neighbors.IP_ADDRESS]) def get_neighbor_in_filter(neigh_ip_address): core = CORE_MANAGER.get_core_service() peer = core.peer_manager.get_by_addr(neigh_ip_address) return peer.in_filters
[ "@", "RegisterWithArgChecks", "(", "name", "=", "'neighbor.in_filter.get'", ",", "req_args", "=", "[", "neighbors", ".", "IP_ADDRESS", "]", ")", "def", "get_neighbor_in_filter", "(", "neigh_ip_address", ")", ":", "core", "=", "CORE_MANAGER", ".", "get_core_service", "(", ")", "peer", "=", "core", ".", "peer_manager", ".", "get_by_addr", "(", "neigh_ip_address", ")", "return", "peer", ".", "in_filters" ]
returns a neighbor in_filter for given ip address if exists .
train
false
45,152
def normalize_together(option_together): try: if (not option_together): return () if (not isinstance(option_together, (tuple, list))): raise TypeError first_element = next(iter(option_together)) if (not isinstance(first_element, (tuple, list))): option_together = (option_together,) return tuple((tuple(ot) for ot in option_together)) except TypeError: return option_together
[ "def", "normalize_together", "(", "option_together", ")", ":", "try", ":", "if", "(", "not", "option_together", ")", ":", "return", "(", ")", "if", "(", "not", "isinstance", "(", "option_together", ",", "(", "tuple", ",", "list", ")", ")", ")", ":", "raise", "TypeError", "first_element", "=", "next", "(", "iter", "(", "option_together", ")", ")", "if", "(", "not", "isinstance", "(", "first_element", ",", "(", "tuple", ",", "list", ")", ")", ")", ":", "option_together", "=", "(", "option_together", ",", ")", "return", "tuple", "(", "(", "tuple", "(", "ot", ")", "for", "ot", "in", "option_together", ")", ")", "except", "TypeError", ":", "return", "option_together" ]
option_together can be either a tuple of tuples .
train
false
45,154
def _check_n_samples(n_samples, n_chan): n_samples_min = ((10 * (n_chan + 1)) // 2) if (n_samples <= 0): raise ValueError('No samples found to compute the covariance matrix') if (n_samples < n_samples_min): warn(('Too few samples (required : %d got : %d), covariance estimate may be unreliable' % (n_samples_min, n_samples)))
[ "def", "_check_n_samples", "(", "n_samples", ",", "n_chan", ")", ":", "n_samples_min", "=", "(", "(", "10", "*", "(", "n_chan", "+", "1", ")", ")", "//", "2", ")", "if", "(", "n_samples", "<=", "0", ")", ":", "raise", "ValueError", "(", "'No samples found to compute the covariance matrix'", ")", "if", "(", "n_samples", "<", "n_samples_min", ")", ":", "warn", "(", "(", "'Too few samples (required : %d got : %d), covariance estimate may be unreliable'", "%", "(", "n_samples_min", ",", "n_samples", ")", ")", ")" ]
check to see if there are enough samples for reliable cov calc .
train
false
45,155
def _wait_for_spot_request_fulfillment(conn, requests, fulfilled_requests=[]): if (len(requests) == 0): reservations = conn.get_all_instances(instance_ids=[r.instance_id for r in fulfilled_requests]) return [r.instances[0] for r in reservations] else: time.sleep(10) print '.' requests = conn.get_all_spot_instance_requests(request_ids=[req.id for req in requests]) for req in requests: if (req.status.code == 'fulfilled'): fulfilled_requests.append(req) print 'spot bee `{}` joined the swarm.'.format(req.instance_id) return _wait_for_spot_request_fulfillment(conn, [r for r in requests if (r not in fulfilled_requests)], fulfilled_requests)
[ "def", "_wait_for_spot_request_fulfillment", "(", "conn", ",", "requests", ",", "fulfilled_requests", "=", "[", "]", ")", ":", "if", "(", "len", "(", "requests", ")", "==", "0", ")", ":", "reservations", "=", "conn", ".", "get_all_instances", "(", "instance_ids", "=", "[", "r", ".", "instance_id", "for", "r", "in", "fulfilled_requests", "]", ")", "return", "[", "r", ".", "instances", "[", "0", "]", "for", "r", "in", "reservations", "]", "else", ":", "time", ".", "sleep", "(", "10", ")", "print", "'.'", "requests", "=", "conn", ".", "get_all_spot_instance_requests", "(", "request_ids", "=", "[", "req", ".", "id", "for", "req", "in", "requests", "]", ")", "for", "req", "in", "requests", ":", "if", "(", "req", ".", "status", ".", "code", "==", "'fulfilled'", ")", ":", "fulfilled_requests", ".", "append", "(", "req", ")", "print", "'spot bee `{}` joined the swarm.'", ".", "format", "(", "req", ".", "instance_id", ")", "return", "_wait_for_spot_request_fulfillment", "(", "conn", ",", "[", "r", "for", "r", "in", "requests", "if", "(", "r", "not", "in", "fulfilled_requests", ")", "]", ",", "fulfilled_requests", ")" ]
wait until all spot requests are fulfilled .
train
false
45,156
def nth(n, seq): if isinstance(seq, (tuple, list, collections.Sequence)): return seq[n] else: return next(itertools.islice(seq, n, None))
[ "def", "nth", "(", "n", ",", "seq", ")", ":", "if", "isinstance", "(", "seq", ",", "(", "tuple", ",", "list", ",", "collections", ".", "Sequence", ")", ")", ":", "return", "seq", "[", "n", "]", "else", ":", "return", "next", "(", "itertools", ".", "islice", "(", "seq", ",", "n", ",", "None", ")", ")" ]
the nth element in a sequence .
train
false
45,157
def _api_server_stats(name, output, kwargs): (sum_t, sum_m, sum_w, sum_d) = BPSMeter.do.get_sums() stats = {'total': sum_t, 'month': sum_m, 'week': sum_w, 'day': sum_d} stats['servers'] = {} for svr in config.get_servers(): (t, m, w, d) = BPSMeter.do.amounts(svr) stats['servers'][svr] = {'total': (t or 0), 'month': (m or 0), 'week': (w or 0), 'day': (d or 0)} return report(output, keyword='', data=stats)
[ "def", "_api_server_stats", "(", "name", ",", "output", ",", "kwargs", ")", ":", "(", "sum_t", ",", "sum_m", ",", "sum_w", ",", "sum_d", ")", "=", "BPSMeter", ".", "do", ".", "get_sums", "(", ")", "stats", "=", "{", "'total'", ":", "sum_t", ",", "'month'", ":", "sum_m", ",", "'week'", ":", "sum_w", ",", "'day'", ":", "sum_d", "}", "stats", "[", "'servers'", "]", "=", "{", "}", "for", "svr", "in", "config", ".", "get_servers", "(", ")", ":", "(", "t", ",", "m", ",", "w", ",", "d", ")", "=", "BPSMeter", ".", "do", ".", "amounts", "(", "svr", ")", "stats", "[", "'servers'", "]", "[", "svr", "]", "=", "{", "'total'", ":", "(", "t", "or", "0", ")", ",", "'month'", ":", "(", "m", "or", "0", ")", ",", "'week'", ":", "(", "w", "or", "0", ")", ",", "'day'", ":", "(", "d", "or", "0", ")", "}", "return", "report", "(", "output", ",", "keyword", "=", "''", ",", "data", "=", "stats", ")" ]
api: accepts output .
train
false