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
28,102
def re_rsearch(pattern, text, chunk_size=1024): def _chunk_iter(): offset = len(text) while True: offset -= (chunk_size * 1024) if (offset <= 0): break (yield (text[offset:], offset)) (yield (text, 0)) pattern = (re.compile(pattern) if isinstance(pattern, basestring) else pattern) for (chunk, offset) in _chunk_iter(): matches = [match for match in pattern.finditer(chunk)] if matches: return ((offset + matches[(-1)].span()[0]), (offset + matches[(-1)].span()[1])) return None
[ "def", "re_rsearch", "(", "pattern", ",", "text", ",", "chunk_size", "=", "1024", ")", ":", "def", "_chunk_iter", "(", ")", ":", "offset", "=", "len", "(", "text", ")", "while", "True", ":", "offset", "-=", "(", "chunk_size", "*", "1024", ")", "if", ...
this function does a reverse search in a text using a regular expression given in the attribute pattern .
train
false
28,103
def isSane(totalLen, payloadLen, flags): def isFine(length): '\n Check if the given length is fine.\n ' return (True if (0 <= length <= const.MPU) else False) validFlags = [const.FLAG_PAYLOAD, const.FLAG_NEW_TICKET, const.FLAG_PRNG_SEED] return (isFine(totalLen) and isFine(payloadLen) and (totalLen >= payloadLen) and (flags in validFlags))
[ "def", "isSane", "(", "totalLen", ",", "payloadLen", ",", "flags", ")", ":", "def", "isFine", "(", "length", ")", ":", "return", "(", "True", "if", "(", "0", "<=", "length", "<=", "const", ".", "MPU", ")", "else", "False", ")", "validFlags", "=", "...
verifies whether the given header fields are sane .
train
false
28,105
def read_custom_metric(client, project_id, now_rfc3339, color, size): labels = ['{}/color=={}'.format(CUSTOM_METRIC_DOMAIN, color), '{}/size=={}'.format(CUSTOM_METRIC_DOMAIN, size)] request = client.timeseries().list(project=project_id, metric=CUSTOM_METRIC_NAME, youngest=now_rfc3339, labels=labels) start = time.time() while True: try: response = request.execute() for point in response['timeseries'][0]['points']: print '{}: {}'.format(point['end'], point['int64Value']) break except Exception as e: if (time.time() < (start + 20)): print 'Failed to read custom metric data, retrying...' time.sleep(3) else: print 'Failed to read custom metric data, aborting: exception={}'.format(e) raise
[ "def", "read_custom_metric", "(", "client", ",", "project_id", ",", "now_rfc3339", ",", "color", ",", "size", ")", ":", "labels", "=", "[", "'{}/color=={}'", ".", "format", "(", "CUSTOM_METRIC_DOMAIN", ",", "color", ")", ",", "'{}/size=={}'", ".", "format", ...
read all the timeseries data points for a given set of label values .
train
false
28,106
def lu_factor(a, overwrite_a=False, check_finite=True): if check_finite: a1 = asarray_chkfinite(a) else: a1 = asarray(a) if ((len(a1.shape) != 2) or (a1.shape[0] != a1.shape[1])): raise ValueError('expected square matrix') overwrite_a = (overwrite_a or _datacopied(a1, a)) (getrf,) = get_lapack_funcs(('getrf',), (a1,)) (lu, piv, info) = getrf(a1, overwrite_a=overwrite_a) if (info < 0): raise ValueError(('illegal value in %d-th argument of internal getrf (lu_factor)' % (- info))) if (info > 0): warn(('Diagonal number %d is exactly zero. Singular matrix.' % info), RuntimeWarning) return (lu, piv)
[ "def", "lu_factor", "(", "a", ",", "overwrite_a", "=", "False", ",", "check_finite", "=", "True", ")", ":", "if", "check_finite", ":", "a1", "=", "asarray_chkfinite", "(", "a", ")", "else", ":", "a1", "=", "asarray", "(", "a", ")", "if", "(", "(", ...
compute pivoted lu decomposition of a matrix .
train
false
28,107
@testing.requires_testing_data @requires_mayavi def test_fiducials_source(): from mne.gui._file_traits import FiducialsSource fid = FiducialsSource() fid.file = fid_path points = array([[(-0.08061612), (-0.02908875), (-0.04131077)], [0.00146763, 0.08506715, (-0.03483611)], [0.08436285, (-0.02850276), (-0.04127743)]]) assert_allclose(fid.points, points, 1e-06) fid.file = '' assert_equal(fid.points, None)
[ "@", "testing", ".", "requires_testing_data", "@", "requires_mayavi", "def", "test_fiducials_source", "(", ")", ":", "from", "mne", ".", "gui", ".", "_file_traits", "import", "FiducialsSource", "fid", "=", "FiducialsSource", "(", ")", "fid", ".", "file", "=", ...
test fiducialssource .
train
false
28,108
def file_browser(request, path='/'): directories = DojoFileStore(path, dirsonly=False, root=request.GET.get('root', '/')).items() context = directories content = json.dumps(context) return HttpResponse(content, content_type='application/json')
[ "def", "file_browser", "(", "request", ",", "path", "=", "'/'", ")", ":", "directories", "=", "DojoFileStore", "(", "path", ",", "dirsonly", "=", "False", ",", "root", "=", "request", ".", "GET", ".", "get", "(", "'root'", ",", "'/'", ")", ")", ".", ...
this view provides the ajax driven directory browser callback .
train
false
28,109
def _parse_openssl_req(csr_filename): if (not salt.utils.which('openssl')): raise salt.exceptions.SaltInvocationError('openssl binary not found in path') cmd = 'openssl req -text -noout -in {0}'.format(csr_filename) output = __salt__['cmd.run_stdout'](cmd) output = re.sub(': rsaEncryption', ':', output) output = re.sub('[0-9a-f]{2}:', '', output) return yaml.safe_load(output)
[ "def", "_parse_openssl_req", "(", "csr_filename", ")", ":", "if", "(", "not", "salt", ".", "utils", ".", "which", "(", "'openssl'", ")", ")", ":", "raise", "salt", ".", "exceptions", ".", "SaltInvocationError", "(", "'openssl binary not found in path'", ")", "...
parses openssl command line output .
train
false
28,110
def nameservers(): with settings(hide('running', 'stdout')): res = run("cat /etc/resolv.conf | grep 'nameserver' | cut -d\\ -f2") return res.splitlines()
[ "def", "nameservers", "(", ")", ":", "with", "settings", "(", "hide", "(", "'running'", ",", "'stdout'", ")", ")", ":", "res", "=", "run", "(", "\"cat /etc/resolv.conf | grep 'nameserver' | cut -d\\\\ -f2\"", ")", "return", "res", ".", "splitlines", "(", ")" ]
get the list of nameserver addresses .
train
false
28,112
def is_transparent(image): if (not isinstance(image, Image.Image)): return False return ((image.mode in ('RGBA', 'LA')) or ((image.mode == 'P') and ('transparency' in image.info)))
[ "def", "is_transparent", "(", "image", ")", ":", "if", "(", "not", "isinstance", "(", "image", ",", "Image", ".", "Image", ")", ")", ":", "return", "False", "return", "(", "(", "image", ".", "mode", "in", "(", "'RGBA'", ",", "'LA'", ")", ")", "or",...
check to see if an image is transparent .
train
true
28,113
def get_mod_names(filename): directory = filename if file_exists(filename): directory = get_directory_name(filename) else: raise Exception(('%s does not exist!' % str(filename))) ret_val = [x.rsplit('.py')[0] for x in os.listdir(directory) if ((x.endswith('.py') or ('.' not in x)) and (x.lower() != '__init__.py'))] return ret_val
[ "def", "get_mod_names", "(", "filename", ")", ":", "directory", "=", "filename", "if", "file_exists", "(", "filename", ")", ":", "directory", "=", "get_directory_name", "(", "filename", ")", "else", ":", "raise", "Exception", "(", "(", "'%s does not exist!'", ...
returns a list of all python modules and subpackages in the same location as filename w/o their " .
train
false
28,115
def get_es(hosts=None, timeout=None, **settings): hosts = (hosts or getattr(dj_settings, 'ES_HOSTS', DEFAULT_HOSTS)) timeout = (timeout if (timeout is not None) else getattr(dj_settings, 'ES_TIMEOUT', DEFAULT_TIMEOUT)) return Elasticsearch(hosts, timeout=timeout, **settings)
[ "def", "get_es", "(", "hosts", "=", "None", ",", "timeout", "=", "None", ",", "**", "settings", ")", ":", "hosts", "=", "(", "hosts", "or", "getattr", "(", "dj_settings", ",", "'ES_HOSTS'", ",", "DEFAULT_HOSTS", ")", ")", "timeout", "=", "(", "timeout"...
create an es object and return it .
train
false
28,116
def valid_ipv6(address): return (IPV6_PATTERN.match(address) is not None)
[ "def", "valid_ipv6", "(", "address", ")", ":", "return", "(", "IPV6_PATTERN", ".", "match", "(", "address", ")", "is", "not", "None", ")" ]
validates ipv6 addresses .
train
false
28,118
def user_flags(request, username, slug, template_name='flagging/flag_list.html'): user = get_object_or_404(User, username=username) flag_type = get_object_or_404(FlagType, slug=slug) flag_list = Flag.objects.filter(user=user, flag_type=flag_type) return render_to_response(template_name, {'person': user, 'flag_type': flag_type, 'flag_list': flag_list}, context_instance=RequestContext(request))
[ "def", "user_flags", "(", "request", ",", "username", ",", "slug", ",", "template_name", "=", "'flagging/flag_list.html'", ")", ":", "user", "=", "get_object_or_404", "(", "User", ",", "username", "=", "username", ")", "flag_type", "=", "get_object_or_404", "(",...
returns a list of flagged items for a particular user .
train
false
28,119
def _send_batch_emails(recipient_list, feedback_message_reference, exploration_id, has_suggestion): can_users_receive_email = email_manager.can_users_receive_thread_email(recipient_list, exploration_id, has_suggestion) for (index, recipient_id) in enumerate(recipient_list): if can_users_receive_email[index]: transaction_services.run_in_transaction(_add_feedback_message_reference, recipient_id, feedback_message_reference)
[ "def", "_send_batch_emails", "(", "recipient_list", ",", "feedback_message_reference", ",", "exploration_id", ",", "has_suggestion", ")", ":", "can_users_receive_email", "=", "email_manager", ".", "can_users_receive_thread_email", "(", "recipient_list", ",", "exploration_id",...
adds the given feedbackmessagereference to each of the recipients email buffers .
train
false
28,121
def bumperize(video): video.bumper = {'enabled': False, 'edx_video_id': '', 'transcripts': {}, 'metadata': None} if (not is_bumper_enabled(video)): return bumper_settings = get_bumper_settings(video) try: video.bumper['edx_video_id'] = bumper_settings['video_id'] video.bumper['transcripts'] = bumper_settings['transcripts'] except (TypeError, KeyError): log.warning('Could not retrieve video bumper information from course settings') return sources = get_bumper_sources(video) if (not sources): return video.bumper.update({'metadata': bumper_metadata(video, sources), 'enabled': True})
[ "def", "bumperize", "(", "video", ")", ":", "video", ".", "bumper", "=", "{", "'enabled'", ":", "False", ",", "'edx_video_id'", ":", "''", ",", "'transcripts'", ":", "{", "}", ",", "'metadata'", ":", "None", "}", "if", "(", "not", "is_bumper_enabled", ...
populate video with bumper settings .
train
false
28,122
def check_identity(identity, error_msg): email_start = identity.find('<') email_end = identity.find('>') if ((email_start < 0) or (email_end < 0) or (email_end <= email_start) or (identity.find('<', (email_start + 1)) >= 0) or (identity.find('>', (email_end + 1)) >= 0) or (not identity.endswith('>'))): raise ObjectFormatException(error_msg)
[ "def", "check_identity", "(", "identity", ",", "error_msg", ")", ":", "email_start", "=", "identity", ".", "find", "(", "'<'", ")", "email_end", "=", "identity", ".", "find", "(", "'>'", ")", "if", "(", "(", "email_start", "<", "0", ")", "or", "(", "...
check if the specified identity is valid .
train
false
28,124
def insured(pool, fun, args, kwargs, errback=None, on_revive=None, **opts): errback = (errback or _ensure_errback) with pool.acquire(block=True) as conn: conn.ensure_connection(errback=errback) channel = conn.default_channel revive = partial(revive_connection, conn, on_revive=on_revive) insured = conn.autoretry(fun, channel, errback=errback, on_revive=revive, **opts) (retval, _) = insured(*args, **dict(kwargs, connection=conn)) return retval
[ "def", "insured", "(", "pool", ",", "fun", ",", "args", ",", "kwargs", ",", "errback", "=", "None", ",", "on_revive", "=", "None", ",", "**", "opts", ")", ":", "errback", "=", "(", "errback", "or", "_ensure_errback", ")", "with", "pool", ".", "acquir...
function wrapper to handle connection errors .
train
false
28,126
def obj_list_dictize(obj_list, context, sort_key=(lambda x: x)): result_list = [] active = context.get('active', True) for obj in obj_list: if context.get('with_capacity'): (obj, capacity) = obj dictized = table_dictize(obj, context, capacity=capacity) else: dictized = table_dictize(obj, context) if (active and (obj.state != 'active')): continue result_list.append(dictized) return sorted(result_list, key=sort_key)
[ "def", "obj_list_dictize", "(", "obj_list", ",", "context", ",", "sort_key", "=", "(", "lambda", "x", ":", "x", ")", ")", ":", "result_list", "=", "[", "]", "active", "=", "context", ".", "get", "(", "'active'", ",", "True", ")", "for", "obj", "in", ...
get a list of model object and represent it as a list of dicts .
train
false
28,128
def assert_instance(obj, class_, label): if (not isinstance(obj, class_)): raise ModelInconsistencyError(('%s should be sublcass of %s, provided: %s' % (label, class_.__name__, type(obj).__name__)))
[ "def", "assert_instance", "(", "obj", ",", "class_", ",", "label", ")", ":", "if", "(", "not", "isinstance", "(", "obj", ",", "class_", ")", ")", ":", "raise", "ModelInconsistencyError", "(", "(", "'%s should be sublcass of %s, provided: %s'", "%", "(", "label...
raises argumenterror when obj is not instance of cls .
train
false
28,129
def engine_from_files(daily_bar_path, adjustments_path, asset_db_path, calendar, warmup_assets=False): loader = USEquityPricingLoader.from_files(daily_bar_path, adjustments_path) asset_finder = AssetFinder(asset_db_path) if warmup_assets: results = asset_finder.retrieve_all(asset_finder.sids) print(('Warmed up %d assets.' % len(results))) return SimplePipelineEngine((lambda _: loader), calendar, asset_finder)
[ "def", "engine_from_files", "(", "daily_bar_path", ",", "adjustments_path", ",", "asset_db_path", ",", "calendar", ",", "warmup_assets", "=", "False", ")", ":", "loader", "=", "USEquityPricingLoader", ".", "from_files", "(", "daily_bar_path", ",", "adjustments_path", ...
construct a simplepipelineengine from local filesystem resources .
train
false
28,133
def addSparseEndpoints(doubleExtrusionWidth, endpoints, fillLine, horizontalSegmentLists, infillSolidity, removedEndpoints, solidSurfaceThickness, surroundingXIntersections): horizontalEndpoints = horizontalSegmentLists[fillLine] for segment in horizontalEndpoints: addSparseEndpointsFromSegment(doubleExtrusionWidth, endpoints, fillLine, horizontalSegmentLists, infillSolidity, removedEndpoints, segment, solidSurfaceThickness, surroundingXIntersections)
[ "def", "addSparseEndpoints", "(", "doubleExtrusionWidth", ",", "endpoints", ",", "fillLine", ",", "horizontalSegmentLists", ",", "infillSolidity", ",", "removedEndpoints", ",", "solidSurfaceThickness", ",", "surroundingXIntersections", ")", ":", "horizontalEndpoints", "=", ...
add sparse endpoints .
train
false
28,137
@staff_member_required def dashboard(request, template_name=u'admin/dashboard.html'): profile = Profile.objects.get_or_create(user=request.user)[0] if (profile.extra_data is None): profile.extra_data = {} profile.save(update_fields=(u'extra_data',)) profile_data = profile.extra_data selected_primary_widgets = [] unselected_primary_widgets = [] primary_widget_selections = profile_data.get(u'primary_widget_selections') if primary_widget_selections: for p in primary_widgets: if (primary_widget_selections[p.widget_id] == u'1'): selected_primary_widgets.append(p) else: unselected_primary_widgets.append(p) else: selected_primary_widgets = primary_widgets unselected_primary_widgets = None selected_secondary_widgets = [] unselected_secondary_widgets = [] secondary_widget_selections = profile_data.get(u'secondary_widget_selections') if secondary_widget_selections: for s in secondary_widgets: if (secondary_widget_selections[s.widget_id] == u'1'): selected_secondary_widgets.append(s) else: unselected_secondary_widgets.append(s) else: selected_secondary_widgets = secondary_widgets unselected_secondary_widgets = None primary_widget_positions = profile_data.get(u'primary_widget_positions') if primary_widget_positions: sorted_primary_widgets = sorted(selected_primary_widgets, key=(lambda y: (primary_widget_positions[y.widget_id] or len(primary_widget_positions)))) else: sorted_primary_widgets = selected_primary_widgets secondary_widget_positions = profile_data.get(u'secondary_widget_positions') if secondary_widget_positions: sorted_secondary_widgets = sorted(selected_secondary_widgets, key=(lambda y: (secondary_widget_positions[y.widget_id] or len(secondary_widget_positions)))) else: sorted_secondary_widgets = selected_secondary_widgets return render_to_response(template_name, RequestContext(request, {u'primary_widgets': primary_widgets, u'root_path': (settings.SITE_ROOT + u'admin/db/'), u'secondary_widgets': secondary_widgets, u'selected_primary_widgets': sorted_primary_widgets, u'selected_secondary_widgets': sorted_secondary_widgets, u'support_data': serialize_support_data(request, True), u'title': _(u'Admin Dashboard'), u'unselected_primary_widgets': unselected_primary_widgets, u'unselected_secondary_widgets': unselected_secondary_widgets}))
[ "@", "staff_member_required", "def", "dashboard", "(", "request", ",", "template_name", "=", "u'admin/dashboard.html'", ")", ":", "profile", "=", "Profile", ".", "objects", ".", "get_or_create", "(", "user", "=", "request", ".", "user", ")", "[", "0", "]", "...
return the users dashboard web page .
train
false
28,138
def gcs_put_request(url, local_path): return requests.request('PUT', url, data=open(local_path, 'rb'), headers={'content-type': 'application/x-gzip'}, timeout=REQUEST_TIMEOUT, verify=False)
[ "def", "gcs_put_request", "(", "url", ",", "local_path", ")", ":", "return", "requests", ".", "request", "(", "'PUT'", ",", "url", ",", "data", "=", "open", "(", "local_path", ",", "'rb'", ")", ",", "headers", "=", "{", "'content-type'", ":", "'applicati...
performs a put request to the given url .
train
false
28,139
def dict_without(base_dict, *args): without_keys = dict(base_dict) for key in args: without_keys.pop(key, None) return without_keys
[ "def", "dict_without", "(", "base_dict", ",", "*", "args", ")", ":", "without_keys", "=", "dict", "(", "base_dict", ")", "for", "key", "in", "args", ":", "without_keys", ".", "pop", "(", "key", ",", "None", ")", "return", "without_keys" ]
return a copy of the dictionary without the keys .
train
false
28,140
@register.inclusion_tag('inclusion.html', takes_context=True) def inclusion_tag_without_context_parameter(arg): return {}
[ "@", "register", ".", "inclusion_tag", "(", "'inclusion.html'", ",", "takes_context", "=", "True", ")", "def", "inclusion_tag_without_context_parameter", "(", "arg", ")", ":", "return", "{", "}" ]
expected inclusion_tag_without_context_parameter __doc__ .
train
false
28,141
def _visit_pyfiles(list, dirname, names): if (not globals().has_key('_py_ext')): global _py_ext _py_ext = [triple[0] for triple in imp.get_suffixes() if (triple[2] == imp.PY_SOURCE)][0] if ('CVS' in names): names.remove('CVS') list.extend([os.path.join(dirname, file) for file in names if (os.path.splitext(file)[1] == _py_ext)])
[ "def", "_visit_pyfiles", "(", "list", ",", "dirname", ",", "names", ")", ":", "if", "(", "not", "globals", "(", ")", ".", "has_key", "(", "'_py_ext'", ")", ")", ":", "global", "_py_ext", "_py_ext", "=", "[", "triple", "[", "0", "]", "for", "triple", ...
helper for getfilesforname() .
train
true
28,143
def format_to_curl(context, method=None): raise NotImplementedError('curl format is not supported yet')
[ "def", "format_to_curl", "(", "context", ",", "method", "=", "None", ")", ":", "raise", "NotImplementedError", "(", "'curl format is not supported yet'", ")" ]
format a context object to a curl command .
train
false
28,145
def variance_inflation_factor(exog, exog_idx): k_vars = exog.shape[1] x_i = exog[:, exog_idx] mask = (np.arange(k_vars) != exog_idx) x_noti = exog[:, mask] r_squared_i = OLS(x_i, x_noti).fit().rsquared vif = (1.0 / (1.0 - r_squared_i)) return vif
[ "def", "variance_inflation_factor", "(", "exog", ",", "exog_idx", ")", ":", "k_vars", "=", "exog", ".", "shape", "[", "1", "]", "x_i", "=", "exog", "[", ":", ",", "exog_idx", "]", "mask", "=", "(", "np", ".", "arange", "(", "k_vars", ")", "!=", "ex...
variance inflation factor .
train
false
28,146
def beautiful_soup(*args, **kwargs): import bs4 return bs4.BeautifulSoup(*args, **kwargs)
[ "def", "beautiful_soup", "(", "*", "args", ",", "**", "kwargs", ")", ":", "import", "bs4", "return", "bs4", ".", "BeautifulSoup", "(", "*", "args", ",", "**", "kwargs", ")" ]
indirection function so we can lazy-import bs4 .
train
false
28,147
def get_scalar_type(dtype): if (dtype not in get_scalar_type.cache): get_scalar_type.cache[dtype] = Scalar(dtype=dtype) return get_scalar_type.cache[dtype]
[ "def", "get_scalar_type", "(", "dtype", ")", ":", "if", "(", "dtype", "not", "in", "get_scalar_type", ".", "cache", ")", ":", "get_scalar_type", ".", "cache", "[", "dtype", "]", "=", "Scalar", "(", "dtype", "=", "dtype", ")", "return", "get_scalar_type", ...
return a scalar object .
train
false
28,148
def byte2bin(number, classic_mode=True): text = '' for i in range(0, 8): if classic_mode: mask = (1 << (7 - i)) else: mask = (1 << i) if ((number & mask) == mask): text += '1' else: text += '0' return text
[ "def", "byte2bin", "(", "number", ",", "classic_mode", "=", "True", ")", ":", "text", "=", "''", "for", "i", "in", "range", "(", "0", ",", "8", ")", ":", "if", "classic_mode", ":", "mask", "=", "(", "1", "<<", "(", "7", "-", "i", ")", ")", "e...
convert a byte to a binary string .
train
false
28,149
def _api_browse(name, output, kwargs): compact = kwargs.get('compact') if (compact and (compact == '1')): paths = [] name = platform_encode(kwargs.get('term', '')) paths = [entry['path'] for entry in folders_at_path(os.path.dirname(name)) if ('path' in entry)] return report(output, keyword='', data=paths) else: name = platform_encode(name) show_hidden = kwargs.get('show_hidden_folders') paths = folders_at_path(name, True, show_hidden) return report(output, keyword='paths', data=paths)
[ "def", "_api_browse", "(", "name", ",", "output", ",", "kwargs", ")", ":", "compact", "=", "kwargs", ".", "get", "(", "'compact'", ")", "if", "(", "compact", "and", "(", "compact", "==", "'1'", ")", ")", ":", "paths", "=", "[", "]", "name", "=", ...
return tree of local path .
train
false
28,150
def session_query(session, model): if hasattr(model, 'query'): if callable(model.query): query = model.query() else: query = model.query if hasattr(query, 'filter'): return query return session.query(model)
[ "def", "session_query", "(", "session", ",", "model", ")", ":", "if", "hasattr", "(", "model", ",", "'query'", ")", ":", "if", "callable", "(", "model", ".", "query", ")", ":", "query", "=", "model", ".", "query", "(", ")", "else", ":", "query", "=...
returns a sqlalchemy query object for the specified model .
train
false
28,151
@register.simple_tag def admin_boolean_icon(val): if (django.VERSION > (1, 9)): ext = u'svg' else: ext = u'gif' icon_url = static(u'admin/img/icon-{0}.{1}'.format(TYPE_MAPPING[val], ext)) return mark_safe(u'<img src="{url}" alt="{text}" title="{text}" />'.format(url=icon_url, text=NAME_MAPPING[val]))
[ "@", "register", ".", "simple_tag", "def", "admin_boolean_icon", "(", "val", ")", ":", "if", "(", "django", ".", "VERSION", ">", "(", "1", ",", "9", ")", ")", ":", "ext", "=", "u'svg'", "else", ":", "ext", "=", "u'gif'", "icon_url", "=", "static", ...
admin icon wrapper .
train
false
28,152
def _get_guid_url_for(url): guid_url = guid_url_node_pattern.sub('', url, count=1) guid_url = guid_url_project_pattern.sub('', guid_url, count=1) guid_url = guid_url_profile_pattern.sub('', guid_url, count=1) return guid_url
[ "def", "_get_guid_url_for", "(", "url", ")", ":", "guid_url", "=", "guid_url_node_pattern", ".", "sub", "(", "''", ",", "url", ",", "count", "=", "1", ")", "guid_url", "=", "guid_url_project_pattern", ".", "sub", "(", "''", ",", "guid_url", ",", "count", ...
url post-processor transforms specific /project/<pid> or /project/<pid>/node/<nid> urls into guid urls .
train
false
28,153
def openAllUE9(): returnDict = dict() for i in range(deviceCount(9)): d = UE9(firstFound=False, devNumber=(i + 1)) returnDict[str(d.serialNumber)] = d return returnDict
[ "def", "openAllUE9", "(", ")", ":", "returnDict", "=", "dict", "(", ")", "for", "i", "in", "range", "(", "deviceCount", "(", "9", ")", ")", ":", "d", "=", "UE9", "(", "firstFound", "=", "False", ",", "devNumber", "=", "(", "i", "+", "1", ")", "...
a helpful function which will open all the connected ue9s .
train
false
28,154
def insert_missed_blocks(store): missed = [] for row in store.selectall('\n SELECT b.block_id\n FROM block b\n LEFT JOIN chain_candidate cc ON (b.block_id = cc.block_id)\n WHERE chain_id IS NULL\n ORDER BY b.block_height\n '): missed.append(row[0]) if (not missed): return store.log.info('Attempting to repair %d missed blocks.', len(missed)) inserted = 0 for block_id in missed: store.sql('\n INSERT INTO chain_candidate (\n chain_id, block_id, block_height, in_longest)\n SELECT cc.chain_id, b.block_id, b.block_height, 0\n FROM chain_candidate cc\n JOIN block prev ON (cc.block_id = prev.block_id)\n JOIN block b ON (b.prev_block_id = prev.block_id)\n WHERE b.block_id = ?', (block_id,)) inserted += store.rowcount() store.commit() store.log.info('Inserted %d rows into chain_candidate.', inserted)
[ "def", "insert_missed_blocks", "(", "store", ")", ":", "missed", "=", "[", "]", "for", "row", "in", "store", ".", "selectall", "(", "'\\n SELECT b.block_id\\n FROM block b\\n LEFT JOIN chain_candidate cc ON (b.block_id = cc.block_id)\\n WHERE chain_...
rescanning doesnt always work due to timeouts and resource constraints .
train
false
28,155
def StringToDoubleAddress(pString): parts = pString.split('.') if (len(parts) is not 4): raise LabJackException(0, 'IP address not correctly formatted') try: value = ((((int(parts[0]) << (8 * 3)) + (int(parts[1]) << (8 * 2))) + (int(parts[2]) << 8)) + int(parts[3])) except ValueError: raise LabJackException(0, 'IP address not correctly formatted') return value
[ "def", "StringToDoubleAddress", "(", "pString", ")", ":", "parts", "=", "pString", ".", "split", "(", "'.'", ")", "if", "(", "len", "(", "parts", ")", "is", "not", "4", ")", ":", "raise", "LabJackException", "(", "0", ",", "'IP address not correctly format...
converts an ip string to a number .
train
false
28,157
def function_args(callable_, *args, **kwargs): argspec = inspect.getargspec(callable_) return argspec_args(argspec, False, *args, **kwargs)
[ "def", "function_args", "(", "callable_", ",", "*", "args", ",", "**", "kwargs", ")", ":", "argspec", "=", "inspect", ".", "getargspec", "(", "callable_", ")", "return", "argspec_args", "(", "argspec", ",", "False", ",", "*", "args", ",", "**", "kwargs",...
return matching the function signature .
train
true
28,158
def init(mpstate): return SerialModule(mpstate)
[ "def", "init", "(", "mpstate", ")", ":", "return", "SerialModule", "(", "mpstate", ")" ]
set attributes into both configuration and knowledge base singletons based upon command line and configuration file options .
train
false
28,159
def identifier_from_name(name): if isinstance(name, str): identifier = name.decode('utf-8') else: identifier = name identifier = identifier.lower() identifier = identifier.replace(u'+', u' plus ') identifier = re.sub(u'[ _\u2013]+', u'-', identifier) identifier = re.sub(u"['./;\u2019(),:]", u'', identifier) identifier = identifier.replace(u'\xe9', u'e') identifier = identifier.replace(u'\u2640', u'-f') identifier = identifier.replace(u'\u2642', u'-m') if (identifier in (u'???', u'????')): identifier = u'unknown' elif (identifier == u'!'): identifier = u'exclamation' elif (identifier == u'?'): identifier = u'question' if (not identifier.replace(u'-', u'').isalnum()): raise ValueError(identifier) return identifier
[ "def", "identifier_from_name", "(", "name", ")", ":", "if", "isinstance", "(", "name", ",", "str", ")", ":", "identifier", "=", "name", ".", "decode", "(", "'utf-8'", ")", "else", ":", "identifier", "=", "name", "identifier", "=", "identifier", ".", "low...
make a string safe to use as an identifier .
train
false
28,160
@require_POST @csrf_protect def aifile_save(request): if (not test_user_authenticated(request)): return login(request, next='/cobbler_web/aifile/list', expired=True) aifile_name = request.POST.get('aifile_name', None) aidata = request.POST.get('aidata', '').replace('\r\n', '\n') if (aifile_name is None): return HttpResponse('NO AUTOMATIC INSTALLATION FILE NAME SPECIFIED') delete1 = request.POST.get('delete1', None) delete2 = request.POST.get('delete2', None) if (delete1 and delete2): remote.remove_autoinstall_template(aifile_name, request.session['token']) return HttpResponseRedirect('/cobbler_web/aifile/list') else: remote.write_autoinstall_template(aifile_name, aidata, request.session['token']) return HttpResponseRedirect('/cobbler_web/aifile/list')
[ "@", "require_POST", "@", "csrf_protect", "def", "aifile_save", "(", "request", ")", ":", "if", "(", "not", "test_user_authenticated", "(", "request", ")", ")", ":", "return", "login", "(", "request", ",", "next", "=", "'/cobbler_web/aifile/list'", ",", "expir...
this page processes and saves edits to an automatic os installation file .
train
false
28,161
def dklCart2rgb(LUM, LM, S, conversionMatrix=None): NxNx3 = list(LUM.shape) NxNx3.append(3) dkl_cartesian = numpy.asarray([LUM.reshape([(-1)]), LM.reshape([(-1)]), S.reshape([(-1)])]) if (conversionMatrix is None): conversionMatrix = numpy.asarray([[1.0, 1.0, (-0.1462)], [1.0, (-0.39), 0.2094], [1.0, 0.018, (-1.0)]]) rgb = numpy.dot(conversionMatrix, dkl_cartesian) return numpy.reshape(numpy.transpose(rgb), NxNx3)
[ "def", "dklCart2rgb", "(", "LUM", ",", "LM", ",", "S", ",", "conversionMatrix", "=", "None", ")", ":", "NxNx3", "=", "list", "(", "LUM", ".", "shape", ")", "NxNx3", ".", "append", "(", "3", ")", "dkl_cartesian", "=", "numpy", ".", "asarray", "(", "...
like dkl2rgb except that it uses cartesian coords rather than spherical coords for dkl .
train
false
28,162
def terminal_eval(source): node = ast.parse(source, '<source>', mode='eval') try: return _terminal_value(node.body) except ValueError: raise raise ValueError(('%r is not a terminal constant' % source))
[ "def", "terminal_eval", "(", "source", ")", ":", "node", "=", "ast", ".", "parse", "(", "source", ",", "'<source>'", ",", "mode", "=", "'eval'", ")", "try", ":", "return", "_terminal_value", "(", "node", ".", "body", ")", "except", "ValueError", ":", "...
evaluate a python constant source .
train
false
28,164
@requires_ipython(2.0) def test_webgl_loading(): import IPython from distutils.version import LooseVersion from IPython.testing.globalipapp import get_ipython ipy = get_ipython() ipy.run_cell('from vispy import app') if (LooseVersion(IPython.__version__) >= LooseVersion('3.0.0')): ipy.run_cell('%load_ext vispy.ipython') ipy.run_cell('backend_name = app.use_app().backend_name') assert_equal(ipy.user_ns['backend_name'], 'ipynb_webgl') else: ipy.run_cell('%load_ext vispy.ipython') ipy.run_cell('backend_name = app.use_app().backend_name') def invalid_backend_access(ipy): ipy.user_ns['backend_name'] assert_raises(KeyError, invalid_backend_access, ipy)
[ "@", "requires_ipython", "(", "2.0", ")", "def", "test_webgl_loading", "(", ")", ":", "import", "IPython", "from", "distutils", ".", "version", "import", "LooseVersion", "from", "IPython", ".", "testing", ".", "globalipapp", "import", "get_ipython", "ipy", "=", ...
test if the vispy .
train
false
28,165
def sT(expr, string): assert (srepr(expr) == string) assert (eval(string, ENV) == expr)
[ "def", "sT", "(", "expr", ",", "string", ")", ":", "assert", "(", "srepr", "(", "expr", ")", "==", "string", ")", "assert", "(", "eval", "(", "string", ",", "ENV", ")", "==", "expr", ")" ]
st := sreprtest from sympy/printing/tests/test_repr .
train
false
28,167
def remove_unnecessary_semicolons(css): return re.sub(';+\\}', '}', css)
[ "def", "remove_unnecessary_semicolons", "(", "css", ")", ":", "return", "re", ".", "sub", "(", "';+\\\\}'", ",", "'}'", ",", "css", ")" ]
remove unnecessary semicolons .
train
false
28,168
def minimum_part_size(size_in_bytes, default_part_size=DEFAULT_PART_SIZE): part_size = _MEGABYTE if ((default_part_size * MAXIMUM_NUMBER_OF_PARTS) < size_in_bytes): if (size_in_bytes > ((4096 * _MEGABYTE) * 10000)): raise ValueError(('File size too large: %s' % size_in_bytes)) min_part_size = (size_in_bytes / 10000) power = 3 while (part_size < min_part_size): part_size = math.ldexp(_MEGABYTE, power) power += 1 part_size = int(part_size) else: part_size = default_part_size return part_size
[ "def", "minimum_part_size", "(", "size_in_bytes", ",", "default_part_size", "=", "DEFAULT_PART_SIZE", ")", ":", "part_size", "=", "_MEGABYTE", "if", "(", "(", "default_part_size", "*", "MAXIMUM_NUMBER_OF_PARTS", ")", "<", "size_in_bytes", ")", ":", "if", "(", "siz...
calculate the minimum part size needed for a multipart upload .
train
false
28,169
def _get_content_length(url, preloading=False): prefix = ('preload: ' if preloading else '') util.dbg((((c.y + prefix) + 'getting content-length header') + c.w)) response = urlopen(url) headers = response.headers cl = headers['content-length'] return int(cl)
[ "def", "_get_content_length", "(", "url", ",", "preloading", "=", "False", ")", ":", "prefix", "=", "(", "'preload: '", "if", "preloading", "else", "''", ")", "util", ".", "dbg", "(", "(", "(", "(", "c", ".", "y", "+", "prefix", ")", "+", "'getting c...
return content length of a url .
train
false
28,171
def std_cdf(x): return (0.5 + (0.5 * tt.erf((x / tt.sqrt(2.0)))))
[ "def", "std_cdf", "(", "x", ")", ":", "return", "(", "0.5", "+", "(", "0.5", "*", "tt", ".", "erf", "(", "(", "x", "/", "tt", ".", "sqrt", "(", "2.0", ")", ")", ")", ")", ")" ]
calculates the standard normal cumulative distribution function .
train
false
28,172
def floatX(X): try: return X.astype(theano.config.floatX) except AttributeError: return np.asarray(X, dtype=theano.config.floatX)
[ "def", "floatX", "(", "X", ")", ":", "try", ":", "return", "X", ".", "astype", "(", "theano", ".", "config", ".", "floatX", ")", "except", "AttributeError", ":", "return", "np", ".", "asarray", "(", "X", ",", "dtype", "=", "theano", ".", "config", ...
convert a theano tensor or numpy array to theano .
train
false
28,173
@public def resultant(f, g, *gens, **args): includePRS = args.pop('includePRS', False) options.allowed_flags(args, ['polys']) try: ((F, G), opt) = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('resultant', 2, exc) if includePRS: (result, R) = F.resultant(G, includePRS=includePRS) else: result = F.resultant(G) if (not opt.polys): if includePRS: return (result.as_expr(), [r.as_expr() for r in R]) return result.as_expr() else: if includePRS: return (result, R) return result
[ "@", "public", "def", "resultant", "(", "f", ",", "g", ",", "*", "gens", ",", "**", "args", ")", ":", "includePRS", "=", "args", ".", "pop", "(", "'includePRS'", ",", "False", ")", "options", ".", "allowed_flags", "(", "args", ",", "[", "'polys'", ...
compute resultant of f and g .
train
false
28,175
@overload(where) def overload_where_scalars(cond, x, y): if (not isinstance(cond, types.Array)): if (x != y): raise errors.TypingError('x and y should have the same type') def where_impl(cond, x, y): '\n Scalar where() => return a 0-dim array\n ' scal = (x if cond else y) arr = np.empty_like(scal) arr[()] = scal return arr return where_impl
[ "@", "overload", "(", "where", ")", "def", "overload_where_scalars", "(", "cond", ",", "x", ",", "y", ")", ":", "if", "(", "not", "isinstance", "(", "cond", ",", "types", ".", "Array", ")", ")", ":", "if", "(", "x", "!=", "y", ")", ":", "raise", ...
implement where() for scalars .
train
false
28,176
def get_related_models_tuples(model): return {(rel_mod._meta.app_label, rel_mod._meta.model_name) for rel_mod in _get_related_models(model)}
[ "def", "get_related_models_tuples", "(", "model", ")", ":", "return", "{", "(", "rel_mod", ".", "_meta", ".", "app_label", ",", "rel_mod", ".", "_meta", ".", "model_name", ")", "for", "rel_mod", "in", "_get_related_models", "(", "model", ")", "}" ]
return a list of typical tuples for all related models for the given model .
train
false
28,177
def sunday_to_monday(dt): if (dt.weekday() == 6): return (dt + timedelta(1)) return dt
[ "def", "sunday_to_monday", "(", "dt", ")", ":", "if", "(", "dt", ".", "weekday", "(", ")", "==", "6", ")", ":", "return", "(", "dt", "+", "timedelta", "(", "1", ")", ")", "return", "dt" ]
if holiday falls on sunday .
train
false
28,178
def set_url_prefixer(prefixer): _locals.prefixer = prefixer
[ "def", "set_url_prefixer", "(", "prefixer", ")", ":", "_locals", ".", "prefixer", "=", "prefixer" ]
set the prefixer for the current thread .
train
false
28,179
def getCommonVertexIndex(edgeFirst, edgeSecond): for edgeFirstVertexIndex in edgeFirst.vertexIndexes: if ((edgeFirstVertexIndex == edgeSecond.vertexIndexes[0]) or (edgeFirstVertexIndex == edgeSecond.vertexIndexes[1])): return edgeFirstVertexIndex print 'Inconsistent GNU Triangulated Surface' print edgeFirst print edgeSecond return 0
[ "def", "getCommonVertexIndex", "(", "edgeFirst", ",", "edgeSecond", ")", ":", "for", "edgeFirstVertexIndex", "in", "edgeFirst", ".", "vertexIndexes", ":", "if", "(", "(", "edgeFirstVertexIndex", "==", "edgeSecond", ".", "vertexIndexes", "[", "0", "]", ")", "or",...
get the vertex index that both edges have in common .
train
false
28,180
def _retrieve_channel_id(email, profile='telemetry'): key = 'telemetry.channels' auth = _auth(profile=profile) if (key not in __context__): get_url = (_get_telemetry_base(profile) + '/notification-channels?_type=EmailNotificationChannel') response = requests.get(get_url, headers=auth) if (response.status_code == 200): cache_result = {} for (index, alert) in enumerate(response.json()): cache_result[alert.get('email')] = alert.get('_id', 'false') __context__[key] = cache_result return __context__[key].get(email, False)
[ "def", "_retrieve_channel_id", "(", "email", ",", "profile", "=", "'telemetry'", ")", ":", "key", "=", "'telemetry.channels'", "auth", "=", "_auth", "(", "profile", "=", "profile", ")", "if", "(", "key", "not", "in", "__context__", ")", ":", "get_url", "="...
given an email address .
train
true
28,181
def handoverComplete(MobileTimeDifference_presence=0): a = TpPd(pd=6) b = MessageType(mesType=44) c = RrCause() packet = ((a / b) / c) if (MobileTimeDifference_presence is 1): d = MobileTimeDifferenceHdr(ieiMTD=119, eightBitMTD=0) packet = (packet / d) return packet
[ "def", "handoverComplete", "(", "MobileTimeDifference_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "6", ")", "b", "=", "MessageType", "(", "mesType", "=", "44", ")", "c", "=", "RrCause", "(", ")", "packet", "=", "(", "(", "a", "...
handover complete section 9 .
train
true
28,182
def pde_separate_add(eq, fun, sep): return pde_separate(eq, fun, sep, strategy='add')
[ "def", "pde_separate_add", "(", "eq", ",", "fun", ",", "sep", ")", ":", "return", "pde_separate", "(", "eq", ",", "fun", ",", "sep", ",", "strategy", "=", "'add'", ")" ]
helper function for searching additive separable solutions .
train
false
28,183
def accepts_auth_key(func): @wraps(func) def process(request, *args, **kwargs): request.authkey = None http_auth = request.META.get('HTTP_AUTHORIZATION', '') if http_auth: try: (basic, b64_auth) = http_auth.split(' ', 1) if ('Basic' == basic): auth = base64.decodestring(b64_auth) (key_id, secret) = auth.split(':', 1) key = Key.objects.get(key=key_id) if key.check_secret(secret): request.authkey = key request.user = key.user except (binascii.Error, ValueError, Key.DoesNotExist): pass return func(request, *args, **kwargs) return process
[ "def", "accepts_auth_key", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "process", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "request", ".", "authkey", "=", "None", "http_auth", "=", "request", ".", "META", "."...
enable a view to accept an auth key via http basic auth .
train
false
28,184
def get_theme_by_identifier(identifier, settings_obj=None): for theme_cls in get_provide_objects('xtheme'): if (theme_cls.identifier == identifier): return theme_cls(settings_obj=settings_obj) return None
[ "def", "get_theme_by_identifier", "(", "identifier", ",", "settings_obj", "=", "None", ")", ":", "for", "theme_cls", "in", "get_provide_objects", "(", "'xtheme'", ")", ":", "if", "(", "theme_cls", ".", "identifier", "==", "identifier", ")", ":", "return", "the...
get an instantiated theme by identifier .
train
false
28,185
def p_relexpr(p): p[0] = ('RELOP', p[2], p[1], p[3])
[ "def", "p_relexpr", "(", "p", ")", ":", "p", "[", "0", "]", "=", "(", "'RELOP'", ",", "p", "[", "2", "]", ",", "p", "[", "1", "]", ",", "p", "[", "3", "]", ")" ]
relexpr : expr lt expr | expr le expr | expr gt expr | expr ge expr | expr equals expr | expr ne expr .
train
false
28,186
def tgrep_positions(pattern, trees, search_leaves=True): if isinstance(pattern, (binary_type, text_type)): pattern = tgrep_compile(pattern) for tree in trees: try: if search_leaves: positions = tree.treepositions() else: positions = treepositions_no_leaves(tree) (yield [position for position in positions if pattern(tree[position])]) except AttributeError: (yield [])
[ "def", "tgrep_positions", "(", "pattern", ",", "trees", ",", "search_leaves", "=", "True", ")", ":", "if", "isinstance", "(", "pattern", ",", "(", "binary_type", ",", "text_type", ")", ")", ":", "pattern", "=", "tgrep_compile", "(", "pattern", ")", "for", ...
return the tree positions in the trees which match the given pattern .
train
false
28,187
def matrix_to_density(mat): from sympy.physics.quantum.density import Density eigen = mat.eigenvects() args = [[matrix_to_qubit(Matrix([vector])), x[0]] for x in eigen for vector in x[2] if (x[0] != 0)] if (len(args) == 0): return 0 else: return Density(*args)
[ "def", "matrix_to_density", "(", "mat", ")", ":", "from", "sympy", ".", "physics", ".", "quantum", ".", "density", "import", "Density", "eigen", "=", "mat", ".", "eigenvects", "(", ")", "args", "=", "[", "[", "matrix_to_qubit", "(", "Matrix", "(", "[", ...
works by finding the eigenvectors and eigenvalues of the matrix .
train
false
28,188
def uninstall_overlay(module, name): layman = init_layman() if (not layman.is_installed(name)): return False if module.check_mode: mymsg = (("Would remove layman repo '" + name) + "'") module.exit_json(changed=True, msg=mymsg) layman.delete_repos(name) if layman.get_errors(): raise ModuleError(layman.get_errors()) return True
[ "def", "uninstall_overlay", "(", "module", ",", "name", ")", ":", "layman", "=", "init_layman", "(", ")", "if", "(", "not", "layman", ".", "is_installed", "(", "name", ")", ")", ":", "return", "False", "if", "module", ".", "check_mode", ":", "mymsg", "...
uninstalls the given overlay repository from the system .
train
false
28,189
def sum_of_four_squares(n): if (n == 0): return (0, 0, 0, 0) v = multiplicity(4, n) n //= (4 ** v) if ((n % 8) == 7): d = 2 n = (n - 4) elif (((n % 8) == 6) or ((n % 8) == 2)): d = 1 n = (n - 1) else: d = 0 (x, y, z) = sum_of_three_squares(n) return _sorted_tuple(((2 ** v) * d), ((2 ** v) * x), ((2 ** v) * y), ((2 ** v) * z))
[ "def", "sum_of_four_squares", "(", "n", ")", ":", "if", "(", "n", "==", "0", ")", ":", "return", "(", "0", ",", "0", ",", "0", ",", "0", ")", "v", "=", "multiplicity", "(", "4", ",", "n", ")", "n", "//=", "(", "4", "**", "v", ")", "if", "...
returns a 4-tuple such that a^2 + b^2 + c^2 + d^2 = n .
train
false
28,190
def infer_enum(node, context=None): enum_meta = nodes.Class('EnumMeta', 'docstring') class_node = infer_func_form(node, enum_meta, context=context, enum=True)[0] return iter([class_node.instanciate_class()])
[ "def", "infer_enum", "(", "node", ",", "context", "=", "None", ")", ":", "enum_meta", "=", "nodes", ".", "Class", "(", "'EnumMeta'", ",", "'docstring'", ")", "class_node", "=", "infer_func_form", "(", "node", ",", "enum_meta", ",", "context", "=", "context...
specific inference function for enum callfunc node .
train
false
28,191
def reload_config(): _env_reloader.update()
[ "def", "reload_config", "(", ")", ":", "_env_reloader", ".", "update", "(", ")" ]
reload supervisor configuration .
train
false
28,192
def remove_certbot_files(): nginx_dir_location = os.path.join(PROJECT_DIRECTORY, 'compose/nginx') for filename in ['nginx-secure.conf', 'start.sh', 'dhparams.example.pem']: file_name = os.path.join(nginx_dir_location, filename) remove_file(file_name)
[ "def", "remove_certbot_files", "(", ")", ":", "nginx_dir_location", "=", "os", ".", "path", ".", "join", "(", "PROJECT_DIRECTORY", ",", "'compose/nginx'", ")", "for", "filename", "in", "[", "'nginx-secure.conf'", ",", "'start.sh'", ",", "'dhparams.example.pem'", "...
removes files needed for certbot if it isnt going to be used .
train
false
28,193
def update_if_dirty(model_instance, **kwargs): dirty = False for (key, value) in kwargs.items(): if (getattr(model_instance, key) != value): setattr(model_instance, key, value) dirty = True if dirty: model_instance.save()
[ "def", "update_if_dirty", "(", "model_instance", ",", "**", "kwargs", ")", ":", "dirty", "=", "False", "for", "(", "key", ",", "value", ")", "in", "kwargs", ".", "items", "(", ")", ":", "if", "(", "getattr", "(", "model_instance", ",", "key", ")", "!...
updates an instance of a model with kwargs .
train
false
28,194
def config_changes(config, unused_plugins): client.view_config_changes(config, num=config.num)
[ "def", "config_changes", "(", "config", ",", "unused_plugins", ")", ":", "client", ".", "view_config_changes", "(", "config", ",", "num", "=", "config", ".", "num", ")" ]
show changes made to server config during installation view checkpoints and associated configuration changes .
train
false
28,195
def guess_mime_type(content, deftype): starts_with_mappings = {'#include': 'text/x-include-url', '#!': 'text/x-shellscript', '#cloud-config': 'text/cloud-config', '#upstart-job': 'text/upstart-job', '#part-handler': 'text/part-handler', '#cloud-boothook': 'text/cloud-boothook'} rtype = deftype for (possible_type, mimetype) in starts_with_mappings.items(): if content.startswith(possible_type): rtype = mimetype break return rtype
[ "def", "guess_mime_type", "(", "content", ",", "deftype", ")", ":", "starts_with_mappings", "=", "{", "'#include'", ":", "'text/x-include-url'", ",", "'#!'", ":", "'text/x-shellscript'", ",", "'#cloud-config'", ":", "'text/cloud-config'", ",", "'#upstart-job'", ":", ...
description: guess the mime type of a block of text .
train
true
28,196
def keywords(func): if isinstance(func, type): return keywords(func.__init__) elif isinstance(func, partial): return keywords(func.func) return inspect.getargspec(func).args
[ "def", "keywords", "(", "func", ")", ":", "if", "isinstance", "(", "func", ",", "type", ")", ":", "return", "keywords", "(", "func", ".", "__init__", ")", "elif", "isinstance", "(", "func", ",", "partial", ")", ":", "return", "keywords", "(", "func", ...
returns a sorted list of keywords in the given string .
train
false
28,197
def auth_user_options_get_osm(pe_id): db = current.db table = current.s3db.auth_user_options query = (table.pe_id == pe_id) record = db(query).select(limitby=(0, 1)).first() if record: return (record.osm_oauth_consumer_key, record.osm_oauth_consumer_secret) else: return None
[ "def", "auth_user_options_get_osm", "(", "pe_id", ")", ":", "db", "=", "current", ".", "db", "table", "=", "current", ".", "s3db", ".", "auth_user_options", "query", "=", "(", "table", ".", "pe_id", "==", "pe_id", ")", "record", "=", "db", "(", "query", ...
gets the osm-related options for a pe_id .
train
false
28,198
def _chomp(string): if (len(string) and (string[(-1)] == '\n')): string = string[:(-1)] if (len(string) and (string[(-1)] == '\r')): string = string[:(-1)] return string
[ "def", "_chomp", "(", "string", ")", ":", "if", "(", "len", "(", "string", ")", "and", "(", "string", "[", "(", "-", "1", ")", "]", "==", "'\\n'", ")", ")", ":", "string", "=", "string", "[", ":", "(", "-", "1", ")", "]", "if", "(", "len", ...
rather than rstrip() .
train
false
28,199
def test_length(): assert (hug.types.length(1, 10)('bacon') == 'bacon') assert (hug.types.length(1, 10)(42) == '42') assert ('42' in hug.types.length(1, 42).__doc__) with pytest.raises(ValueError): hug.types.length(1, 10)('bacon is the greatest food known to man') with pytest.raises(ValueError): hug.types.length(1, 10)('') with pytest.raises(ValueError): hug.types.length(1, 10)('bacon is th')
[ "def", "test_length", "(", ")", ":", "assert", "(", "hug", ".", "types", ".", "length", "(", "1", ",", "10", ")", "(", "'bacon'", ")", "==", "'bacon'", ")", "assert", "(", "hug", ".", "types", ".", "length", "(", "1", ",", "10", ")", "(", "42",...
tests that hugs length type successfully handles a length range .
train
false
28,203
@raises(OptionError) def test_parse_command_option_error(): arg_str = 'selector click options' screenshot._parse_command(arg_str) arg_str = 'selector click options' screenshot._parse_command(arg_str)
[ "@", "raises", "(", "OptionError", ")", "def", "test_parse_command_option_error", "(", ")", ":", "arg_str", "=", "'selector click options'", "screenshot", ".", "_parse_command", "(", "arg_str", ")", "arg_str", "=", "'selector click options'", "screenshot", ".", "_pars...
test optionerror(s) raised by screenshot .
train
false
28,204
@boto3_log def _get_ebs_volume_state(volume): volume.reload() return volume
[ "@", "boto3_log", "def", "_get_ebs_volume_state", "(", "volume", ")", ":", "volume", ".", "reload", "(", ")", "return", "volume" ]
fetch input ebs volumes latest state from backend .
train
false
28,205
@api_versions.wraps('2.26') @utils.arg('server', metavar='<server>', help=_('Name or ID of server.')) @utils.arg('tag', metavar='<tag>', nargs='+', help=_('Tag(s) to delete.')) def do_server_tag_delete(cs, args): server = _find_server(cs, args.server) utils.do_action_on_many((lambda t: server.delete_tag(t)), args.tag, _('Request to delete tag %s from specified server has been accepted.'), _('Unable to delete tag %s from specified server.'))
[ "@", "api_versions", ".", "wraps", "(", "'2.26'", ")", "@", "utils", ".", "arg", "(", "'server'", ",", "metavar", "=", "'<server>'", ",", "help", "=", "_", "(", "'Name or ID of server.'", ")", ")", "@", "utils", ".", "arg", "(", "'tag'", ",", "metavar"...
delete one or more tags from a server .
train
false
28,209
def is_target_available(conda_target, conda_context=None, channels_override=None): (best_hit, exact) = best_search_result(conda_target, conda_context, channels_override) if best_hit: return ('exact' if exact else True) else: return False
[ "def", "is_target_available", "(", "conda_target", ",", "conda_context", "=", "None", ",", "channels_override", "=", "None", ")", ":", "(", "best_hit", ",", "exact", ")", "=", "best_search_result", "(", "conda_target", ",", "conda_context", ",", "channels_override...
check if a specified target is available for installation .
train
false
28,210
def get_component_review(app, id): sa_session = app.model.context.current return sa_session.query(app.model.ComponentReview).get(app.security.decode_id(id))
[ "def", "get_component_review", "(", "app", ",", "id", ")", ":", "sa_session", "=", "app", ".", "model", ".", "context", ".", "current", "return", "sa_session", ".", "query", "(", "app", ".", "model", ".", "ComponentReview", ")", ".", "get", "(", "app", ...
get a component_review from the database .
train
false
28,211
def _set_account_policy(name, policy): cmd = 'pwpolicy -u {0} -setpolicy "{1}"'.format(name, policy) try: return salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: if ('Error: user <{0}> not found'.format(name) in exc.strerror): raise CommandExecutionError('User not found: {0}'.format(name)) raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
[ "def", "_set_account_policy", "(", "name", ",", "policy", ")", ":", "cmd", "=", "'pwpolicy -u {0} -setpolicy \"{1}\"'", ".", "format", "(", "name", ",", "policy", ")", "try", ":", "return", "salt", ".", "utils", ".", "mac_utils", ".", "execute_return_success", ...
set a value in the user accountpolicy .
train
true
28,212
def _cherrypy_pydoc_resolve(thing, forceload=0): if isinstance(thing, _ThreadLocalProxy): thing = getattr(serving, thing.__attrname__) return _pydoc._builtin_resolve(thing, forceload)
[ "def", "_cherrypy_pydoc_resolve", "(", "thing", ",", "forceload", "=", "0", ")", ":", "if", "isinstance", "(", "thing", ",", "_ThreadLocalProxy", ")", ":", "thing", "=", "getattr", "(", "serving", ",", "thing", ".", "__attrname__", ")", "return", "_pydoc", ...
given an object or a path to an object .
train
false
28,213
def time_snowflake(datetime_obj, high=False): unix_seconds = (datetime_obj - type(datetime_obj)(1970, 1, 1)).total_seconds() discord_millis = int(((unix_seconds * 1000) - DISCORD_EPOCH)) return ((discord_millis << 22) + (((2 ** 22) - 1) if high else 0))
[ "def", "time_snowflake", "(", "datetime_obj", ",", "high", "=", "False", ")", ":", "unix_seconds", "=", "(", "datetime_obj", "-", "type", "(", "datetime_obj", ")", "(", "1970", ",", "1", ",", "1", ")", ")", ".", "total_seconds", "(", ")", "discord_millis...
returns a numeric snowflake pretending to be created at the given date .
train
true
28,214
def ConstructAssetId(id_prefix, device_id, uniquifier): assert IdPrefix.IsValid(id_prefix), id_prefix byte_str = util.EncodeVarLengthNumber(device_id) byte_str += _EncodeUniquifier(uniquifier) return (id_prefix + base64hex.B64HexEncode(byte_str, padding=False))
[ "def", "ConstructAssetId", "(", "id_prefix", ",", "device_id", ",", "uniquifier", ")", ":", "assert", "IdPrefix", ".", "IsValid", "(", "id_prefix", ")", ",", "id_prefix", "byte_str", "=", "util", ".", "EncodeVarLengthNumber", "(", "device_id", ")", "byte_str", ...
constructs an asset id that does not have a timestamp part .
train
false
28,215
def print_segments(segments_response): print('------ Segments Collection -------') print_pagination_info(segments_response) print() for segment in segments_response.get('items', []): print(('Segment ID = %s' % segment.get('id'))) print(('Kind = %s' % segment.get('kind'))) print(('Self Link = %s' % segment.get('selfLink'))) print(('Name = %s' % segment.get('name'))) print(('Definition = %s' % segment.get('definition'))) print(('Created = %s' % segment.get('created'))) print(('Updated = %s' % segment.get('updated'))) print()
[ "def", "print_segments", "(", "segments_response", ")", ":", "print", "(", "'------ Segments Collection -------'", ")", "print_pagination_info", "(", "segments_response", ")", "print", "(", ")", "for", "segment", "in", "segments_response", ".", "get", "(", "'items'", ...
prints all the segment info in the segments collection .
train
false
28,216
def _create_ha_name(name, channel, param, count): if ((count == 1) and (param is None)): return name if ((count > 1) and (param is None)): return '{} {}'.format(name, channel) if ((count == 1) and (param is not None)): return '{} {}'.format(name, param) if ((count > 1) and (param is not None)): return '{} {} {}'.format(name, channel, param)
[ "def", "_create_ha_name", "(", "name", ",", "channel", ",", "param", ",", "count", ")", ":", "if", "(", "(", "count", "==", "1", ")", "and", "(", "param", "is", "None", ")", ")", ":", "return", "name", "if", "(", "(", "count", ">", "1", ")", "a...
generate a unique object name .
train
false
28,217
def extract_read_to_sample_mapping(labels): sample_id_mapping = {} re = compile('(\\S+) (\\S+)') for label in labels: tmatch = search(re, label) sample_id = tmatch.group(1) flowgram_id = tmatch.group(2) sample_id_mapping[flowgram_id] = sample_id return sample_id_mapping
[ "def", "extract_read_to_sample_mapping", "(", "labels", ")", ":", "sample_id_mapping", "=", "{", "}", "re", "=", "compile", "(", "'(\\\\S+) (\\\\S+)'", ")", "for", "label", "in", "labels", ":", "tmatch", "=", "search", "(", "re", ",", "label", ")", "sample_i...
extract a mapping from reads to sample_ids from split_libraries .
train
false
28,218
def _get_n_moments(order): order = np.asarray(order, int) return ((order + 2) * order)
[ "def", "_get_n_moments", "(", "order", ")", ":", "order", "=", "np", ".", "asarray", "(", "order", ",", "int", ")", "return", "(", "(", "order", "+", "2", ")", "*", "order", ")" ]
compute the number of multipolar moments .
train
false
28,220
def _message_to_entity(msg, modelclass): ent = modelclass() for (prop_name, prop) in modelclass._properties.iteritems(): if (prop._code_name == 'blob_'): continue value = getattr(msg, prop_name) if ((value is not None) and isinstance(prop, model.StructuredProperty)): if prop._repeated: value = [_message_to_entity(v, prop._modelclass) for v in value] else: value = _message_to_entity(value, prop._modelclass) setattr(ent, prop_name, value) return ent
[ "def", "_message_to_entity", "(", "msg", ",", "modelclass", ")", ":", "ent", "=", "modelclass", "(", ")", "for", "(", "prop_name", ",", "prop", ")", "in", "modelclass", ".", "_properties", ".", "iteritems", "(", ")", ":", "if", "(", "prop", ".", "_code...
recursive helper for _to_base_type() to convert a message to an entity .
train
true
28,221
def do_ScpDelete(po): sc = _get_option(po, 'service_class') try: ScpDelete(sc) except adsi.error as details: if (details[0] != winerror.ERROR_DS_OBJ_NOT_FOUND): raise log(2, "ScpDelete ignoring ERROR_DS_OBJ_NOT_FOUND for service-class '%s'", sc) return sc
[ "def", "do_ScpDelete", "(", "po", ")", ":", "sc", "=", "_get_option", "(", "po", ",", "'service_class'", ")", "try", ":", "ScpDelete", "(", "sc", ")", "except", "adsi", ".", "error", "as", "details", ":", "if", "(", "details", "[", "0", "]", "!=", ...
delete a service connection point .
train
false
28,222
def image_ec2_id(image_id, image_type='ami'): template = (image_type + '-%08x') try: return id_to_ec2_id(image_id, template=template) except ValueError: return 'ami-00000000'
[ "def", "image_ec2_id", "(", "image_id", ",", "image_type", "=", "'ami'", ")", ":", "template", "=", "(", "image_type", "+", "'-%08x'", ")", "try", ":", "return", "id_to_ec2_id", "(", "image_id", ",", "template", "=", "template", ")", "except", "ValueError", ...
returns image ec2_id using id and three letter type .
train
false
28,223
def ValidateTargetType(target, target_dict): VALID_TARGET_TYPES = ('executable', 'loadable_module', 'static_library', 'shared_library', 'mac_kernel_extension', 'none') target_type = target_dict.get('type', None) if (target_type not in VALID_TARGET_TYPES): raise GypError(("Target %s has an invalid target type '%s'. Must be one of %s." % (target, target_type, '/'.join(VALID_TARGET_TYPES)))) if (target_dict.get('standalone_static_library', 0) and (not (target_type == 'static_library'))): raise GypError(('Target %s has type %s but standalone_static_library flag is only valid for static_library type.' % (target, target_type)))
[ "def", "ValidateTargetType", "(", "target", ",", "target_dict", ")", ":", "VALID_TARGET_TYPES", "=", "(", "'executable'", ",", "'loadable_module'", ",", "'static_library'", ",", "'shared_library'", ",", "'mac_kernel_extension'", ",", "'none'", ")", "target_type", "=",...
ensures the type field on the target is one of the known types .
train
false
28,225
def set_current_theme(identifier): cache.bump_version(THEME_CACHE_KEY) theme = get_theme_by_identifier(identifier) if (not theme): raise ValueError('Invalid theme identifier') theme.set_current() cache.set(THEME_CACHE_KEY, theme) return theme
[ "def", "set_current_theme", "(", "identifier", ")", ":", "cache", ".", "bump_version", "(", "THEME_CACHE_KEY", ")", "theme", "=", "get_theme_by_identifier", "(", "identifier", ")", "if", "(", "not", "theme", ")", ":", "raise", "ValueError", "(", "'Invalid theme ...
activate a theme based on identifier .
train
false
28,226
def auto_device(obj, stream=0, copy=True): if _driver.is_device_memory(obj): return (obj, False) else: sentry_contiguous(obj) if isinstance(obj, np.void): devobj = from_record_like(obj, stream=stream) else: devobj = from_array_like(obj, stream=stream) if copy: devobj.copy_to_device(obj, stream=stream) return (devobj, True)
[ "def", "auto_device", "(", "obj", ",", "stream", "=", "0", ",", "copy", "=", "True", ")", ":", "if", "_driver", ".", "is_device_memory", "(", "obj", ")", ":", "return", "(", "obj", ",", "False", ")", "else", ":", "sentry_contiguous", "(", "obj", ")",...
create a devicerecord or devicearray like obj and optionally copy data from host to device .
train
false
28,227
def p_specifier_qualifier_list_3(t): pass
[ "def", "p_specifier_qualifier_list_3", "(", "t", ")", ":", "pass" ]
specifier_qualifier_list : type_qualifier specifier_qualifier_list .
train
false
28,228
@register.simple_tag(takes_context=True) def pagination_querystring(context, page_number, page_key=DEFAULT_PAGE_KEY): return querystring(context, **{page_key: page_number})
[ "@", "register", ".", "simple_tag", "(", "takes_context", "=", "True", ")", "def", "pagination_querystring", "(", "context", ",", "page_number", ",", "page_key", "=", "DEFAULT_PAGE_KEY", ")", ":", "return", "querystring", "(", "context", ",", "**", "{", "page_...
print out a querystring with an updated page number: {% if page .
train
false
28,230
def test_ast_good_take(): can_compile(u'(take 1 [2 3])')
[ "def", "test_ast_good_take", "(", ")", ":", "can_compile", "(", "u'(take 1 [2 3])'", ")" ]
make sure ast can compile valid take .
train
false
28,231
def _set_string(path, value, base=win32con.HKEY_CLASSES_ROOT): win32api.RegSetValue(base, path, win32con.REG_SZ, value)
[ "def", "_set_string", "(", "path", ",", "value", ",", "base", "=", "win32con", ".", "HKEY_CLASSES_ROOT", ")", ":", "win32api", ".", "RegSetValue", "(", "base", ",", "path", ",", "win32con", ".", "REG_SZ", ",", "value", ")" ]
set a string value in the registry .
train
false