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
50,895
def floor(x): return Floor()(x)
[ "def", "floor", "(", "x", ")", ":", "return", "Floor", "(", ")", "(", "x", ")" ]
elementwise floor function .
train
false
50,898
def seed_permissions_roles(course_key): administrator_role = _save_forum_role(course_key, FORUM_ROLE_ADMINISTRATOR) moderator_role = _save_forum_role(course_key, FORUM_ROLE_MODERATOR) community_ta_role = _save_forum_role(course_key, FORUM_ROLE_COMMUNITY_TA) student_role = _save_forum_role(course_key, FORUM_ROLE_STUDENT) for per in STUDENT_ROLE_PERMISSIONS: student_role.add_permission(per) for per in MODERATOR_ROLE_PERMISSIONS: moderator_role.add_permission(per) for per in ADMINISTRATOR_ROLE_PERMISSIONS: administrator_role.add_permission(per) moderator_role.inherit_permissions(student_role) community_ta_role.inherit_permissions(moderator_role) administrator_role.inherit_permissions(moderator_role)
[ "def", "seed_permissions_roles", "(", "course_key", ")", ":", "administrator_role", "=", "_save_forum_role", "(", "course_key", ",", "FORUM_ROLE_ADMINISTRATOR", ")", "moderator_role", "=", "_save_forum_role", "(", "course_key", ",", "FORUM_ROLE_MODERATOR", ")", "community...
create and assign permissions for forum roles .
train
false
50,899
@app.teardown_appcontext def close_database(exception): top = _app_ctx_stack.top if hasattr(top, 'sqlite_db'): top.sqlite_db.close()
[ "@", "app", ".", "teardown_appcontext", "def", "close_database", "(", "exception", ")", ":", "top", "=", "_app_ctx_stack", ".", "top", "if", "hasattr", "(", "top", ",", "'sqlite_db'", ")", ":", "top", ".", "sqlite_db", ".", "close", "(", ")" ]
closes the database again at the end of the request .
train
false
50,900
@requires_application() def test_arrow_attributes(): with TestingCanvas() as c: arrow = visuals.Arrow(pos=vertices, arrow_type='stealth', arrows=arrows, arrow_size=10, color='red', connect='segments', parent=c.scene) def size_test(): arrow.arrow_size = 0.0 def type_test(): arrow.arrow_type = 'random_non_existent' assert_raises(ValueError, size_test) assert_raises(ValueError, type_test)
[ "@", "requires_application", "(", ")", "def", "test_arrow_attributes", "(", ")", ":", "with", "TestingCanvas", "(", ")", "as", "c", ":", "arrow", "=", "visuals", ".", "Arrow", "(", "pos", "=", "vertices", ",", "arrow_type", "=", "'stealth'", ",", "arrows",...
tests if the arrowvisual performs the required checks for the attributes .
train
false
50,901
def bugs_to_json_response(data, bunch_of_bugs, callback_function_name=''): obj_serializer = serializers.get_serializer('python')() bugs = obj_serializer.serialize(bunch_of_bugs) for bug in bugs: project = Project.objects.get(pk=int(bug['fields']['project'])) bug['fields']['project'] = project.display_name data_list = [{'bugs': bugs}] json_as_string = json.dumps(data_list, default=encode_datetime) json_string_with_callback = (((callback_function_name + '(') + json_as_string) + ')') return HttpResponse(json_string_with_callback)
[ "def", "bugs_to_json_response", "(", "data", ",", "bunch_of_bugs", ",", "callback_function_name", "=", "''", ")", ":", "obj_serializer", "=", "serializers", ".", "get_serializer", "(", "'python'", ")", "(", ")", "bugs", "=", "obj_serializer", ".", "serialize", "...
the search results page accesses this view via jquerys getjson method .
train
false
50,902
def notTorNZBFile(filename): return (not (filename.endswith(u'.torrent') or filename.endswith(u'.nzb')))
[ "def", "notTorNZBFile", "(", "filename", ")", ":", "return", "(", "not", "(", "filename", ".", "endswith", "(", "u'.torrent'", ")", "or", "filename", ".", "endswith", "(", "u'.nzb'", ")", ")", ")" ]
returns true if filename is not a nzb nor torrent file .
train
false
50,903
def Hypergeometric(name, N, m, n): return rv(name, HypergeometricDistribution, N, m, n)
[ "def", "Hypergeometric", "(", "name", ",", "N", ",", "m", ",", "n", ")", ":", "return", "rv", "(", "name", ",", "HypergeometricDistribution", ",", "N", ",", "m", ",", "n", ")" ]
create a finite random variable representing a hypergeometric distribution .
train
false
50,904
def enable_share(cookie, tokens, fid_list): url = ''.join([const.PAN_URL, 'share/set?channel=chunlei&clienttype=0&web=1', '&bdstoken=', tokens['bdstoken']]) data = encoder.encode_uri('fid_list={0}&schannel=0&channel_list=[]'.format(fid_list)) req = net.urlopen(url, headers={'Cookie': cookie.header_output(), 'Content-type': const.CONTENT_FORM_UTF8}, data=data.encode()) if req: content = req.data return json.loads(content.decode()) else: return None
[ "def", "enable_share", "(", "cookie", ",", "tokens", ",", "fid_list", ")", ":", "url", "=", "''", ".", "join", "(", "[", "const", ".", "PAN_URL", ",", "'share/set?channel=chunlei&clienttype=0&web=1'", ",", "'&bdstoken='", ",", "tokens", "[", "'bdstoken'", "]",...
fid_list - 是一个list .
train
true
50,906
def cache_feed(): resourcename = 'cache' output = s3_rest_controller(module, resourcename) return output
[ "def", "cache_feed", "(", ")", ":", "resourcename", "=", "'cache'", "output", "=", "s3_rest_controller", "(", "module", ",", "resourcename", ")", "return", "output" ]
restful crud controller - cache georss/kml feeds & make them available to the map viewing client as geojson the create .
train
false
50,907
def set_game_score(token, user_id, score, force=None, disable_edit_message=None, chat_id=None, message_id=None, inline_message_id=None): method_url = 'setGameScore' payload = {'user_id': user_id, 'score': score} if force: payload['force'] = force if chat_id: payload['chat_id'] = chat_id if message_id: payload['message_id'] = message_id if inline_message_id: payload['inline_message_id'] = inline_message_id if disable_edit_message: payload['disable_edit_message'] = disable_edit_message return _make_request(token, method_url, params=payload)
[ "def", "set_game_score", "(", "token", ",", "user_id", ",", "score", ",", "force", "=", "None", ",", "disable_edit_message", "=", "None", ",", "chat_id", "=", "None", ",", "message_id", "=", "None", ",", "inline_message_id", "=", "None", ")", ":", "method_...
use this method to set the score of the specified user in a game .
train
true
50,908
def __pack_message(operation, data): request_id = _randint() message = struct.pack('<i', (16 + len(data))) message += struct.pack('<i', request_id) message += _ZERO_32 message += struct.pack('<i', operation) return (request_id, (message + data))
[ "def", "__pack_message", "(", "operation", ",", "data", ")", ":", "request_id", "=", "_randint", "(", ")", "message", "=", "struct", ".", "pack", "(", "'<i'", ",", "(", "16", "+", "len", "(", "data", ")", ")", ")", "message", "+=", "struct", ".", "...
takes message data and adds a message header based on the operation .
train
true
50,909
def strip_prefix(device_name): device_name = strip_dev(device_name) return (_pref.sub('', device_name) if device_name else device_name)
[ "def", "strip_prefix", "(", "device_name", ")", ":", "device_name", "=", "strip_dev", "(", "device_name", ")", "return", "(", "_pref", ".", "sub", "(", "''", ",", "device_name", ")", "if", "device_name", "else", "device_name", ")" ]
remove both leading /dev/ and xvd or sd or vd or hd .
train
false
50,910
@register('http') def _check_http(brain, match_kind, match, target_dict, cred_dict): url = ('http:' + (match % target_dict)) data = {'target': jsonutils.dumps(target_dict), 'credentials': jsonutils.dumps(cred_dict)} post_data = urllib.urlencode(data) f = urllib2.urlopen(url, post_data) return (f.read() == 'True')
[ "@", "register", "(", "'http'", ")", "def", "_check_http", "(", "brain", ",", "match_kind", ",", "match", ",", "target_dict", ",", "cred_dict", ")", ":", "url", "=", "(", "'http:'", "+", "(", "match", "%", "target_dict", ")", ")", "data", "=", "{", "...
check http: rules by calling to a remote server .
train
false
50,911
@with_setup(prepare_stdout) def test_output_with_success_colorless2(): runner = Runner(join(abspath(dirname(__file__)), 'output_features', 'runner_features'), verbosity=3, no_color=True) runner.run() assert_stdout_lines('\nFeature: Dumb feature # tests/functional/output_features/runner_features/first.feature:1\n In order to test success # tests/functional/output_features/runner_features/first.feature:2\n As a programmer # tests/functional/output_features/runner_features/first.feature:3\n I want to see that the output is green # tests/functional/output_features/runner_features/first.feature:4\n\n Scenario: Do nothing # tests/functional/output_features/runner_features/first.feature:6\n Given I do nothing # tests/functional/output_features/runner_features/dumb_steps.py:6\n\n1 feature (1 passed)\n1 scenario (1 passed)\n1 step (1 passed)\n')
[ "@", "with_setup", "(", "prepare_stdout", ")", "def", "test_output_with_success_colorless2", "(", ")", ":", "runner", "=", "Runner", "(", "join", "(", "abspath", "(", "dirname", "(", "__file__", ")", ")", ",", "'output_features'", ",", "'runner_features'", ")", ...
testing the colorless output of a successful feature .
train
false
50,912
def get_opts(): return __opts__
[ "def", "get_opts", "(", ")", ":", "return", "__opts__" ]
return the configuration options passed to this minion cli example: .
train
false
50,915
def isfinal(elt): return (type(elt) in [str, int, float, unicode, datetime.datetime, REGEXP_T])
[ "def", "isfinal", "(", "elt", ")", ":", "return", "(", "type", "(", "elt", ")", "in", "[", "str", ",", "int", ",", "float", ",", "unicode", ",", "datetime", ".", "datetime", ",", "REGEXP_T", "]", ")" ]
decides whether or not elt is a final element .
train
false
50,916
def _get_links(sr_id, sort, time): q = Link._query((Link.c.sr_id == sr_id), sort=db_sort(sort), data=True) if (time != 'all'): q._filter(db_times[time]) res = make_results(q) return res
[ "def", "_get_links", "(", "sr_id", ",", "sort", ",", "time", ")", ":", "q", "=", "Link", ".", "_query", "(", "(", "Link", ".", "c", ".", "sr_id", "==", "sr_id", ")", ",", "sort", "=", "db_sort", "(", "sort", ")", ",", "data", "=", "True", ")", ...
general link query for a subreddit .
train
false
50,917
def get_nav_history(code, start=None, end=None, retry_count=3, pause=0.001, timeout=10): start = (du.today_last_year() if (start is None) else start) end = (du.today() if (end is None) else end) ismonetary = False df_fund = get_fund_info(code) fund_type = df_fund.ix[0]['Type2Name'] if ((fund_type.find(u'\u503a\u5238\u578b') != (-1)) or (fund_type.find(u'\u8d27\u5e01\u578b') != (-1))): ismonetary = True ct._write_head() nums = _get_nav_histroy_num(code, start, end, ismonetary) data = _parse_nav_history_data(code, start, end, nums, ismonetary, retry_count, pause, timeout) return data
[ "def", "get_nav_history", "(", "code", ",", "start", "=", "None", ",", "end", "=", "None", ",", "retry_count", "=", "3", ",", "pause", "=", "0.001", ",", "timeout", "=", "10", ")", ":", "start", "=", "(", "du", ".", "today_last_year", "(", ")", "if...
parameters code:string 基金代码 e .
train
false
50,918
def requestPdpContextActivation(AccessPointName_presence=0): a = TpPd(pd=8) b = MessageType(mesType=68) c = PacketDataProtocolAddress() packet = ((a / b) / c) if (AccessPointName_presence is 1): d = AccessPointName(ieiAPN=40) packet = (packet / d) return packet
[ "def", "requestPdpContextActivation", "(", "AccessPointName_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "8", ")", "b", "=", "MessageType", "(", "mesType", "=", "68", ")", "c", "=", "PacketDataProtocolAddress", "(", ")", "packet", "=", ...
request pdp context activation section 9 .
train
true
50,919
def _commoncrypto_pbkdf2(data, salt, iterations, digest, keylen): c_hashfunc = ctypes.c_uint32(_commoncrypto_hashlib_to_crypto_map_get(digest)) c_pass = ctypes.c_char_p(data) c_passlen = ctypes.c_size_t(len(data)) c_salt = ctypes.c_char_p(salt) c_saltlen = ctypes.c_size_t(len(salt)) c_iter = ctypes.c_uint(iterations) c_keylen = ctypes.c_size_t(keylen) c_buff = ctypes.create_string_buffer(keylen) crypto.CCKeyDerivationPBKDF.restype = ctypes.c_int crypto.CCKeyDerivationPBKDF.argtypes = [ctypes.c_uint32, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_uint32, ctypes.c_uint, ctypes.c_char_p, ctypes.c_size_t] ret = crypto.CCKeyDerivationPBKDF(2, c_pass, c_passlen, c_salt, c_saltlen, c_hashfunc, c_iter, c_buff, c_keylen) return ((1 - ret), c_buff)
[ "def", "_commoncrypto_pbkdf2", "(", "data", ",", "salt", ",", "iterations", ",", "digest", ",", "keylen", ")", ":", "c_hashfunc", "=", "ctypes", ".", "c_uint32", "(", "_commoncrypto_hashlib_to_crypto_map_get", "(", "digest", ")", ")", "c_pass", "=", "ctypes", ...
common crypto compatibile wrapper .
train
false
50,920
@step(u'a file named "{filename}" exists') def step_file_named_filename_exists(context, filename): step_file_named_filename_should_exist(context, filename)
[ "@", "step", "(", "u'a file named \"{filename}\" exists'", ")", "def", "step_file_named_filename_exists", "(", "context", ",", "filename", ")", ":", "step_file_named_filename_should_exist", "(", "context", ",", "filename", ")" ]
verifies that a file with this filename exists .
train
false
50,922
def app_factory(global_conf, **kwargs): kwargs = load_app_properties(kwds=kwargs, config_prefix='TOOL_SHED_CONFIG_') if ('app' in kwargs): app = kwargs.pop('app') else: try: from galaxy.webapps.tool_shed.app import UniverseApplication app = UniverseApplication(global_conf=global_conf, **kwargs) except: import traceback import sys traceback.print_exc() sys.exit(1) atexit.register(app.shutdown) webapp = CommunityWebApplication(app, session_cookie='galaxycommunitysession', name='tool_shed') add_ui_controllers(webapp, app) webapp.add_route('/view/{owner}', controller='repository', action='sharable_owner') webapp.add_route('/view/{owner}/{name}', controller='repository', action='sharable_repository') webapp.add_route('/view/{owner}/{name}/{changeset_revision}', controller='repository', action='sharable_repository_revision') webapp.add_route('/repository/static/images/{repository_id}/{image_file:.+?}', controller='repository', action='display_image_in_repository', repository_id=None, image_file=None) webapp.add_route('/{controller}/{action}', action='index') webapp.add_route('/{action}', controller='repository', action='index') webapp.add_route('/repos/*path_info', controller='hg', action='handle_request', path_info='/') webapp.add_api_controllers('galaxy.webapps.tool_shed.api', app) webapp.mapper.connect('api_key_retrieval', '/api/authenticate/baseauth/', controller='authenticate', action='get_tool_shed_api_key', conditions=dict(method=['GET'])) webapp.mapper.connect('group', '/api/groups/', controller='groups', action='index', conditions=dict(method=['GET'])) webapp.mapper.connect('group', '/api/groups/', controller='groups', action='create', conditions=dict(method=['POST'])) webapp.mapper.connect('group', '/api/groups/{encoded_id}', controller='groups', action='show', conditions=dict(method=['GET'])) webapp.mapper.resource('category', 'categories', controller='categories', name_prefix='category_', path_prefix='/api', parent_resources=dict(member_name='category', collection_name='categories')) webapp.mapper.connect('repositories_in_category', '/api/categories/{category_id}/repositories', controller='categories', action='get_repositories', conditions=dict(method=['GET'])) webapp.mapper.connect('show_updates_for_repository', '/api/repositories/updates', controller='repositories', action='updates', conditions=dict(method=['GET'])) webapp.mapper.resource('repository', 'repositories', controller='repositories', collection={'add_repository_registry_entry': 'POST', 'get_repository_revision_install_info': 'GET', 'get_ordered_installable_revisions': 'GET', 'get_installable_revisions': 'GET', 'remove_repository_registry_entry': 'POST', 'repository_ids_for_setting_metadata': 'GET', 'reset_metadata_on_repositories': 'POST', 'reset_metadata_on_repository': 'POST'}, name_prefix='repository_', path_prefix='/api', new={'import_capsule': 'POST'}, parent_resources=dict(member_name='repository', collection_name='repositories')) webapp.mapper.resource('repository_revision', 'repository_revisions', member={'repository_dependencies': 'GET', 'export': 'POST'}, controller='repository_revisions', name_prefix='repository_revision_', path_prefix='/api', parent_resources=dict(member_name='repository_revision', collection_name='repository_revisions')) webapp.mapper.resource('user', 'users', controller='users', name_prefix='user_', path_prefix='/api', parent_resources=dict(member_name='user', collection_name='users')) webapp.mapper.connect('update_repository', '/api/repositories/{id}', controller='repositories', action='update', conditions=dict(method=['PATCH', 'PUT'])) webapp.mapper.connect('repository_create_changeset_revision', '/api/repositories/{id}/changeset_revision', controller='repositories', action='create_changeset_revision', conditions=dict(method=['POST'])) webapp.mapper.connect('repository_get_metadata', '/api/repositories/{id}/metadata', controller='repositories', action='metadata', conditions=dict(method=['GET'])) webapp.mapper.connect('repository_show_tools', '/api/repositories/{id}/{changeset}/show_tools', controller='repositories', action='show_tools', conditions=dict(method=['GET'])) webapp.mapper.connect('create_repository', '/api/repositories', controller='repositories', action='create', conditions=dict(method=['POST'])) webapp.mapper.connect('tools', '/api/tools', controller='tools', action='index', conditions=dict(method=['GET'])) webapp.mapper.connect('version', '/api/version', controller='configuration', action='version', conditions=dict(method=['GET'])) webapp.finalize_config() if kwargs.get('middleware', True): webapp = wrap_in_middleware(webapp, global_conf, **kwargs) if asbool(kwargs.get('static_enabled', True)): if process_is_uwsgi: log.error('Static middleware is enabled in your configuration but this is a uwsgi process. Refusing to wrap in static middleware.') else: webapp = wrap_in_static(webapp, global_conf, **kwargs) try: galaxy.webapps.tool_shed.model.mapping.metadata.bind.dispose() except: log.exception('Unable to dispose of pooled tool_shed model database connections.') return webapp
[ "def", "app_factory", "(", "global_conf", ",", "**", "kwargs", ")", ":", "kwargs", "=", "load_app_properties", "(", "kwds", "=", "kwargs", ",", "config_prefix", "=", "'TOOL_SHED_CONFIG_'", ")", "if", "(", "'app'", "in", "kwargs", ")", ":", "app", "=", "kwa...
return a wsgi application serving the root object .
train
false
50,923
def scale_timedelta(context, builder, val, srcty, destty): factor = npdatetime.get_timedelta_conversion_factor(srcty.unit, destty.unit) if (factor is None): raise NotImplementedError(('cannot convert timedelta64 from %r to %r' % (srcty.unit, destty.unit))) return scale_by_constant(builder, val, factor)
[ "def", "scale_timedelta", "(", "context", ",", "builder", ",", "val", ",", "srcty", ",", "destty", ")", ":", "factor", "=", "npdatetime", ".", "get_timedelta_conversion_factor", "(", "srcty", ".", "unit", ",", "destty", ".", "unit", ")", "if", "(", "factor...
scale the timedelta64 *val* from *srcty* to *destty* .
train
false
50,925
def encode_hex_to_base32(hex_string): bin_form = binascii.unhexlify(hex_string) return base64.b32encode(bin_form)
[ "def", "encode_hex_to_base32", "(", "hex_string", ")", ":", "bin_form", "=", "binascii", ".", "unhexlify", "(", "hex_string", ")", "return", "base64", ".", "b32encode", "(", "bin_form", ")" ]
encodes hex to base32 bit as per rfc4648 .
train
false
50,926
def getStepKeyFromPoint(point): return (int(round(point.real)), int(round(point.imag)))
[ "def", "getStepKeyFromPoint", "(", "point", ")", ":", "return", "(", "int", "(", "round", "(", "point", ".", "real", ")", ")", ",", "int", "(", "round", "(", "point", ".", "imag", ")", ")", ")" ]
get step key for the point .
train
false
50,927
def test_issue_3825(): x = Symbol('x') y = Symbol('y') a1 = (x + y) a2 = (y + x) a2.is_comparable h1 = hash(a1) h2 = hash(a2) assert (h1 == h2)
[ "def", "test_issue_3825", "(", ")", ":", "x", "=", "Symbol", "(", "'x'", ")", "y", "=", "Symbol", "(", "'y'", ")", "a1", "=", "(", "x", "+", "y", ")", "a2", "=", "(", "y", "+", "x", ")", "a2", ".", "is_comparable", "h1", "=", "hash", "(", "...
catch: hash instability .
train
false
50,928
def send_login(): form_class = _security.passwordless_login_form if request.json: form = form_class(MultiDict(request.json)) else: form = form_class() if form.validate_on_submit(): send_login_instructions(form.user) if (request.json is None): do_flash(*get_message('LOGIN_EMAIL_SENT', email=form.user.email)) if request.json: return _render_json(form) return _security.render_template(config_value('SEND_LOGIN_TEMPLATE'), send_login_form=form, **_ctx('send_login'))
[ "def", "send_login", "(", ")", ":", "form_class", "=", "_security", ".", "passwordless_login_form", "if", "request", ".", "json", ":", "form", "=", "form_class", "(", "MultiDict", "(", "request", ".", "json", ")", ")", "else", ":", "form", "=", "form_class...
view function that sends login instructions for passwordless login .
train
true
50,929
def type_or_constraint_repr(constraint): if isinstance(constraint, type): return constraint.__name__ elif isinstance(constraint, Exactly): return repr(constraint)
[ "def", "type_or_constraint_repr", "(", "constraint", ")", ":", "if", "isinstance", "(", "constraint", ",", "type", ")", ":", "return", "constraint", ".", "__name__", "elif", "isinstance", "(", "constraint", ",", "Exactly", ")", ":", "return", "repr", "(", "c...
generate correct repr for types and typeconstraints .
train
false
50,931
def _expand_cookie_path(protocolinfo_response, pid_resolver, pid_resolution_arg): cookie_path = protocolinfo_response.cookie_path if (cookie_path and (not os.path.isabs(cookie_path))): try: tor_pid = pid_resolver(pid_resolution_arg) if (not tor_pid): raise IOError('pid lookup failed') tor_cwd = stem.util.system.cwd(tor_pid) if (not tor_cwd): raise IOError('cwd lookup failed') cookie_path = stem.util.system.expand_path(cookie_path, tor_cwd) except IOError as exc: resolver_labels = {stem.util.system.pid_by_name: ' by name', stem.util.system.pid_by_port: ' by port', stem.util.system.pid_by_open_file: ' by socket file'} pid_resolver_label = resolver_labels.get(pid_resolver, '') log.debug(('unable to expand relative tor cookie path%s: %s' % (pid_resolver_label, exc))) protocolinfo_response.cookie_path = cookie_path
[ "def", "_expand_cookie_path", "(", "protocolinfo_response", ",", "pid_resolver", ",", "pid_resolution_arg", ")", ":", "cookie_path", "=", "protocolinfo_response", ".", "cookie_path", "if", "(", "cookie_path", "and", "(", "not", "os", ".", "path", ".", "isabs", "("...
attempts to expand a relative cookie path with the given pid resolver .
train
false
50,932
def set2rel(s): new = set() for elem in s: if isinstance(elem, string_types): new.add((elem,)) elif isinstance(elem, int): new.add(str(elem)) else: new.add(elem) return new
[ "def", "set2rel", "(", "s", ")", ":", "new", "=", "set", "(", ")", "for", "elem", "in", "s", ":", "if", "isinstance", "(", "elem", ",", "string_types", ")", ":", "new", ".", "add", "(", "(", "elem", ",", ")", ")", "elif", "isinstance", "(", "el...
convert a set containing individuals into a set of unary tuples .
train
false
50,933
def test_gloo_without_app(): class DummyParser(gloo.glir.BaseGlirParser, ): def __init__(self): self.commands = [] def parse(self, commands): self.commands.extend(commands) p = DummyParser() c = gloo.context.FakeCanvas() c.context.shared.parser = p gloo.clear() c.flush() gloo.clear() c.flush() assert (len(p.commands) in (2, 3)) assert (p.commands[(-1)][1] == 'glClear')
[ "def", "test_gloo_without_app", "(", ")", ":", "class", "DummyParser", "(", "gloo", ".", "glir", ".", "BaseGlirParser", ",", ")", ":", "def", "__init__", "(", "self", ")", ":", "self", ".", "commands", "=", "[", "]", "def", "parse", "(", "self", ",", ...
test gloo without vispy .
train
false
50,935
def handle_extendsnode(extendsnode, context): if (BLOCK_CONTEXT_KEY not in context.render_context): context.render_context[BLOCK_CONTEXT_KEY] = BlockContext() block_context = context.render_context[BLOCK_CONTEXT_KEY] blocks = dict(((n.name, n) for n in extendsnode.nodelist.get_nodes_by_type(BlockNode))) block_context.add_blocks(blocks) compiled_parent = extendsnode.get_parent(context) parent_nodelist = compiled_parent.nodelist for node in parent_nodelist: if (not isinstance(node, TextNode)): if isinstance(node, ExtendsNode): return handle_extendsnode(node, context) break blocks = dict(((n.name, n) for n in parent_nodelist.get_nodes_by_type(BlockNode))) block_context.add_blocks(blocks) block_stack = [] new_nodelist = remove_block_nodes(parent_nodelist, block_stack, block_context) return new_nodelist
[ "def", "handle_extendsnode", "(", "extendsnode", ",", "context", ")", ":", "if", "(", "BLOCK_CONTEXT_KEY", "not", "in", "context", ".", "render_context", ")", ":", "context", ".", "render_context", "[", "BLOCK_CONTEXT_KEY", "]", "=", "BlockContext", "(", ")", ...
create a copy of node tree of a derived template replacing all blocks tags with the nodes of appropriate blocks .
train
false
50,936
def backward_eye(n): M = eye(n) for i in range(int((M.rows / 2))): M.row_swap((0 + i), ((M.rows - 1) - i)) return M
[ "def", "backward_eye", "(", "n", ")", ":", "M", "=", "eye", "(", "n", ")", "for", "i", "in", "range", "(", "int", "(", "(", "M", ".", "rows", "/", "2", ")", ")", ")", ":", "M", ".", "row_swap", "(", "(", "0", "+", "i", ")", ",", "(", "(...
returns the backward identity matrix of dimensions n x n .
train
false
50,937
def iterateLineGenerator(proto, gen): coll = _IteratorBuffer(proto.transport.writeSequence, gen) return proto.schedule(coll)
[ "def", "iterateLineGenerator", "(", "proto", ",", "gen", ")", ":", "coll", "=", "_IteratorBuffer", "(", "proto", ".", "transport", ".", "writeSequence", ",", "gen", ")", "return", "proto", ".", "schedule", "(", "coll", ")" ]
hook the given protocol instance up to the given iterator with an _iteratorbuffer and schedule the result to be exhausted via the protocol .
train
false
50,939
def _is_valid_shell(shell): if salt.utils.is_windows(): return True shells = '/etc/shells' available_shells = [] if os.path.exists(shells): try: with salt.utils.fopen(shells, 'r') as shell_fp: lines = shell_fp.read().splitlines() for line in lines: if line.startswith('#'): continue else: available_shells.append(line) except OSError: return True else: return None if (shell in available_shells): return True else: return False
[ "def", "_is_valid_shell", "(", "shell", ")", ":", "if", "salt", ".", "utils", ".", "is_windows", "(", ")", ":", "return", "True", "shells", "=", "'/etc/shells'", "available_shells", "=", "[", "]", "if", "os", ".", "path", ".", "exists", "(", "shells", ...
attempts to search for valid shells on a system and see if a given shell is in the list .
train
false
50,940
def iterate_attributes(cls): keys = dir(cls) for key in keys: for c in cls.__mro__: if (key in c.__dict__): (yield (key, c.__dict__[key])) break
[ "def", "iterate_attributes", "(", "cls", ")", ":", "keys", "=", "dir", "(", "cls", ")", "for", "key", "in", "keys", ":", "for", "c", "in", "cls", ".", "__mro__", ":", "if", "(", "key", "in", "c", ".", "__dict__", ")", ":", "(", "yield", "(", "k...
iterate all the keys and attributes associated with a class .
train
false
50,941
def windowview(folder, view=None): fsr = Carbon.File.FSRef(folder) folder_alias = fsr.FSNewAliasMinimal() if (view is None): return _getwindowview(folder_alias) return _setwindowview(folder_alias, view)
[ "def", "windowview", "(", "folder", ",", "view", "=", "None", ")", ":", "fsr", "=", "Carbon", ".", "File", ".", "FSRef", "(", "folder", ")", "folder_alias", "=", "fsr", ".", "FSNewAliasMinimal", "(", ")", "if", "(", "view", "is", "None", ")", ":", ...
windowview: set the view of the window for the folder .
train
false
50,942
def relative_recursive_glob(dirname, pattern): assert (pattern == '**') if dirname: (yield pattern[:0]) for relative_dir in _iter_relative_dirs(dirname): (yield relative_dir)
[ "def", "relative_recursive_glob", "(", "dirname", ",", "pattern", ")", ":", "assert", "(", "pattern", "==", "'**'", ")", "if", "dirname", ":", "(", "yield", "pattern", "[", ":", "0", "]", ")", "for", "relative_dir", "in", "_iter_relative_dirs", "(", "dirna...
recursive glob for one directory and all its subdirectories .
train
false
50,943
def suppress(action='ignore', **kwarg): return ((action,), kwarg)
[ "def", "suppress", "(", "action", "=", "'ignore'", ",", "**", "kwarg", ")", ":", "return", "(", "(", "action", ",", ")", ",", "kwarg", ")" ]
sets up the .
train
false
50,944
@skip('netstandard') def test_cp_19510(): import clr clr.AddReference('System.Xml') import System.Xml doc = System.Xml.XmlDocument() doc.LoadXml('<tag attr="value">Data</tag>') root = doc.SelectSingleNode('tag') AreEqual(root.Attributes['attr'].Name, 'attr')
[ "@", "skip", "(", "'netstandard'", ")", "def", "test_cp_19510", "(", ")", ":", "import", "clr", "clr", ".", "AddReference", "(", "'System.Xml'", ")", "import", "System", ".", "Xml", "doc", "=", "System", ".", "Xml", ".", "XmlDocument", "(", ")", "doc", ...
test indexing on .
train
false
50,945
def normcase(s): return s
[ "def", "normcase", "(", "s", ")", ":", "return", "s" ]
normalize case of pathname .
train
false
50,946
@decorators.memoize def _check_mdata_put(): return salt.utils.which('mdata-put')
[ "@", "decorators", ".", "memoize", "def", "_check_mdata_put", "(", ")", ":", "return", "salt", ".", "utils", ".", "which", "(", "'mdata-put'", ")" ]
looks to see if mdata-put is present on the system .
train
false
50,947
def HostNameValid(host): valid = False for attr in ['AF_INET', 'AF_INET6']: try: socket.inet_pton(socket.__getattribute__(attr), host) valid = True break except socket.error: pass if (not valid): if ((not host) or ((not DnsNameValid(host)) and (not ALPHA_RE.match(host)))): return False else: return True else: return True
[ "def", "HostNameValid", "(", "host", ")", ":", "valid", "=", "False", "for", "attr", "in", "[", "'AF_INET'", ",", "'AF_INET6'", "]", ":", "try", ":", "socket", ".", "inet_pton", "(", "socket", ".", "__getattribute__", "(", "attr", ")", ",", "host", ")"...
tests whether a string is a valid host-name .
train
false
50,948
def comparePosition(firstElement, secondElement): return cmp(firstElement._markpos, secondElement._markpos)
[ "def", "comparePosition", "(", "firstElement", ",", "secondElement", ")", ":", "return", "cmp", "(", "firstElement", ".", "_markpos", ",", "secondElement", ".", "_markpos", ")" ]
compare the two elements given by their position in the document or documents they were parsed from .
train
false
50,949
def is_ignorable_404(uri): return any((pattern.search(uri) for pattern in getattr(settings, 'IGNORABLE_404_URLS', ())))
[ "def", "is_ignorable_404", "(", "uri", ")", ":", "return", "any", "(", "(", "pattern", ".", "search", "(", "uri", ")", "for", "pattern", "in", "getattr", "(", "settings", ",", "'IGNORABLE_404_URLS'", ",", "(", ")", ")", ")", ")" ]
returns true if a 404 at the given url *shouldnt* notify the site managers .
train
false
50,950
def numericise(value, empty2zero=False, default_blank=''): if (value is not None): try: value = int(value) except ValueError: try: value = float(value) except ValueError: if (value == ''): if empty2zero: value = 0 else: value = default_blank return value
[ "def", "numericise", "(", "value", ",", "empty2zero", "=", "False", ",", "default_blank", "=", "''", ")", ":", "if", "(", "value", "is", "not", "None", ")", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "ValueError", ":", "try", ...
returns a value that depends on the input string: - float if input can be converted to float - integer if input can be converted to integer - zero if the input string is empty and empty2zero flag is set - the same input string .
train
true
50,951
def readBody(response): def cancel(deferred): '\n Cancel a L{readBody} call, close the connection to the HTTP server\n immediately, if it is still open.\n\n @param deferred: The cancelled L{defer.Deferred}.\n ' abort = getAbort() if (abort is not None): abort() d = defer.Deferred(cancel) protocol = _ReadBodyProtocol(response.code, response.phrase, d) def getAbort(): return getattr(protocol.transport, 'abortConnection', None) response.deliverBody(protocol) if ((protocol.transport is not None) and (getAbort() is None)): warnings.warn('Using readBody with a transport that does not have an abortConnection method', category=DeprecationWarning, stacklevel=2) return d
[ "def", "readBody", "(", "response", ")", ":", "def", "cancel", "(", "deferred", ")", ":", "abort", "=", "getAbort", "(", ")", "if", "(", "abort", "is", "not", "None", ")", ":", "abort", "(", ")", "d", "=", "defer", ".", "Deferred", "(", "cancel", ...
get the body of an l{iresponse} and return it as a byte string .
train
false
50,954
def _CheckFieldName(name): _ValidateString(name, 'name', MAXIMUM_FIELD_NAME_LENGTH) if (not re.match(_FIELD_NAME_PATTERN, name)): raise ValueError(('field name "%s" should match pattern: %s' % (name, _FIELD_NAME_PATTERN))) return name
[ "def", "_CheckFieldName", "(", "name", ")", ":", "_ValidateString", "(", "name", ",", "'name'", ",", "MAXIMUM_FIELD_NAME_LENGTH", ")", "if", "(", "not", "re", ".", "match", "(", "_FIELD_NAME_PATTERN", ",", "name", ")", ")", ":", "raise", "ValueError", "(", ...
checks field name is not too long and matches field name pattern .
train
false
50,957
def tstd(a, limits=None, inclusive=(True, True), axis=0, ddof=1): return np.sqrt(tvar(a, limits, inclusive, axis, ddof))
[ "def", "tstd", "(", "a", ",", "limits", "=", "None", ",", "inclusive", "=", "(", "True", ",", "True", ")", ",", "axis", "=", "0", ",", "ddof", "=", "1", ")", ":", "return", "np", ".", "sqrt", "(", "tvar", "(", "a", ",", "limits", ",", "inclus...
compute the trimmed sample standard deviation this function finds the sample standard deviation of given values .
train
false
50,959
def _encode_sk_name_entry(backend, attributes): stack = backend._lib.sk_X509_NAME_ENTRY_new_null() for attribute in attributes: name_entry = _encode_name_entry(backend, attribute) res = backend._lib.sk_X509_NAME_ENTRY_push(stack, name_entry) backend.openssl_assert((res == 1)) return stack
[ "def", "_encode_sk_name_entry", "(", "backend", ",", "attributes", ")", ":", "stack", "=", "backend", ".", "_lib", ".", "sk_X509_NAME_ENTRY_new_null", "(", ")", "for", "attribute", "in", "attributes", ":", "name_entry", "=", "_encode_name_entry", "(", "backend", ...
the sk_x50_name_entry created will not be gcd .
train
false
50,961
def test_ternary(method, prec, exp_range, restricted_range, itr, stat): if (method in TernaryRestricted): exp_range = restricted_range for op in all_ternary(prec, exp_range, itr): t = TestSet(method, op) try: if (not convert(t)): continue callfuncs(t) verify(t, stat) except VerifyError as err: log(err) if (not method.startswith('__')): for op in ternary_optarg(prec, exp_range, itr): t = TestSet(method, op) try: if (not convert(t)): continue callfuncs(t) verify(t, stat) except VerifyError as err: log(err)
[ "def", "test_ternary", "(", "method", ",", "prec", ",", "exp_range", ",", "restricted_range", ",", "itr", ",", "stat", ")", ":", "if", "(", "method", "in", "TernaryRestricted", ")", ":", "exp_range", "=", "restricted_range", "for", "op", "in", "all_ternary",...
iterate a ternary function through many test cases .
train
false
50,962
@click.command('nginx') @click.option('--yes', help='Yes to regeneration of nginx config file', default=False, is_flag=True) def setup_nginx(yes=False): from bench.config.nginx import make_nginx_conf make_nginx_conf(bench_path='.', yes=yes)
[ "@", "click", ".", "command", "(", "'nginx'", ")", "@", "click", ".", "option", "(", "'--yes'", ",", "help", "=", "'Yes to regeneration of nginx config file'", ",", "default", "=", "False", ",", "is_flag", "=", "True", ")", "def", "setup_nginx", "(", "yes", ...
generate config for nginx .
train
false
50,963
def getEngineFilename(): base_search_path = os.path.dirname(inspect.getfile(getEngineFilename)) search_filename = 'CuraEngine' if (platform.system() == 'Windows'): search_filename += '.exe' if (version.isDevVersion() and os.path.exists('C:/Software/Cura_SteamEngine/_bin/Release/Cura_SteamEngine.exe')): return 'C:/Software/Cura_SteamEngine/_bin/Release/Cura_SteamEngine.exe' for n in xrange(0, 10): full_filename = os.path.abspath(os.path.join(base_search_path, '/'.join((['..'] * n)), search_filename)) if os.path.isfile(full_filename): return full_filename full_filename = os.path.abspath(os.path.join(base_search_path, '/'.join((['..'] * n)), 'CuraEngine', search_filename)) if os.path.isfile(full_filename): return full_filename if os.path.isfile('/usr/bin/CuraEngine'): return '/usr/bin/CuraEngine' if os.path.isfile('/usr/local/bin/CuraEngine'): return '/usr/local/bin/CuraEngine' return ''
[ "def", "getEngineFilename", "(", ")", ":", "base_search_path", "=", "os", ".", "path", ".", "dirname", "(", "inspect", ".", "getfile", "(", "getEngineFilename", ")", ")", "search_filename", "=", "'CuraEngine'", "if", "(", "platform", ".", "system", "(", ")",...
finds and returns the path to the current engine executable .
train
false
50,965
def get_username(user_id): if (user_id == feconf.MIGRATION_BOT_USER_ID): return feconf.MIGRATION_BOT_USERNAME else: return get_user_settings(user_id, strict=True).username
[ "def", "get_username", "(", "user_id", ")", ":", "if", "(", "user_id", "==", "feconf", ".", "MIGRATION_BOT_USER_ID", ")", ":", "return", "feconf", ".", "MIGRATION_BOT_USERNAME", "else", ":", "return", "get_user_settings", "(", "user_id", ",", "strict", "=", "T...
gets username corresponding to the given user_id .
train
false
50,966
def _relevant(option): from certbot import renewal from certbot.plugins import disco as plugins_disco plugins = list(plugins_disco.PluginsRegistry.find_all()) return ((option in renewal.CONFIG_ITEMS) or any((option.startswith((x + '_')) for x in plugins)))
[ "def", "_relevant", "(", "option", ")", ":", "from", "certbot", "import", "renewal", "from", "certbot", ".", "plugins", "import", "disco", "as", "plugins_disco", "plugins", "=", "list", "(", "plugins_disco", ".", "PluginsRegistry", ".", "find_all", "(", ")", ...
is this option one that could be restored for future renewal purposes? .
train
false
50,967
def _ifconfig_getnode(): for args in ('', '-a', '-av'): mac = _find_mac('ifconfig', args, ['hwaddr', 'ether'], (lambda i: (i + 1))) if mac: return mac import socket ip_addr = socket.gethostbyname(socket.gethostname()) mac = _find_mac('arp', '-an', [ip_addr], (lambda i: (-1))) if mac: return mac mac = _find_mac('lanscan', '-ai', ['lan0'], (lambda i: 0)) if mac: return mac return None
[ "def", "_ifconfig_getnode", "(", ")", ":", "for", "args", "in", "(", "''", ",", "'-a'", ",", "'-av'", ")", ":", "mac", "=", "_find_mac", "(", "'ifconfig'", ",", "args", ",", "[", "'hwaddr'", ",", "'ether'", "]", ",", "(", "lambda", "i", ":", "(", ...
get the hardware address on unix by running ifconfig .
train
true
50,970
def isnull(obj): return _isnull(obj)
[ "def", "isnull", "(", "obj", ")", ":", "return", "_isnull", "(", "obj", ")" ]
detect missing values parameters arr : ndarray or object value object to check for null-ness returns isnulled : array-like of bool or bool array or bool indicating whether an object is null or if an array is given which of the element is null .
train
false
50,972
def is_port_trusted(port): return port['device_owner'].startswith(n_const.DEVICE_OWNER_NETWORK_PREFIX)
[ "def", "is_port_trusted", "(", "port", ")", ":", "return", "port", "[", "'device_owner'", "]", ".", "startswith", "(", "n_const", ".", "DEVICE_OWNER_NETWORK_PREFIX", ")" ]
used to determine if port can be trusted not to attack network .
train
false
50,973
def _guess_type(field): data_types = set([int, float]) if isinstance(field, (dict, list)): return 'nested' if isinstance(field, int): return 'int' if isinstance(field, float): return 'float' for data_type in list(data_types): try: data_type(field) except (TypeError, ValueError): data_types.discard(data_type) if (not data_types): break if (int in data_types): return 'integer' elif (float in data_types): return 'numeric' for format in _DATE_FORMATS: try: datetime.datetime.strptime(field, format) return 'timestamp' except (ValueError, TypeError): continue return 'text'
[ "def", "_guess_type", "(", "field", ")", ":", "data_types", "=", "set", "(", "[", "int", ",", "float", "]", ")", "if", "isinstance", "(", "field", ",", "(", "dict", ",", "list", ")", ")", ":", "return", "'nested'", "if", "isinstance", "(", "field", ...
simple guess type of field .
train
false
50,974
def post_clear_cache(func): @wraps(func) def post_clear_cache_if_not_raised(self, *args, **kwargs): rval = func(self, *args, **kwargs) self._delete_entries_cache() return rval return post_clear_cache_if_not_raised
[ "def", "post_clear_cache", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "post_clear_cache_if_not_raised", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "rval", "=", "func", "(", "self", ",", "*", "args", ",", "**", "k...
decorator for functions that alter the index using the git command .
train
true
50,976
@register.simple_tag def check_severity(check): try: return escape(CHECKS[check].severity) except KeyError: return u'info'
[ "@", "register", ".", "simple_tag", "def", "check_severity", "(", "check", ")", ":", "try", ":", "return", "escape", "(", "CHECKS", "[", "check", "]", ".", "severity", ")", "except", "KeyError", ":", "return", "u'info'" ]
returns check severity .
train
false
50,977
def _get_s3transfer_performance_script(script_name): s3transfer_directory = os.path.dirname(s3transfer.__file__) s3transfer_directory = os.path.dirname(s3transfer_directory) scripts_directory = 'scripts/performance' scripts_directory = os.path.join(s3transfer_directory, scripts_directory) script = os.path.join(scripts_directory, script_name) if os.path.isfile(script): return script else: return None
[ "def", "_get_s3transfer_performance_script", "(", "script_name", ")", ":", "s3transfer_directory", "=", "os", ".", "path", ".", "dirname", "(", "s3transfer", ".", "__file__", ")", "s3transfer_directory", "=", "os", ".", "path", ".", "dirname", "(", "s3transfer_dir...
retrieves an s3transfer performance script if available .
train
false
50,978
def bool_int(value): if isinstance(value, basestring): if (value.lower() in ('', '0', 'false', 'f', 'no', 'n', 'off')): value = 0 return int(bool(value))
[ "def", "bool_int", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "basestring", ")", ":", "if", "(", "value", ".", "lower", "(", ")", "in", "(", "''", ",", "'0'", ",", "'false'", ",", "'f'", ",", "'no'", ",", "'n'", ",", "'off'", ...
casts a config value into a 0 or 1 .
train
false
50,981
@pytest.mark.parametrize('specialchars', [' ', ' abcde ', ' ab cd', ' abcde', 'abcde ', ' a b c d e ', ' a b c d e ']) @pytest.mark.django_db def test_clean_specialchars_whitespace(specialchars): form_data = {'code': 'foo', 'fullname': 'Foo', 'checkstyle': 'foo', 'nplurals': '2', 'specialchars': specialchars} form = LanguageForm(form_data) assert form.is_valid() assert (' ' in form.cleaned_data['specialchars'])
[ "@", "pytest", ".", "mark", ".", "parametrize", "(", "'specialchars'", ",", "[", "' '", ",", "' abcde '", ",", "' ab cd'", ",", "' abcde'", ",", "'abcde '", ",", "' a b c d e '", ",", "' a b c d e '", "]", ")", "@", "pytest", ".", "mark", ".", "django_db",...
tests whitespace is accepted in special characters .
train
false
50,982
def relu__(x): return T.switch((x < 0.0), 0.0, x)
[ "def", "relu__", "(", "x", ")", ":", "return", "T", ".", "switch", "(", "(", "x", "<", "0.0", ")", ",", "0.0", ",", "x", ")" ]
alternative relu implementation .
train
false
50,983
@app.route('/auth/info/googlejwt', methods=['GET']) def auth_info_google_jwt(): return auth_info()
[ "@", "app", ".", "route", "(", "'/auth/info/googlejwt'", ",", "methods", "=", "[", "'GET'", "]", ")", "def", "auth_info_google_jwt", "(", ")", ":", "return", "auth_info", "(", ")" ]
auth info with google signed jwt .
train
false
50,984
def time_until(d, now=None, count=2, accuracy=6, simple=False): if (not now): now = datetime.datetime.now() return time_since(now, d, count, accuracy, simple)
[ "def", "time_until", "(", "d", ",", "now", "=", "None", ",", "count", "=", "2", ",", "accuracy", "=", "6", ",", "simple", "=", "False", ")", ":", "if", "(", "not", "now", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ...
like timesince .
train
false
50,986
def copy_weights(teacher_model, student_model, layer_names): for name in layer_names: weights = teacher_model.get_layer(name=name).get_weights() student_model.get_layer(name=name).set_weights(weights)
[ "def", "copy_weights", "(", "teacher_model", ",", "student_model", ",", "layer_names", ")", ":", "for", "name", "in", "layer_names", ":", "weights", "=", "teacher_model", ".", "get_layer", "(", "name", "=", "name", ")", ".", "get_weights", "(", ")", "student...
copy weights from teacher_model to student_model .
train
false
50,987
def logged_run_process(reactor, command): d = Deferred() action = TWISTED_CHILD_PROCESS_ACTION(command=command) with action.context(): d2 = DeferredContext(d) protocol = _LoggingProcessProtocol(d, action) reactor.spawnProcess(protocol, command[0], command) def process_ended((reason, output)): status = reason.value.status if status: raise _CalledProcessError(returncode=status, cmd=command, output=output) return _ProcessResult(command=command, status=status, output=output) d2.addCallback(process_ended) d2.addActionFinish() return d2.result
[ "def", "logged_run_process", "(", "reactor", ",", "command", ")", ":", "d", "=", "Deferred", "(", ")", "action", "=", "TWISTED_CHILD_PROCESS_ACTION", "(", "command", "=", "command", ")", "with", "action", ".", "context", "(", ")", ":", "d2", "=", "Deferred...
run a child process .
train
false
50,988
def _check_pil_jpeg_bytes(): from PIL import Image buf = BytesIO() img = Image.new('RGB', (4, 4)) try: img.save(buf, 'jpeg') except Exception as e: ename = e.__class__.__name__ raise SkipTest(("PIL can't write JPEG to BytesIO: %s: %s" % (ename, e)))
[ "def", "_check_pil_jpeg_bytes", "(", ")", ":", "from", "PIL", "import", "Image", "buf", "=", "BytesIO", "(", ")", "img", "=", "Image", ".", "new", "(", "'RGB'", ",", "(", "4", ",", "4", ")", ")", "try", ":", "img", ".", "save", "(", "buf", ",", ...
skip if pil cant write jpegs to bytesio objects .
train
false
50,989
def get_sd_configcheck(agentConfig, configs): print '\nSource of the configuration objects built by the agent:\n' for (check_name, config) in configs.iteritems(): print ('Check "%s":\n source --> %s\n config --> %s\n' % (check_name, config[0], config[1])) try: print_containers() except Exception: print 'Failed to collect containers info.' try: print_templates(agentConfig) except Exception: print 'Failed to collect configuration templates.'
[ "def", "get_sd_configcheck", "(", "agentConfig", ",", "configs", ")", ":", "print", "'\\nSource of the configuration objects built by the agent:\\n'", "for", "(", "check_name", ",", "config", ")", "in", "configs", ".", "iteritems", "(", ")", ":", "print", "(", "'Che...
trace how the configuration objects are loaded and from where .
train
false
50,990
@login_required def account_redirect(request): return redirect(u'profile_update')
[ "@", "login_required", "def", "account_redirect", "(", "request", ")", ":", "return", "redirect", "(", "u'profile_update'", ")" ]
just gives the url prefix for accounts an action - redirect to the profile update form .
train
false
50,992
def assert_type(name, obj, types, none_ok=True): if (obj is None): if none_ok: return True else: raise AssertionError(('%s may not be None' % name)) if (not isinstance(types, (tuple, list))): types = [types] for cls in types: if isinstance(obj, cls): return True allowed_types = '|'.join(map((lambda x: str(x)), types)) stack = traceback.extract_stack() stack_msg = ('Function call %s() in %s:%d' % (stack[(-2)][2], stack[(-3)][0], stack[(-3)][1])) type_msg = ('%s must be instance of %s (but is %s)' % (name, allowed_types, str(type(obj)))) raise AssertionError(((stack_msg + ': ') + type_msg))
[ "def", "assert_type", "(", "name", ",", "obj", ",", "types", ",", "none_ok", "=", "True", ")", ":", "if", "(", "obj", "is", "None", ")", ":", "if", "none_ok", ":", "return", "True", "else", ":", "raise", "AssertionError", "(", "(", "'%s may not be None...
assert that a parameter is of a given type .
train
false
50,994
def find_initrd(path): if (path is None): return None if os.path.isfile(path): return path elif os.path.isdir(path): return find_highest_files(path, 'initrd.img', _re_initrd) elif (file_is_remote(path) and remote_file_exists(path)): return path return None
[ "def", "find_initrd", "(", "path", ")", ":", "if", "(", "path", "is", "None", ")", ":", "return", "None", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "return", "path", "elif", "os", ".", "path", ".", "isdir", "(", "path", ")", ...
given a directory or a filename .
train
false
50,995
def _maybe_upcast(values, fill_value=np.nan, dtype=None, copy=False): if is_extension_type(values): if copy: values = values.copy() else: if (dtype is None): dtype = values.dtype (new_dtype, fill_value) = _maybe_promote(dtype, fill_value) if (new_dtype != values.dtype): values = values.astype(new_dtype) elif copy: values = values.copy() return (values, fill_value)
[ "def", "_maybe_upcast", "(", "values", ",", "fill_value", "=", "np", ".", "nan", ",", "dtype", "=", "None", ",", "copy", "=", "False", ")", ":", "if", "is_extension_type", "(", "values", ")", ":", "if", "copy", ":", "values", "=", "values", ".", "cop...
provide explict type promotion and coercion parameters values : the ndarray that we want to maybe upcast fill_value : what we want to fill with dtype : if none .
train
false
50,996
def read(results_file): results = {} if (not os.path.exists(results_file)): raise IOError('Results file does not exist.') with open(results_file) as handle: lines = handle.readlines() (results, num_params) = _parse_baseml.parse_basics(lines, results) results = _parse_baseml.parse_parameters(lines, results, num_params) if (results.get('version') is None): raise ValueError('Invalid results file') return results
[ "def", "read", "(", "results_file", ")", ":", "results", "=", "{", "}", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "results_file", ")", ")", ":", "raise", "IOError", "(", "'Results file does not exist.'", ")", "with", "open", "(", "results_...
parses an xml file from the ncbi entrez utilities into python objects .
train
false
50,997
def all_subindices(index): return (index[start:stop] for (start, stop) in product_upper_triangle(range((len(index) + 1))))
[ "def", "all_subindices", "(", "index", ")", ":", "return", "(", "index", "[", "start", ":", "stop", "]", "for", "(", "start", ",", "stop", ")", "in", "product_upper_triangle", "(", "range", "(", "(", "len", "(", "index", ")", "+", "1", ")", ")", ")...
return all valid sub-indices of a pandas index .
train
false
51,001
@contextlib.contextmanager def with_comprehensive_theme_context(theme=None): if theme: domain = '{theme}.org'.format(theme=re.sub('\\.org$', '', theme)) (site, __) = Site.objects.get_or_create(domain=domain, name=theme) (site_theme, __) = SiteTheme.objects.get_or_create(site=site, theme_dir_name=theme) with patch('openedx.core.djangoapps.theming.helpers.get_current_site_theme', return_value=site_theme): with patch('openedx.core.djangoapps.theming.helpers.get_current_site', return_value=site): (yield) else: (yield)
[ "@", "contextlib", ".", "contextmanager", "def", "with_comprehensive_theme_context", "(", "theme", "=", "None", ")", ":", "if", "theme", ":", "domain", "=", "'{theme}.org'", ".", "format", "(", "theme", "=", "re", ".", "sub", "(", "'\\\\.org$'", ",", "''", ...
a function to run a test as if request was made to the given theme .
train
false
51,002
def generate_tool_guid(repository_clone_url, tool): tmp_url = common_util.remove_protocol_and_user_from_clone_url(repository_clone_url) return ('%s/%s/%s' % (tmp_url, tool.id, tool.version))
[ "def", "generate_tool_guid", "(", "repository_clone_url", ",", "tool", ")", ":", "tmp_url", "=", "common_util", ".", "remove_protocol_and_user_from_clone_url", "(", "repository_clone_url", ")", "return", "(", "'%s/%s/%s'", "%", "(", "tmp_url", ",", "tool", ".", "id"...
generate a guid for the installed tool .
train
false
51,003
def vectorize_if_needed(func, *x): if any(map(isiterable, x)): return np.vectorize(func)(*x) else: return func(*x)
[ "def", "vectorize_if_needed", "(", "func", ",", "*", "x", ")", ":", "if", "any", "(", "map", "(", "isiterable", ",", "x", ")", ")", ":", "return", "np", ".", "vectorize", "(", "func", ")", "(", "*", "x", ")", "else", ":", "return", "func", "(", ...
helper function to vectorize functions on array inputs .
train
false
51,007
def create_hash_map(): hashmap = {} from base64 import encodestring as base64 import pwd login_name = pwd.getpwuid(os.geteuid())[0] conn = http.client.HTTPSConnection(u'api.github.com') conn.request(u'GET', u'/repos/nipy/nipype', headers={u'Authorization': (u'Basic %s' % base64(login_name))}) try: conn.request(u'GET', u'/repos/nipy/nipype/git/trees/master?recursive=1') except: pass else: r1 = conn.getresponse() if (r1.reason != u'OK'): raise Exception((u'HTTP Response %s:%s' % (r1.status, r1.reason))) payload = simplejson.loads(r1.read()) for infodict in payload[u'tree']: if (infodict[u'type'] == u'blob'): hashmap[infodict[u'sha']] = infodict[u'path'] return hashmap
[ "def", "create_hash_map", "(", ")", ":", "hashmap", "=", "{", "}", "from", "base64", "import", "encodestring", "as", "base64", "import", "pwd", "login_name", "=", "pwd", ".", "getpwuid", "(", "os", ".", "geteuid", "(", ")", ")", "[", "0", "]", "conn", ...
create a hash map for all objects .
train
false
51,008
def getVector3ByMultiplierPrefix(elementNode, multiplier, prefix, vector3): if (multiplier == 0.0): return vector3 oldMultipliedValueVector3 = (vector3 * multiplier) vector3ByPrefix = getVector3ByPrefix(oldMultipliedValueVector3.copy(), elementNode, prefix) if (vector3ByPrefix == oldMultipliedValueVector3): return vector3 return (vector3ByPrefix / multiplier)
[ "def", "getVector3ByMultiplierPrefix", "(", "elementNode", ",", "multiplier", ",", "prefix", ",", "vector3", ")", ":", "if", "(", "multiplier", "==", "0.0", ")", ":", "return", "vector3", "oldMultipliedValueVector3", "=", "(", "vector3", "*", "multiplier", ")", ...
get vector3 from multiplier .
train
false
51,009
@box(types.RawPointer) def box_raw_pointer(typ, val, c): ll_intp = c.context.get_value_type(types.uintp) addr = c.builder.ptrtoint(val, ll_intp) return c.box(types.uintp, addr)
[ "@", "box", "(", "types", ".", "RawPointer", ")", "def", "box_raw_pointer", "(", "typ", ",", "val", ",", "c", ")", ":", "ll_intp", "=", "c", ".", "context", ".", "get_value_type", "(", "types", ".", "uintp", ")", "addr", "=", "c", ".", "builder", "...
convert a raw pointer to a python int .
train
false
51,010
def add_imap_status_info_rows(folder_id, account_id, db_session): if (not db_session.query(ImapFolderSyncStatus).filter_by(account_id=account_id, folder_id=folder_id).all()): db_session.add(ImapFolderSyncStatus(account_id=account_id, folder_id=folder_id, state='initial')) if (not db_session.query(ImapFolderInfo).filter_by(account_id=account_id, folder_id=folder_id).all()): db_session.add(ImapFolderInfo(account_id=account_id, folder_id=folder_id, uidvalidity=1, highestmodseq=22))
[ "def", "add_imap_status_info_rows", "(", "folder_id", ",", "account_id", ",", "db_session", ")", ":", "if", "(", "not", "db_session", ".", "query", "(", "ImapFolderSyncStatus", ")", ".", "filter_by", "(", "account_id", "=", "account_id", ",", "folder_id", "=", ...
add placeholder imapfoldersyncstatus and imapfolderinfo rows for this folder_id if none exist .
train
false
51,011
def do_get_current_language_bidi(parser, token): args = token.contents.split() if ((len(args) != 3) or (args[1] != 'as')): raise TemplateSyntaxError(("'get_current_language_bidi' requires 'as variable' (got %r)" % args)) return GetCurrentLanguageBidiNode(args[2])
[ "def", "do_get_current_language_bidi", "(", "parser", ",", "token", ")", ":", "args", "=", "token", ".", "contents", ".", "split", "(", ")", "if", "(", "(", "len", "(", "args", ")", "!=", "3", ")", "or", "(", "args", "[", "1", "]", "!=", "'as'", ...
this will store the current language layout in the context .
train
false
51,012
def RunTest(name, handler): test_path = os.path.join(_module_dir, (name + '.py')) try: x = __LoadModule(test_path, name) for test in x.List(): test_object = eval(('x.%s(handler)' % test)) if (test_object.Enabled() and (not test_object.Test())): return False except BaseException as e: print(("Couldn't load test %s: %s" % (name, str(e)))) return True
[ "def", "RunTest", "(", "name", ",", "handler", ")", ":", "test_path", "=", "os", ".", "path", ".", "join", "(", "_module_dir", ",", "(", "name", "+", "'.py'", ")", ")", "try", ":", "x", "=", "__LoadModule", "(", "test_path", ",", "name", ")", "for"...
run a single test .
train
false
51,013
def wait_for_read(socks, timeout=None): return _wait_for_io_events(socks, EVENT_READ, timeout)
[ "def", "wait_for_read", "(", "socks", ",", "timeout", "=", "None", ")", ":", "return", "_wait_for_io_events", "(", "socks", ",", "EVENT_READ", ",", "timeout", ")" ]
waits for reading to be available from a list of sockets or optionally a single socket if passed in .
train
false
51,014
@FileSystem.in_directory(current_directory, 'django', 'brocolis') def test_harvest_with_debug_mode_enabled(): for option in ['-d', '--debug-mode']: (status, out) = run_scenario('leaves', 'enabled', **{option: None}) assert_equals(status, 0, out)
[ "@", "FileSystem", ".", "in_directory", "(", "current_directory", ",", "'django'", ",", "'brocolis'", ")", "def", "test_harvest_with_debug_mode_enabled", "(", ")", ":", "for", "option", "in", "[", "'-d'", ",", "'--debug-mode'", "]", ":", "(", "status", ",", "o...
python manage .
train
false
51,015
def _set_concurrent_future_state(concurr, source): assert source.done() if source.cancelled(): concurr.cancel() if (not concurr.set_running_or_notify_cancel()): return exception = source.exception() if (exception is not None): concurr.set_exception(exception) else: result = source.result() concurr.set_result(result)
[ "def", "_set_concurrent_future_state", "(", "concurr", ",", "source", ")", ":", "assert", "source", ".", "done", "(", ")", "if", "source", ".", "cancelled", "(", ")", ":", "concurr", ".", "cancel", "(", ")", "if", "(", "not", "concurr", ".", "set_running...
copy state from a future to a concurrent .
train
false
51,016
def create_trigger_type_db(trigger_type): trigger_type_api = TriggerTypeAPI(**trigger_type) trigger_type_api.validate() ref = ResourceReference.to_string_reference(name=trigger_type_api.name, pack=trigger_type_api.pack) trigger_type_db = get_trigger_type_db(ref) if (not trigger_type_db): trigger_type_db = TriggerTypeAPI.to_model(trigger_type_api) LOG.debug('verified trigger and formulated TriggerDB=%s', trigger_type_db) trigger_type_db = TriggerType.add_or_update(trigger_type_db) return trigger_type_db
[ "def", "create_trigger_type_db", "(", "trigger_type", ")", ":", "trigger_type_api", "=", "TriggerTypeAPI", "(", "**", "trigger_type", ")", "trigger_type_api", ".", "validate", "(", ")", "ref", "=", "ResourceReference", ".", "to_string_reference", "(", "name", "=", ...
creates a trigger type db object in the db given trigger_type definition as dict .
train
false
51,018
def urljoin_bytes(*atoms): url = ntob('/').join([x for x in atoms if x]) while (ntob('//') in url): url = url.replace(ntob('//'), ntob('/')) return (url or ntob('/'))
[ "def", "urljoin_bytes", "(", "*", "atoms", ")", ":", "url", "=", "ntob", "(", "'/'", ")", ".", "join", "(", "[", "x", "for", "x", "in", "atoms", "if", "x", "]", ")", "while", "(", "ntob", "(", "'//'", ")", "in", "url", ")", ":", "url", "=", ...
return the given path *atoms .
train
false
51,020
def is_linux(): return sys.platform.startswith(u'linux')
[ "def", "is_linux", "(", ")", ":", "return", "sys", ".", "platform", ".", "startswith", "(", "u'linux'", ")" ]
is this a linux machine? .
train
false
51,022
def pportInAcknowledge(): if (port.DlPortReadPortUchar(statusRegAdrs) & 64): return 1 else: return 0
[ "def", "pportInAcknowledge", "(", ")", ":", "if", "(", "port", ".", "DlPortReadPortUchar", "(", "statusRegAdrs", ")", "&", "64", ")", ":", "return", "1", "else", ":", "return", "0" ]
input from acknowledge pin .
train
false
51,023
def pointbiserialr(x, y): (rpb, prob) = pearsonr(x, y) return PointbiserialrResult(rpb, prob)
[ "def", "pointbiserialr", "(", "x", ",", "y", ")", ":", "(", "rpb", ",", "prob", ")", "=", "pearsonr", "(", "x", ",", "y", ")", "return", "PointbiserialrResult", "(", "rpb", ",", "prob", ")" ]
calculates a point biserial correlation coefficient and its p-value .
train
false
51,024
def floating_ip_get_by_fixed_ip_id(context, fixed_ip_id): return IMPL.floating_ip_get_by_fixed_ip_id(context, fixed_ip_id)
[ "def", "floating_ip_get_by_fixed_ip_id", "(", "context", ",", "fixed_ip_id", ")", ":", "return", "IMPL", ".", "floating_ip_get_by_fixed_ip_id", "(", "context", ",", "fixed_ip_id", ")" ]
get a floating ips by fixed address .
train
false
51,025
def DisableInterfaces(interface): set_tested_versions = ['vista', '2008'] set_args = ['/c', 'netsh', 'set', 'interface', interface, 'DISABLED'] host_version = platform.platform().lower() for version in set_tested_versions: if (host_version.find(version) != (-1)): res = client_utils_common.Execute('cmd', set_args, time_limit=(-1), bypass_whitelist=True) return res return ('', 'Command not available for this version.', 99, '')
[ "def", "DisableInterfaces", "(", "interface", ")", ":", "set_tested_versions", "=", "[", "'vista'", ",", "'2008'", "]", "set_args", "=", "[", "'/c'", ",", "'netsh'", ",", "'set'", ",", "'interface'", ",", "interface", ",", "'DISABLED'", "]", "host_version", ...
tries to disable an interface .
train
true
51,026
def versionToUsefulObject(version): from incremental import Version return Version(*[x.value for x in version.asList()[1:] if x])
[ "def", "versionToUsefulObject", "(", "version", ")", ":", "from", "incremental", "import", "Version", "return", "Version", "(", "*", "[", "x", ".", "value", "for", "x", "in", "version", ".", "asList", "(", ")", "[", "1", ":", "]", "if", "x", "]", ")"...
change an ast c{version()} to a real one .
train
false
51,027
def _get_pkg_license(pkg): licenses = set() cpr = '/usr/share/doc/{0}/copyright'.format(pkg) if os.path.exists(cpr): with salt.utils.fopen(cpr) as fp_: for line in fp_.read().split(os.linesep): if line.startswith('License:'): licenses.add(line.split(':', 1)[1].strip()) return ', '.join(sorted(licenses))
[ "def", "_get_pkg_license", "(", "pkg", ")", ":", "licenses", "=", "set", "(", ")", "cpr", "=", "'/usr/share/doc/{0}/copyright'", ".", "format", "(", "pkg", ")", "if", "os", ".", "path", ".", "exists", "(", "cpr", ")", ":", "with", "salt", ".", "utils",...
try to get a license from the package .
train
true
51,028
def api_payload_to_create_params(payload): required_parameters = ['collection_type', 'element_identifiers'] missing_parameters = [p for p in required_parameters if (p not in payload)] if missing_parameters: message = ('Missing required parameters %s' % missing_parameters) raise exceptions.ObjectAttributeMissingException(message) params = dict(collection_type=payload.get('collection_type'), element_identifiers=payload.get('element_identifiers'), name=payload.get('name', None)) return params
[ "def", "api_payload_to_create_params", "(", "payload", ")", ":", "required_parameters", "=", "[", "'collection_type'", ",", "'element_identifiers'", "]", "missing_parameters", "=", "[", "p", "for", "p", "in", "required_parameters", "if", "(", "p", "not", "in", "pa...
cleanup api payload to pass into dataset_collections .
train
false
51,029
def test_lazy_process(): t = tempfile.NamedTemporaryFile() os.remove(t.name) lazy_process = LazyProcess(['bash', '-c', ('touch %s; sleep 100' % t.name)]) assert (not os.path.exists(t.name)) lazy_process.start_process() while (not os.path.exists(t.name)): time.sleep(0.01) assert (lazy_process.process.poll() is None) lazy_process.shutdown() ret_val = None for i in range(10): ret_val = lazy_process.process.poll() if (ret_val is not None): break time.sleep(0.01) assert (ret_val is not None)
[ "def", "test_lazy_process", "(", ")", ":", "t", "=", "tempfile", ".", "NamedTemporaryFile", "(", ")", "os", ".", "remove", "(", "t", ".", "name", ")", "lazy_process", "=", "LazyProcess", "(", "[", "'bash'", ",", "'-c'", ",", "(", "'touch %s; sleep 100'", ...
create process .
train
false