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
24,039
@raises(ValueError) def test_conditional_requires_nested_mlp(): mlp = MLP(nvis=10, layers=[Linear(layer_name='h', dim=10, irange=0.01)]) Conditional(mlp=mlp, name='conditional')
[ "@", "raises", "(", "ValueError", ")", "def", "test_conditional_requires_nested_mlp", "(", ")", ":", "mlp", "=", "MLP", "(", "nvis", "=", "10", ",", "layers", "=", "[", "Linear", "(", "layer_name", "=", "'h'", ",", "dim", "=", "10", ",", "irange", "=", "0.01", ")", "]", ")", "Conditional", "(", "mlp", "=", "mlp", ",", "name", "=", "'conditional'", ")" ]
conditional rejects non-nested mlps .
train
false
24,041
def test_scharr_vertical(): (i, j) = np.mgrid[(-5):6, (-5):6] image = (j >= 0).astype(float) result = (filters.scharr(image) * np.sqrt(2)) j[(np.abs(i) == 5)] = 10000 assert_allclose(result[(j == 0)], 1) assert np.all((result[(np.abs(j) > 1)] == 0))
[ "def", "test_scharr_vertical", "(", ")", ":", "(", "i", ",", "j", ")", "=", "np", ".", "mgrid", "[", "(", "-", "5", ")", ":", "6", ",", "(", "-", "5", ")", ":", "6", "]", "image", "=", "(", "j", ">=", "0", ")", ".", "astype", "(", "float", ")", "result", "=", "(", "filters", ".", "scharr", "(", "image", ")", "*", "np", ".", "sqrt", "(", "2", ")", ")", "j", "[", "(", "np", ".", "abs", "(", "i", ")", "==", "5", ")", "]", "=", "10000", "assert_allclose", "(", "result", "[", "(", "j", "==", "0", ")", "]", ",", "1", ")", "assert", "np", ".", "all", "(", "(", "result", "[", "(", "np", ".", "abs", "(", "j", ")", ">", "1", ")", "]", "==", "0", ")", ")" ]
scharr on a vertical edge should be a vertical line .
train
false
24,042
def generate_auth_header(consumer_key, timestamp, nonce, signature_type, signature, version='1.0', next=None, token=None, verifier=None): params = {'oauth_consumer_key': consumer_key, 'oauth_version': version, 'oauth_nonce': nonce, 'oauth_timestamp': str(timestamp), 'oauth_signature_method': signature_type, 'oauth_signature': signature} if (next is not None): params['oauth_callback'] = str(next) if (token is not None): params['oauth_token'] = token if (verifier is not None): params['oauth_verifier'] = verifier pairs = [('%s="%s"' % (k, urllib.quote(v, safe='~'))) for (k, v) in params.iteritems()] return ('OAuth %s' % ', '.join(pairs))
[ "def", "generate_auth_header", "(", "consumer_key", ",", "timestamp", ",", "nonce", ",", "signature_type", ",", "signature", ",", "version", "=", "'1.0'", ",", "next", "=", "None", ",", "token", "=", "None", ",", "verifier", "=", "None", ")", ":", "params", "=", "{", "'oauth_consumer_key'", ":", "consumer_key", ",", "'oauth_version'", ":", "version", ",", "'oauth_nonce'", ":", "nonce", ",", "'oauth_timestamp'", ":", "str", "(", "timestamp", ")", ",", "'oauth_signature_method'", ":", "signature_type", ",", "'oauth_signature'", ":", "signature", "}", "if", "(", "next", "is", "not", "None", ")", ":", "params", "[", "'oauth_callback'", "]", "=", "str", "(", "next", ")", "if", "(", "token", "is", "not", "None", ")", ":", "params", "[", "'oauth_token'", "]", "=", "token", "if", "(", "verifier", "is", "not", "None", ")", ":", "params", "[", "'oauth_verifier'", "]", "=", "verifier", "pairs", "=", "[", "(", "'%s=\"%s\"'", "%", "(", "k", ",", "urllib", ".", "quote", "(", "v", ",", "safe", "=", "'~'", ")", ")", ")", "for", "(", "k", ",", "v", ")", "in", "params", ".", "iteritems", "(", ")", "]", "return", "(", "'OAuth %s'", "%", "', '", ".", "join", "(", "pairs", ")", ")" ]
builds the authorization header to be sent in the request .
train
false
24,043
def _deprecated_getitem_method(name, attrs): attrs = frozenset(attrs) msg = "'{name}[{attr!r}]' is deprecated, please use '{name}.{attr}' instead" def __getitem__(self, key): '``__getitem__`` is deprecated, please use attribute access instead.\n ' warn(msg.format(name=name, attr=key), DeprecationWarning, stacklevel=2) if (key in attrs): return self.__dict__[key] raise KeyError(key) return __getitem__
[ "def", "_deprecated_getitem_method", "(", "name", ",", "attrs", ")", ":", "attrs", "=", "frozenset", "(", "attrs", ")", "msg", "=", "\"'{name}[{attr!r}]' is deprecated, please use '{name}.{attr}' instead\"", "def", "__getitem__", "(", "self", ",", "key", ")", ":", "warn", "(", "msg", ".", "format", "(", "name", "=", "name", ",", "attr", "=", "key", ")", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "if", "(", "key", "in", "attrs", ")", ":", "return", "self", ".", "__dict__", "[", "key", "]", "raise", "KeyError", "(", "key", ")", "return", "__getitem__" ]
create a deprecated __getitem__ method that tells users to use getattr instead .
train
true
24,044
def getoutput(cmd): psi = System.Diagnostics.ProcessStartInfo(cmd) psi.RedirectStandardOutput = True psi.RedirectStandardError = True psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal psi.UseShellExecute = False reg = System.Diagnostics.Process.Start(psi) myOutput = reg.StandardOutput output = myOutput.ReadToEnd() myError = reg.StandardError error = myError.ReadToEnd() return output
[ "def", "getoutput", "(", "cmd", ")", ":", "psi", "=", "System", ".", "Diagnostics", ".", "ProcessStartInfo", "(", "cmd", ")", "psi", ".", "RedirectStandardOutput", "=", "True", "psi", ".", "RedirectStandardError", "=", "True", "psi", ".", "WindowStyle", "=", "System", ".", "Diagnostics", ".", "ProcessWindowStyle", ".", "Normal", "psi", ".", "UseShellExecute", "=", "False", "reg", "=", "System", ".", "Diagnostics", ".", "Process", ".", "Start", "(", "psi", ")", "myOutput", "=", "reg", ".", "StandardOutput", "output", "=", "myOutput", ".", "ReadToEnd", "(", ")", "myError", "=", "reg", ".", "StandardError", "error", "=", "myError", ".", "ReadToEnd", "(", ")", "return", "output" ]
return output of executing cmd in a shell .
train
false
24,045
def norm_entropy_vec(loc, scale): if (isinstance(loc, float) or isinstance(loc, int)): return stats.norm.entropy(loc, scale) else: return np.array([stats.norm.entropy(loc_x, scale_x) for (loc_x, scale_x) in zip(loc, scale)])
[ "def", "norm_entropy_vec", "(", "loc", ",", "scale", ")", ":", "if", "(", "isinstance", "(", "loc", ",", "float", ")", "or", "isinstance", "(", "loc", ",", "int", ")", ")", ":", "return", "stats", ".", "norm", ".", "entropy", "(", "loc", ",", "scale", ")", "else", ":", "return", "np", ".", "array", "(", "[", "stats", ".", "norm", ".", "entropy", "(", "loc_x", ",", "scale_x", ")", "for", "(", "loc_x", ",", "scale_x", ")", "in", "zip", "(", "loc", ",", "scale", ")", "]", ")" ]
vectorized version of stats .
train
false
24,046
def _cache_normalize_path(path): try: return _NORM_PATH_CACHE[path] except KeyError: if (not path): return _normalize_path(path) result = _NORM_PATH_CACHE[path] = _normalize_path(path) return result
[ "def", "_cache_normalize_path", "(", "path", ")", ":", "try", ":", "return", "_NORM_PATH_CACHE", "[", "path", "]", "except", "KeyError", ":", "if", "(", "not", "path", ")", ":", "return", "_normalize_path", "(", "path", ")", "result", "=", "_NORM_PATH_CACHE", "[", "path", "]", "=", "_normalize_path", "(", "path", ")", "return", "result" ]
abspath with caching .
train
true
24,048
@receiver(PROBLEM_WEIGHTED_SCORE_CHANGED) def score_changed_handler(sender, **kwargs): points_possible = kwargs.get('weighted_possible', None) points_earned = kwargs.get('weighted_earned', None) user_id = kwargs.get('user_id', None) course_id = kwargs.get('course_id', None) usage_id = kwargs.get('usage_id', None) if (None not in (points_earned, points_possible, user_id, course_id)): (course_key, usage_key) = parse_course_and_usage_keys(course_id, usage_id) assignments = increment_assignment_versions(course_key, usage_key, user_id) for assignment in assignments: if (assignment.usage_key == usage_key): send_leaf_outcome.delay(assignment.id, points_earned, points_possible) else: send_composite_outcome.apply_async((user_id, course_id, assignment.id, assignment.version_number), countdown=settings.LTI_AGGREGATE_SCORE_PASSBACK_DELAY) else: log.error('Outcome Service: Required signal parameter is None. points_possible: %s, points_earned: %s, user_id: %s, course_id: %s, usage_id: %s', points_possible, points_earned, user_id, course_id, usage_id)
[ "@", "receiver", "(", "PROBLEM_WEIGHTED_SCORE_CHANGED", ")", "def", "score_changed_handler", "(", "sender", ",", "**", "kwargs", ")", ":", "points_possible", "=", "kwargs", ".", "get", "(", "'weighted_possible'", ",", "None", ")", "points_earned", "=", "kwargs", ".", "get", "(", "'weighted_earned'", ",", "None", ")", "user_id", "=", "kwargs", ".", "get", "(", "'user_id'", ",", "None", ")", "course_id", "=", "kwargs", ".", "get", "(", "'course_id'", ",", "None", ")", "usage_id", "=", "kwargs", ".", "get", "(", "'usage_id'", ",", "None", ")", "if", "(", "None", "not", "in", "(", "points_earned", ",", "points_possible", ",", "user_id", ",", "course_id", ")", ")", ":", "(", "course_key", ",", "usage_key", ")", "=", "parse_course_and_usage_keys", "(", "course_id", ",", "usage_id", ")", "assignments", "=", "increment_assignment_versions", "(", "course_key", ",", "usage_key", ",", "user_id", ")", "for", "assignment", "in", "assignments", ":", "if", "(", "assignment", ".", "usage_key", "==", "usage_key", ")", ":", "send_leaf_outcome", ".", "delay", "(", "assignment", ".", "id", ",", "points_earned", ",", "points_possible", ")", "else", ":", "send_composite_outcome", ".", "apply_async", "(", "(", "user_id", ",", "course_id", ",", "assignment", ".", "id", ",", "assignment", ".", "version_number", ")", ",", "countdown", "=", "settings", ".", "LTI_AGGREGATE_SCORE_PASSBACK_DELAY", ")", "else", ":", "log", ".", "error", "(", "'Outcome Service: Required signal parameter is None. points_possible: %s, points_earned: %s, user_id: %s, course_id: %s, usage_id: %s'", ",", "points_possible", ",", "points_earned", ",", "user_id", ",", "course_id", ",", "usage_id", ")" ]
consume signals that indicate score changes .
train
false
24,049
def proto_library(name, srcs=[], deps=[], optimize=[], deprecated=False, generate_descriptors=False, plugins=[], source_encoding='iso-8859-1', **kwargs): proto_library_target = ProtoLibrary(name, srcs, deps, optimize, deprecated, generate_descriptors, plugins, source_encoding, blade.blade, kwargs) blade.blade.register_target(proto_library_target)
[ "def", "proto_library", "(", "name", ",", "srcs", "=", "[", "]", ",", "deps", "=", "[", "]", ",", "optimize", "=", "[", "]", ",", "deprecated", "=", "False", ",", "generate_descriptors", "=", "False", ",", "plugins", "=", "[", "]", ",", "source_encoding", "=", "'iso-8859-1'", ",", "**", "kwargs", ")", ":", "proto_library_target", "=", "ProtoLibrary", "(", "name", ",", "srcs", ",", "deps", ",", "optimize", ",", "deprecated", ",", "generate_descriptors", ",", "plugins", ",", "source_encoding", ",", "blade", ".", "blade", ",", "kwargs", ")", "blade", ".", "blade", ".", "register_target", "(", "proto_library_target", ")" ]
proto_library target .
train
false
24,050
def stats(request): context = {} context['title'] = _('Weblate statistics') totals = Profile.objects.aggregate(Sum('translated'), Sum('suggested'), Count('id')) total_strings = [] total_words = [] for project in SubProject.objects.iterator(): try: translation_obj = project.translation_set.all()[0] total_strings.append(translation_obj.total) total_words.append(translation_obj.total_words) except IndexError: pass context['total_translations'] = totals['translated__sum'] context['total_suggestions'] = totals['suggested__sum'] context['total_users'] = totals['id__count'] context['total_strings'] = sum(total_strings) context['total_units'] = Unit.objects.count() context['total_words'] = sum(total_words) context['total_languages'] = Language.objects.filter(translation__total__gt=0).distinct().count() context['total_checks'] = Check.objects.count() context['ignored_checks'] = Check.objects.filter(ignore=True).count() top_translations = Profile.objects.order_by('-translated')[:10] top_suggestions = Profile.objects.order_by('-suggested')[:10] context['top_translations'] = top_translations.select_related('user') context['top_suggestions'] = top_suggestions.select_related('user') return render(request, 'stats.html', context)
[ "def", "stats", "(", "request", ")", ":", "context", "=", "{", "}", "context", "[", "'title'", "]", "=", "_", "(", "'Weblate statistics'", ")", "totals", "=", "Profile", ".", "objects", ".", "aggregate", "(", "Sum", "(", "'translated'", ")", ",", "Sum", "(", "'suggested'", ")", ",", "Count", "(", "'id'", ")", ")", "total_strings", "=", "[", "]", "total_words", "=", "[", "]", "for", "project", "in", "SubProject", ".", "objects", ".", "iterator", "(", ")", ":", "try", ":", "translation_obj", "=", "project", ".", "translation_set", ".", "all", "(", ")", "[", "0", "]", "total_strings", ".", "append", "(", "translation_obj", ".", "total", ")", "total_words", ".", "append", "(", "translation_obj", ".", "total_words", ")", "except", "IndexError", ":", "pass", "context", "[", "'total_translations'", "]", "=", "totals", "[", "'translated__sum'", "]", "context", "[", "'total_suggestions'", "]", "=", "totals", "[", "'suggested__sum'", "]", "context", "[", "'total_users'", "]", "=", "totals", "[", "'id__count'", "]", "context", "[", "'total_strings'", "]", "=", "sum", "(", "total_strings", ")", "context", "[", "'total_units'", "]", "=", "Unit", ".", "objects", ".", "count", "(", ")", "context", "[", "'total_words'", "]", "=", "sum", "(", "total_words", ")", "context", "[", "'total_languages'", "]", "=", "Language", ".", "objects", ".", "filter", "(", "translation__total__gt", "=", "0", ")", ".", "distinct", "(", ")", ".", "count", "(", ")", "context", "[", "'total_checks'", "]", "=", "Check", ".", "objects", ".", "count", "(", ")", "context", "[", "'ignored_checks'", "]", "=", "Check", ".", "objects", ".", "filter", "(", "ignore", "=", "True", ")", ".", "count", "(", ")", "top_translations", "=", "Profile", ".", "objects", ".", "order_by", "(", "'-translated'", ")", "[", ":", "10", "]", "top_suggestions", "=", "Profile", ".", "objects", ".", "order_by", "(", "'-suggested'", ")", "[", ":", "10", "]", "context", "[", "'top_translations'", "]", "=", "top_translations", ".", "select_related", "(", "'user'", ")", "context", "[", "'top_suggestions'", "]", "=", "top_suggestions", ".", "select_related", "(", "'user'", ")", "return", "render", "(", "request", ",", "'stats.html'", ",", "context", ")" ]
returns a dictionary containing synchronization details of the ntp peers .
train
false
24,051
def _resolve_dependencies(G): context = {} for name in nx.topological_sort(G): node = G.node[name] try: context[name] = _render(node, context) except Exception as e: LOG.debug('Failed to render %s: %s', name, e, exc_info=True) msg = ('Failed to render parameter "%s": %s' % (name, str(e))) raise ParamException(msg) return context
[ "def", "_resolve_dependencies", "(", "G", ")", ":", "context", "=", "{", "}", "for", "name", "in", "nx", ".", "topological_sort", "(", "G", ")", ":", "node", "=", "G", ".", "node", "[", "name", "]", "try", ":", "context", "[", "name", "]", "=", "_render", "(", "node", ",", "context", ")", "except", "Exception", "as", "e", ":", "LOG", ".", "debug", "(", "'Failed to render %s: %s'", ",", "name", ",", "e", ",", "exc_info", "=", "True", ")", "msg", "=", "(", "'Failed to render parameter \"%s\": %s'", "%", "(", "name", ",", "str", "(", "e", ")", ")", ")", "raise", "ParamException", "(", "msg", ")", "return", "context" ]
traverse the dependency graph starting from resolved nodes .
train
false
24,052
def normpath(path): if (path == ''): return '.' initial_slashes = path.startswith('/') if (initial_slashes and path.startswith('//') and (not path.startswith('///'))): initial_slashes = 2 comps = path.split('/') new_comps = [] for comp in comps: if (comp in ('', '.')): continue if ((comp != '..') or ((not initial_slashes) and (not new_comps)) or (new_comps and (new_comps[(-1)] == '..'))): new_comps.append(comp) elif new_comps: new_comps.pop() comps = new_comps path = '/'.join(comps) if initial_slashes: path = (('/' * initial_slashes) + path) return (path or '.')
[ "def", "normpath", "(", "path", ")", ":", "if", "(", "path", "==", "''", ")", ":", "return", "'.'", "initial_slashes", "=", "path", ".", "startswith", "(", "'/'", ")", "if", "(", "initial_slashes", "and", "path", ".", "startswith", "(", "'//'", ")", "and", "(", "not", "path", ".", "startswith", "(", "'///'", ")", ")", ")", ":", "initial_slashes", "=", "2", "comps", "=", "path", ".", "split", "(", "'/'", ")", "new_comps", "=", "[", "]", "for", "comp", "in", "comps", ":", "if", "(", "comp", "in", "(", "''", ",", "'.'", ")", ")", ":", "continue", "if", "(", "(", "comp", "!=", "'..'", ")", "or", "(", "(", "not", "initial_slashes", ")", "and", "(", "not", "new_comps", ")", ")", "or", "(", "new_comps", "and", "(", "new_comps", "[", "(", "-", "1", ")", "]", "==", "'..'", ")", ")", ")", ":", "new_comps", ".", "append", "(", "comp", ")", "elif", "new_comps", ":", "new_comps", ".", "pop", "(", ")", "comps", "=", "new_comps", "path", "=", "'/'", ".", "join", "(", "comps", ")", "if", "initial_slashes", ":", "path", "=", "(", "(", "'/'", "*", "initial_slashes", ")", "+", "path", ")", "return", "(", "path", "or", "'.'", ")" ]
eliminates double-slashes .
train
false
24,053
@sync_performer def perform_copy_s3_keys(dispatcher, intent): s3 = boto.connect_s3() source_bucket = s3.get_bucket(intent.source_bucket) for key in intent.keys: source_key = source_bucket.get_key((intent.source_prefix + key)) destination_metadata = source_key.metadata for (extention, content_type) in EXTENSION_MIME_TYPES.items(): if key.endswith(extention): destination_metadata['Content-Type'] = content_type break source_key.copy(dst_bucket=intent.destination_bucket, dst_key=(intent.destination_prefix + key), metadata=destination_metadata)
[ "@", "sync_performer", "def", "perform_copy_s3_keys", "(", "dispatcher", ",", "intent", ")", ":", "s3", "=", "boto", ".", "connect_s3", "(", ")", "source_bucket", "=", "s3", ".", "get_bucket", "(", "intent", ".", "source_bucket", ")", "for", "key", "in", "intent", ".", "keys", ":", "source_key", "=", "source_bucket", ".", "get_key", "(", "(", "intent", ".", "source_prefix", "+", "key", ")", ")", "destination_metadata", "=", "source_key", ".", "metadata", "for", "(", "extention", ",", "content_type", ")", "in", "EXTENSION_MIME_TYPES", ".", "items", "(", ")", ":", "if", "key", ".", "endswith", "(", "extention", ")", ":", "destination_metadata", "[", "'Content-Type'", "]", "=", "content_type", "break", "source_key", ".", "copy", "(", "dst_bucket", "=", "intent", ".", "destination_bucket", ",", "dst_key", "=", "(", "intent", ".", "destination_prefix", "+", "key", ")", ",", "metadata", "=", "destination_metadata", ")" ]
see :class:copys3keys .
train
false
24,054
@task(base=BaseInstructorTask) def reset_problem_attempts(entry_id, xmodule_instance_args): action_name = ugettext_noop('reset') update_fcn = partial(reset_attempts_module_state, xmodule_instance_args) visit_fcn = partial(perform_module_state_update, update_fcn, None) return run_main_task(entry_id, visit_fcn, action_name)
[ "@", "task", "(", "base", "=", "BaseInstructorTask", ")", "def", "reset_problem_attempts", "(", "entry_id", ",", "xmodule_instance_args", ")", ":", "action_name", "=", "ugettext_noop", "(", "'reset'", ")", "update_fcn", "=", "partial", "(", "reset_attempts_module_state", ",", "xmodule_instance_args", ")", "visit_fcn", "=", "partial", "(", "perform_module_state_update", ",", "update_fcn", ",", "None", ")", "return", "run_main_task", "(", "entry_id", ",", "visit_fcn", ",", "action_name", ")" ]
resets problem attempts to zero for a particular problem for all students in a course .
train
false
24,055
def supported_langs(): from django.conf import settings return settings.LANGUAGES
[ "def", "supported_langs", "(", ")", ":", "from", "django", ".", "conf", "import", "settings", "return", "settings", ".", "LANGUAGES" ]
returns a list of supported locales .
train
false
24,056
def getLargestInsetLoopFromLoop(loop, radius): loops = getInsetLoopsFromLoop(loop, radius) return euclidean.getLargestLoop(loops)
[ "def", "getLargestInsetLoopFromLoop", "(", "loop", ",", "radius", ")", ":", "loops", "=", "getInsetLoopsFromLoop", "(", "loop", ",", "radius", ")", "return", "euclidean", ".", "getLargestLoop", "(", "loops", ")" ]
get the largest inset loop from the loop .
train
false
24,057
@require_POST def confirm_member(request, url, user_pk): group = get_object_or_404(Group, url=url) profile = get_object_or_404(UserProfile, pk=user_pk) is_curator = (request.user.userprofile in group.curators.all()) is_manager = request.user.userprofile.is_manager group_url = reverse('groups:show_group', args=[group.url]) next_url = request.REQUEST.get('next_url', group_url) if (not (is_curator or is_manager)): raise Http404() try: membership = GroupMembership.objects.get(group=group, userprofile=profile) except GroupMembership.DoesNotExist: messages.error(request, _('This user has not requested membership in this group.')) else: if (membership.status == GroupMembership.MEMBER): messages.error(request, _('This user is already a member of this group.')) else: status = GroupMembership.MEMBER if group.terms: status = GroupMembership.PENDING_TERMS group.add_member(profile, status=status) messages.info(request, _('This user has been added as a member of this group.')) return redirect(next_url)
[ "@", "require_POST", "def", "confirm_member", "(", "request", ",", "url", ",", "user_pk", ")", ":", "group", "=", "get_object_or_404", "(", "Group", ",", "url", "=", "url", ")", "profile", "=", "get_object_or_404", "(", "UserProfile", ",", "pk", "=", "user_pk", ")", "is_curator", "=", "(", "request", ".", "user", ".", "userprofile", "in", "group", ".", "curators", ".", "all", "(", ")", ")", "is_manager", "=", "request", ".", "user", ".", "userprofile", ".", "is_manager", "group_url", "=", "reverse", "(", "'groups:show_group'", ",", "args", "=", "[", "group", ".", "url", "]", ")", "next_url", "=", "request", ".", "REQUEST", ".", "get", "(", "'next_url'", ",", "group_url", ")", "if", "(", "not", "(", "is_curator", "or", "is_manager", ")", ")", ":", "raise", "Http404", "(", ")", "try", ":", "membership", "=", "GroupMembership", ".", "objects", ".", "get", "(", "group", "=", "group", ",", "userprofile", "=", "profile", ")", "except", "GroupMembership", ".", "DoesNotExist", ":", "messages", ".", "error", "(", "request", ",", "_", "(", "'This user has not requested membership in this group.'", ")", ")", "else", ":", "if", "(", "membership", ".", "status", "==", "GroupMembership", ".", "MEMBER", ")", ":", "messages", ".", "error", "(", "request", ",", "_", "(", "'This user is already a member of this group.'", ")", ")", "else", ":", "status", "=", "GroupMembership", ".", "MEMBER", "if", "group", ".", "terms", ":", "status", "=", "GroupMembership", ".", "PENDING_TERMS", "group", ".", "add_member", "(", "profile", ",", "status", "=", "status", ")", "messages", ".", "info", "(", "request", ",", "_", "(", "'This user has been added as a member of this group.'", ")", ")", "return", "redirect", "(", "next_url", ")" ]
add a member to a group who has requested membership .
train
false
24,058
def fft_multiply_repeated(h_fft, x, cuda_dict=dict(use_cuda=False)): if (not cuda_dict['use_cuda']): x = np.real(ifft((h_fft * fft(x)), overwrite_x=True)).ravel() else: cudafft = _get_cudafft() cuda_dict['x'].set(x.astype(np.float64)) cudafft.fft(cuda_dict['x'], cuda_dict['x_fft'], cuda_dict['fft_plan']) _multiply_inplace_c128(h_fft, cuda_dict['x_fft']) cudafft.ifft(cuda_dict['x_fft'], cuda_dict['x'], cuda_dict['ifft_plan'], False) x = np.array(cuda_dict['x'].get(), dtype=x.dtype, subok=True, copy=False) return x
[ "def", "fft_multiply_repeated", "(", "h_fft", ",", "x", ",", "cuda_dict", "=", "dict", "(", "use_cuda", "=", "False", ")", ")", ":", "if", "(", "not", "cuda_dict", "[", "'use_cuda'", "]", ")", ":", "x", "=", "np", ".", "real", "(", "ifft", "(", "(", "h_fft", "*", "fft", "(", "x", ")", ")", ",", "overwrite_x", "=", "True", ")", ")", ".", "ravel", "(", ")", "else", ":", "cudafft", "=", "_get_cudafft", "(", ")", "cuda_dict", "[", "'x'", "]", ".", "set", "(", "x", ".", "astype", "(", "np", ".", "float64", ")", ")", "cudafft", ".", "fft", "(", "cuda_dict", "[", "'x'", "]", ",", "cuda_dict", "[", "'x_fft'", "]", ",", "cuda_dict", "[", "'fft_plan'", "]", ")", "_multiply_inplace_c128", "(", "h_fft", ",", "cuda_dict", "[", "'x_fft'", "]", ")", "cudafft", ".", "ifft", "(", "cuda_dict", "[", "'x_fft'", "]", ",", "cuda_dict", "[", "'x'", "]", ",", "cuda_dict", "[", "'ifft_plan'", "]", ",", "False", ")", "x", "=", "np", ".", "array", "(", "cuda_dict", "[", "'x'", "]", ".", "get", "(", ")", ",", "dtype", "=", "x", ".", "dtype", ",", "subok", "=", "True", ",", "copy", "=", "False", ")", "return", "x" ]
do fft multiplication by a filter function .
train
false
24,059
def _toload_info(path, extrapath, _toload=None): if (_toload is None): assert isinstance(path, list) _toload = ({}, []) for fileordir in path: if (isdir(fileordir) and exists(join(fileordir, '__init__.py'))): subfiles = [join(fileordir, fname) for fname in listdir(fileordir)] _toload_info(subfiles, extrapath, _toload) elif (fileordir[(-3):] == '.py'): modname = _modname_from_path(fileordir, extrapath) _toload[0][modname] = fileordir _toload[1].append((fileordir, modname)) return _toload
[ "def", "_toload_info", "(", "path", ",", "extrapath", ",", "_toload", "=", "None", ")", ":", "if", "(", "_toload", "is", "None", ")", ":", "assert", "isinstance", "(", "path", ",", "list", ")", "_toload", "=", "(", "{", "}", ",", "[", "]", ")", "for", "fileordir", "in", "path", ":", "if", "(", "isdir", "(", "fileordir", ")", "and", "exists", "(", "join", "(", "fileordir", ",", "'__init__.py'", ")", ")", ")", ":", "subfiles", "=", "[", "join", "(", "fileordir", ",", "fname", ")", "for", "fname", "in", "listdir", "(", "fileordir", ")", "]", "_toload_info", "(", "subfiles", ",", "extrapath", ",", "_toload", ")", "elif", "(", "fileordir", "[", "(", "-", "3", ")", ":", "]", "==", "'.py'", ")", ":", "modname", "=", "_modname_from_path", "(", "fileordir", ",", "extrapath", ")", "_toload", "[", "0", "]", "[", "modname", "]", "=", "fileordir", "_toload", "[", "1", "]", ".", "append", "(", "(", "fileordir", ",", "modname", ")", ")", "return", "_toload" ]
return a dictionary of <modname>: <modpath> and an ordered list of to load .
train
false
24,060
def get_cert_serial(cert_file): cmd = 'certutil.exe -verify {0}'.format(cert_file) out = __salt__['cmd.run'](cmd) matches = re.search('Serial: (.*)', out) if (matches is not None): return matches.groups()[0].strip() else: return None
[ "def", "get_cert_serial", "(", "cert_file", ")", ":", "cmd", "=", "'certutil.exe -verify {0}'", ".", "format", "(", "cert_file", ")", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ")", "matches", "=", "re", ".", "search", "(", "'Serial: (.*)'", ",", "out", ")", "if", "(", "matches", "is", "not", "None", ")", ":", "return", "matches", ".", "groups", "(", ")", "[", "0", "]", ".", "strip", "(", ")", "else", ":", "return", "None" ]
get the serial number of a certificate file cert_file the certificate file to find the serial for cli example: .
train
true
24,061
def _get_lut_id(lut, label, use_lut): if (not use_lut): return 1 assert isinstance(label, string_types) mask = (lut['name'] == label.encode('utf-8')) assert (mask.sum() == 1) return lut['id'][mask]
[ "def", "_get_lut_id", "(", "lut", ",", "label", ",", "use_lut", ")", ":", "if", "(", "not", "use_lut", ")", ":", "return", "1", "assert", "isinstance", "(", "label", ",", "string_types", ")", "mask", "=", "(", "lut", "[", "'name'", "]", "==", "label", ".", "encode", "(", "'utf-8'", ")", ")", "assert", "(", "mask", ".", "sum", "(", ")", "==", "1", ")", "return", "lut", "[", "'id'", "]", "[", "mask", "]" ]
convert a label to a lut id number .
train
false
24,062
def vgcsUplinkGrant(): a = TpPd(pd=6) b = MessageType(mesType=9) c = RrCause() d = RequestReference() e = TimingAdvance() packet = ((((a / b) / c) / d) / e) return packet
[ "def", "vgcsUplinkGrant", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "6", ")", "b", "=", "MessageType", "(", "mesType", "=", "9", ")", "c", "=", "RrCause", "(", ")", "d", "=", "RequestReference", "(", ")", "e", "=", "TimingAdvance", "(", ")", "packet", "=", "(", "(", "(", "(", "a", "/", "b", ")", "/", "c", ")", "/", "d", ")", "/", "e", ")", "return", "packet" ]
vgcs uplink grant section 9 .
train
true
24,063
def libvlc_media_player_next_chapter(p_mi): f = (_Cfunctions.get('libvlc_media_player_next_chapter', None) or _Cfunction('libvlc_media_player_next_chapter', ((1,),), None, None, MediaPlayer)) return f(p_mi)
[ "def", "libvlc_media_player_next_chapter", "(", "p_mi", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_media_player_next_chapter'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_media_player_next_chapter'", ",", "(", "(", "1", ",", ")", ",", ")", ",", "None", ",", "None", ",", "MediaPlayer", ")", ")", "return", "f", "(", "p_mi", ")" ]
set next chapter .
train
false
24,064
def text_to_dict(text): res = {} if (not text): return res for line in text.splitlines(): line = line.strip() if (line and (not line.startswith('#'))): (key, value) = [w.strip() for w in line.split('=', 1)] if (key in res): try: res[key].append(value) except AttributeError: res[key] = [res[key], value] else: res[key] = value return res
[ "def", "text_to_dict", "(", "text", ")", ":", "res", "=", "{", "}", "if", "(", "not", "text", ")", ":", "return", "res", "for", "line", "in", "text", ".", "splitlines", "(", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "(", "line", "and", "(", "not", "line", ".", "startswith", "(", "'#'", ")", ")", ")", ":", "(", "key", ",", "value", ")", "=", "[", "w", ".", "strip", "(", ")", "for", "w", "in", "line", ".", "split", "(", "'='", ",", "1", ")", "]", "if", "(", "key", "in", "res", ")", ":", "try", ":", "res", "[", "key", "]", ".", "append", "(", "value", ")", "except", "AttributeError", ":", "res", "[", "key", "]", "=", "[", "res", "[", "key", "]", ",", "value", "]", "else", ":", "res", "[", "key", "]", "=", "value", "return", "res" ]
parse multilines text containing simple key=value lines and return a dict of {key: value} .
train
false
24,066
def make_exchange_func(a, b): updates = OrderedDict() updates[a] = b updates[b] = a f = function([], updates=updates) return f
[ "def", "make_exchange_func", "(", "a", ",", "b", ")", ":", "updates", "=", "OrderedDict", "(", ")", "updates", "[", "a", "]", "=", "b", "updates", "[", "b", "]", "=", "a", "f", "=", "function", "(", "[", "]", ",", "updates", "=", "updates", ")", "return", "f" ]
a: a theano shared variable b: a theano shared variable returns f where f is a theano function .
train
false
24,067
def dup_euclidean_prs(f, g, K): prs = [f, g] h = dup_rem(f, g, K) while h: prs.append(h) (f, g) = (g, h) h = dup_rem(f, g, K) return prs
[ "def", "dup_euclidean_prs", "(", "f", ",", "g", ",", "K", ")", ":", "prs", "=", "[", "f", ",", "g", "]", "h", "=", "dup_rem", "(", "f", ",", "g", ",", "K", ")", "while", "h", ":", "prs", ".", "append", "(", "h", ")", "(", "f", ",", "g", ")", "=", "(", "g", ",", "h", ")", "h", "=", "dup_rem", "(", "f", ",", "g", ",", "K", ")", "return", "prs" ]
euclidean polynomial remainder sequence in k[x] .
train
false
24,069
def msg_file(package, type_): return roslib.packages.resource_file(package, 'msg', (type_ + EXT))
[ "def", "msg_file", "(", "package", ",", "type_", ")", ":", "return", "roslib", ".", "packages", ".", "resource_file", "(", "package", ",", "'msg'", ",", "(", "type_", "+", "EXT", ")", ")" ]
determine the file system path for the specified .
train
false
24,071
def _usec_to_sec(t_sec): return (t_sec / 1000000.0)
[ "def", "_usec_to_sec", "(", "t_sec", ")", ":", "return", "(", "t_sec", "/", "1000000.0", ")" ]
converts a time in usec to seconds since the epoch .
train
false
24,072
def printProgressByString(progressString): sys.stdout.write(progressString) sys.stdout.write((chr(27) + '\r')) sys.stdout.flush()
[ "def", "printProgressByString", "(", "progressString", ")", ":", "sys", ".", "stdout", ".", "write", "(", "progressString", ")", "sys", ".", "stdout", ".", "write", "(", "(", "chr", "(", "27", ")", "+", "'\\r'", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")" ]
print progress string .
train
false
24,075
def s_delim(value, fuzzable=True, name=None): delim = primitives.delim(value, fuzzable, name) blocks.CURRENT.push(delim)
[ "def", "s_delim", "(", "value", ",", "fuzzable", "=", "True", ",", "name", "=", "None", ")", ":", "delim", "=", "primitives", ".", "delim", "(", "value", ",", "fuzzable", ",", "name", ")", "blocks", ".", "CURRENT", ".", "push", "(", "delim", ")" ]
push a delimiter onto the current block stack .
train
false
24,076
def image_member_count(context, image_id): session = get_session() if (not image_id): msg = _('Image id is required.') raise exception.Invalid(msg) query = session.query(models.ImageMember) query = query.filter_by(deleted=False) query = query.filter((models.ImageMember.image_id == str(image_id))) return query.count()
[ "def", "image_member_count", "(", "context", ",", "image_id", ")", ":", "session", "=", "get_session", "(", ")", "if", "(", "not", "image_id", ")", ":", "msg", "=", "_", "(", "'Image id is required.'", ")", "raise", "exception", ".", "Invalid", "(", "msg", ")", "query", "=", "session", ".", "query", "(", "models", ".", "ImageMember", ")", "query", "=", "query", ".", "filter_by", "(", "deleted", "=", "False", ")", "query", "=", "query", ".", "filter", "(", "(", "models", ".", "ImageMember", ".", "image_id", "==", "str", "(", "image_id", ")", ")", ")", "return", "query", ".", "count", "(", ")" ]
return the number of image members for this image .
train
false
24,077
@click.command('remote-urls') def remote_urls(): for app in get_apps(): repo_dir = get_repo_dir(app) if os.path.exists(os.path.join(repo_dir, '.git')): remote = get_remote(app) remote_url = subprocess.check_output(['git', 'config', '--get', 'remote.{}.url'.format(remote)], cwd=repo_dir).strip() print '{app} DCTB {remote_url}'.format(app=app, remote_url=remote_url)
[ "@", "click", ".", "command", "(", "'remote-urls'", ")", "def", "remote_urls", "(", ")", ":", "for", "app", "in", "get_apps", "(", ")", ":", "repo_dir", "=", "get_repo_dir", "(", "app", ")", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "repo_dir", ",", "'.git'", ")", ")", ":", "remote", "=", "get_remote", "(", "app", ")", "remote_url", "=", "subprocess", ".", "check_output", "(", "[", "'git'", ",", "'config'", ",", "'--get'", ",", "'remote.{}.url'", ".", "format", "(", "remote", ")", "]", ",", "cwd", "=", "repo_dir", ")", ".", "strip", "(", ")", "print", "'{app} DCTB {remote_url}'", ".", "format", "(", "app", "=", "app", ",", "remote_url", "=", "remote_url", ")" ]
show apps remote url .
train
false
24,078
def perm(N, k, exact=False): if exact: if ((k > N) or (N < 0) or (k < 0)): return 0 val = 1 for i in xrange(((N - k) + 1), (N + 1)): val *= i return val else: (k, N) = (asarray(k), asarray(N)) cond = (((k <= N) & (N >= 0)) & (k >= 0)) vals = poch(((N - k) + 1), k) if isinstance(vals, np.ndarray): vals[(~ cond)] = 0 elif (not cond): vals = np.float64(0) return vals
[ "def", "perm", "(", "N", ",", "k", ",", "exact", "=", "False", ")", ":", "if", "exact", ":", "if", "(", "(", "k", ">", "N", ")", "or", "(", "N", "<", "0", ")", "or", "(", "k", "<", "0", ")", ")", ":", "return", "0", "val", "=", "1", "for", "i", "in", "xrange", "(", "(", "(", "N", "-", "k", ")", "+", "1", ")", ",", "(", "N", "+", "1", ")", ")", ":", "val", "*=", "i", "return", "val", "else", ":", "(", "k", ",", "N", ")", "=", "(", "asarray", "(", "k", ")", ",", "asarray", "(", "N", ")", ")", "cond", "=", "(", "(", "(", "k", "<=", "N", ")", "&", "(", "N", ">=", "0", ")", ")", "&", "(", "k", ">=", "0", ")", ")", "vals", "=", "poch", "(", "(", "(", "N", "-", "k", ")", "+", "1", ")", ",", "k", ")", "if", "isinstance", "(", "vals", ",", "np", ".", "ndarray", ")", ":", "vals", "[", "(", "~", "cond", ")", "]", "=", "0", "elif", "(", "not", "cond", ")", ":", "vals", "=", "np", ".", "float64", "(", "0", ")", "return", "vals" ]
permutations of n things taken k at a time .
train
false
24,079
def rotmat(p, q): rot = numpy.dot(refmat(q, (- p)), refmat(p, (- p))) return rot
[ "def", "rotmat", "(", "p", ",", "q", ")", ":", "rot", "=", "numpy", ".", "dot", "(", "refmat", "(", "q", ",", "(", "-", "p", ")", ")", ",", "refmat", "(", "p", ",", "(", "-", "p", ")", ")", ")", "return", "rot" ]
return a matrix that rotates p onto q .
train
false
24,080
def api_url_for(view_name, _absolute=False, _xml=False, _internal=False, *args, **kwargs): renderer = ('XMLRenderer' if _xml else 'JSONRenderer') url = url_for('{0}__{1}'.format(renderer, view_name), *args, **kwargs) if _absolute: domain = (website_settings.INTERNAL_DOMAIN if _internal else website_settings.DOMAIN) return urlparse.urljoin(domain, url) return url
[ "def", "api_url_for", "(", "view_name", ",", "_absolute", "=", "False", ",", "_xml", "=", "False", ",", "_internal", "=", "False", ",", "*", "args", ",", "**", "kwargs", ")", ":", "renderer", "=", "(", "'XMLRenderer'", "if", "_xml", "else", "'JSONRenderer'", ")", "url", "=", "url_for", "(", "'{0}__{1}'", ".", "format", "(", "renderer", ",", "view_name", ")", ",", "*", "args", ",", "**", "kwargs", ")", "if", "_absolute", ":", "domain", "=", "(", "website_settings", ".", "INTERNAL_DOMAIN", "if", "_internal", "else", "website_settings", ".", "DOMAIN", ")", "return", "urlparse", ".", "urljoin", "(", "domain", ",", "url", ")", "return", "url" ]
reverse url lookup for api routes .
train
false
24,081
def rename_key(pki_dir, id_, new_id): oldkey = os.path.join(pki_dir, 'minions', id_) newkey = os.path.join(pki_dir, 'minions', new_id) if os.path.isfile(oldkey): os.rename(oldkey, newkey)
[ "def", "rename_key", "(", "pki_dir", ",", "id_", ",", "new_id", ")", ":", "oldkey", "=", "os", ".", "path", ".", "join", "(", "pki_dir", ",", "'minions'", ",", "id_", ")", "newkey", "=", "os", ".", "path", ".", "join", "(", "pki_dir", ",", "'minions'", ",", "new_id", ")", "if", "os", ".", "path", ".", "isfile", "(", "oldkey", ")", ":", "os", ".", "rename", "(", "oldkey", ",", "newkey", ")" ]
rename a key .
train
true
24,083
def entries_published(queryset): now = timezone.now() return queryset.filter((models.Q(start_publication__lte=now) | models.Q(start_publication=None)), (models.Q(end_publication__gt=now) | models.Q(end_publication=None)), status=PUBLISHED, sites=Site.objects.get_current())
[ "def", "entries_published", "(", "queryset", ")", ":", "now", "=", "timezone", ".", "now", "(", ")", "return", "queryset", ".", "filter", "(", "(", "models", ".", "Q", "(", "start_publication__lte", "=", "now", ")", "|", "models", ".", "Q", "(", "start_publication", "=", "None", ")", ")", ",", "(", "models", ".", "Q", "(", "end_publication__gt", "=", "now", ")", "|", "models", ".", "Q", "(", "end_publication", "=", "None", ")", ")", ",", "status", "=", "PUBLISHED", ",", "sites", "=", "Site", ".", "objects", ".", "get_current", "(", ")", ")" ]
return only the entries published .
train
true
24,084
def required_event_fields(next_value_columns, previous_value_columns): return {TS_FIELD_NAME, SID_FIELD_NAME, EVENT_DATE_FIELD_NAME}.union(viewvalues(next_value_columns), viewvalues(previous_value_columns))
[ "def", "required_event_fields", "(", "next_value_columns", ",", "previous_value_columns", ")", ":", "return", "{", "TS_FIELD_NAME", ",", "SID_FIELD_NAME", ",", "EVENT_DATE_FIELD_NAME", "}", ".", "union", "(", "viewvalues", "(", "next_value_columns", ")", ",", "viewvalues", "(", "previous_value_columns", ")", ")" ]
compute the set of resource columns required to serve next_value_columns and previous_value_columns .
train
true
24,085
def setup_test_environment(): Template.original_render = Template.render Template.render = instrumented_test_render
[ "def", "setup_test_environment", "(", ")", ":", "Template", ".", "original_render", "=", "Template", ".", "render", "Template", ".", "render", "=", "instrumented_test_render" ]
perform global pre-test setup .
train
false
24,088
def graphics_listen_addrs(migrate_data): listen_addrs = None if (migrate_data.obj_attr_is_set('graphics_listen_addr_vnc') or migrate_data.obj_attr_is_set('graphics_listen_addr_spice')): listen_addrs = {'vnc': None, 'spice': None} if migrate_data.obj_attr_is_set('graphics_listen_addr_vnc'): listen_addrs['vnc'] = str(migrate_data.graphics_listen_addr_vnc) if migrate_data.obj_attr_is_set('graphics_listen_addr_spice'): listen_addrs['spice'] = str(migrate_data.graphics_listen_addr_spice) return listen_addrs
[ "def", "graphics_listen_addrs", "(", "migrate_data", ")", ":", "listen_addrs", "=", "None", "if", "(", "migrate_data", ".", "obj_attr_is_set", "(", "'graphics_listen_addr_vnc'", ")", "or", "migrate_data", ".", "obj_attr_is_set", "(", "'graphics_listen_addr_spice'", ")", ")", ":", "listen_addrs", "=", "{", "'vnc'", ":", "None", ",", "'spice'", ":", "None", "}", "if", "migrate_data", ".", "obj_attr_is_set", "(", "'graphics_listen_addr_vnc'", ")", ":", "listen_addrs", "[", "'vnc'", "]", "=", "str", "(", "migrate_data", ".", "graphics_listen_addr_vnc", ")", "if", "migrate_data", ".", "obj_attr_is_set", "(", "'graphics_listen_addr_spice'", ")", ":", "listen_addrs", "[", "'spice'", "]", "=", "str", "(", "migrate_data", ".", "graphics_listen_addr_spice", ")", "return", "listen_addrs" ]
returns listen addresses of vnc/spice from a libvirtlivemigratedata .
train
false
24,091
def get_community_names(): ret = dict() current_values = __salt__['reg.list_values'](_HKEY, _COMMUNITIES_KEY, include_default=False) for current_value in current_values: permissions = str() for permission_name in _PERMISSION_TYPES: if (current_value['vdata'] == _PERMISSION_TYPES[permission_name]): permissions = permission_name break ret[current_value['vname']] = permissions if (not ret): _LOG.debug('Unable to find existing communities.') return ret
[ "def", "get_community_names", "(", ")", ":", "ret", "=", "dict", "(", ")", "current_values", "=", "__salt__", "[", "'reg.list_values'", "]", "(", "_HKEY", ",", "_COMMUNITIES_KEY", ",", "include_default", "=", "False", ")", "for", "current_value", "in", "current_values", ":", "permissions", "=", "str", "(", ")", "for", "permission_name", "in", "_PERMISSION_TYPES", ":", "if", "(", "current_value", "[", "'vdata'", "]", "==", "_PERMISSION_TYPES", "[", "permission_name", "]", ")", ":", "permissions", "=", "permission_name", "break", "ret", "[", "current_value", "[", "'vname'", "]", "]", "=", "permissions", "if", "(", "not", "ret", ")", ":", "_LOG", ".", "debug", "(", "'Unable to find existing communities.'", ")", "return", "ret" ]
get the current accepted snmp community names and their permissions .
train
false
24,093
def date_cast(date): if (date is None): return datetime.datetime.now() elif isinstance(date, datetime.datetime): return date try: if isinstance(date, six.string_types): try: if HAS_TIMELIB: return timelib.strtodatetime(to_bytes(date)) except ValueError: pass if date.isdigit(): date = int(date) else: date = float(date) return datetime.datetime.fromtimestamp(date) except Exception: if HAS_TIMELIB: raise ValueError('Unable to parse {0}'.format(date)) raise RuntimeError('Unable to parse {0}. Consider installing timelib'.format(date))
[ "def", "date_cast", "(", "date", ")", ":", "if", "(", "date", "is", "None", ")", ":", "return", "datetime", ".", "datetime", ".", "now", "(", ")", "elif", "isinstance", "(", "date", ",", "datetime", ".", "datetime", ")", ":", "return", "date", "try", ":", "if", "isinstance", "(", "date", ",", "six", ".", "string_types", ")", ":", "try", ":", "if", "HAS_TIMELIB", ":", "return", "timelib", ".", "strtodatetime", "(", "to_bytes", "(", "date", ")", ")", "except", "ValueError", ":", "pass", "if", "date", ".", "isdigit", "(", ")", ":", "date", "=", "int", "(", "date", ")", "else", ":", "date", "=", "float", "(", "date", ")", "return", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "date", ")", "except", "Exception", ":", "if", "HAS_TIMELIB", ":", "raise", "ValueError", "(", "'Unable to parse {0}'", ".", "format", "(", "date", ")", ")", "raise", "RuntimeError", "(", "'Unable to parse {0}. Consider installing timelib'", ".", "format", "(", "date", ")", ")" ]
casts any object into a datetime .
train
true
24,094
def _tstat_generic(value1, value2, std_diff, dof, alternative, diff=0): tstat = (((value1 - value2) - diff) / std_diff) if (alternative in ['two-sided', '2-sided', '2s']): pvalue = (stats.t.sf(np.abs(tstat), dof) * 2) elif (alternative in ['larger', 'l']): pvalue = stats.t.sf(tstat, dof) elif (alternative in ['smaller', 's']): pvalue = stats.t.cdf(tstat, dof) else: raise ValueError('invalid alternative') return (tstat, pvalue)
[ "def", "_tstat_generic", "(", "value1", ",", "value2", ",", "std_diff", ",", "dof", ",", "alternative", ",", "diff", "=", "0", ")", ":", "tstat", "=", "(", "(", "(", "value1", "-", "value2", ")", "-", "diff", ")", "/", "std_diff", ")", "if", "(", "alternative", "in", "[", "'two-sided'", ",", "'2-sided'", ",", "'2s'", "]", ")", ":", "pvalue", "=", "(", "stats", ".", "t", ".", "sf", "(", "np", ".", "abs", "(", "tstat", ")", ",", "dof", ")", "*", "2", ")", "elif", "(", "alternative", "in", "[", "'larger'", ",", "'l'", "]", ")", ":", "pvalue", "=", "stats", ".", "t", ".", "sf", "(", "tstat", ",", "dof", ")", "elif", "(", "alternative", "in", "[", "'smaller'", ",", "'s'", "]", ")", ":", "pvalue", "=", "stats", ".", "t", ".", "cdf", "(", "tstat", ",", "dof", ")", "else", ":", "raise", "ValueError", "(", "'invalid alternative'", ")", "return", "(", "tstat", ",", "pvalue", ")" ]
generic ttest to save typing .
train
false
24,095
def _transform_DE_RE(DE, g, k, order, syms): from sympy.solvers.solveset import linsolve RE = hyper_re(DE, g, k) eq = [] for i in range(1, order): coeff = RE.coeff(g((k + i))) eq.append(coeff) sol = dict(zip(syms, (i for s in linsolve(eq, list(syms)) for i in s))) if sol: m = Wild('m') RE = RE.subs(sol) RE = RE.factor().as_numer_denom()[0].collect(g((k + m))) RE = RE.as_coeff_mul(g)[1][0] for i in range(order): if (RE.coeff(g((k + i))) and i): RE = RE.subs(k, (k - i)) break return RE
[ "def", "_transform_DE_RE", "(", "DE", ",", "g", ",", "k", ",", "order", ",", "syms", ")", ":", "from", "sympy", ".", "solvers", ".", "solveset", "import", "linsolve", "RE", "=", "hyper_re", "(", "DE", ",", "g", ",", "k", ")", "eq", "=", "[", "]", "for", "i", "in", "range", "(", "1", ",", "order", ")", ":", "coeff", "=", "RE", ".", "coeff", "(", "g", "(", "(", "k", "+", "i", ")", ")", ")", "eq", ".", "append", "(", "coeff", ")", "sol", "=", "dict", "(", "zip", "(", "syms", ",", "(", "i", "for", "s", "in", "linsolve", "(", "eq", ",", "list", "(", "syms", ")", ")", "for", "i", "in", "s", ")", ")", ")", "if", "sol", ":", "m", "=", "Wild", "(", "'m'", ")", "RE", "=", "RE", ".", "subs", "(", "sol", ")", "RE", "=", "RE", ".", "factor", "(", ")", ".", "as_numer_denom", "(", ")", "[", "0", "]", ".", "collect", "(", "g", "(", "(", "k", "+", "m", ")", ")", ")", "RE", "=", "RE", ".", "as_coeff_mul", "(", "g", ")", "[", "1", "]", "[", "0", "]", "for", "i", "in", "range", "(", "order", ")", ":", "if", "(", "RE", ".", "coeff", "(", "g", "(", "(", "k", "+", "i", ")", ")", ")", "and", "i", ")", ":", "RE", "=", "RE", ".", "subs", "(", "k", ",", "(", "k", "-", "i", ")", ")", "break", "return", "RE" ]
converts de with free parameters into re of hypergeometric type .
train
false
24,097
def deduplicate_cities(city, dup_city): users = dup_city.userprofile_set.all() if users.exists(): users.update(geo_city=city, geo_region=city.region, geo_country=city.country) dup_city.delete()
[ "def", "deduplicate_cities", "(", "city", ",", "dup_city", ")", ":", "users", "=", "dup_city", ".", "userprofile_set", ".", "all", "(", ")", "if", "users", ".", "exists", "(", ")", ":", "users", ".", "update", "(", "geo_city", "=", "city", ",", "geo_region", "=", "city", ".", "region", ",", "geo_country", "=", "city", ".", "country", ")", "dup_city", ".", "delete", "(", ")" ]
given 2 city instances .
train
false
24,098
def mail_decode(src_ip_port, dst_ip_port, mail_creds): try: decoded = base64.b64decode(mail_creds).replace('\x00', ' ').decode('utf8') decoded = decoded.replace('\x00', ' ') except TypeError: decoded = None except UnicodeDecodeError as e: decoded = None if (decoded != None): msg = ('Decoded: %s' % decoded) printer(src_ip_port, dst_ip_port, msg)
[ "def", "mail_decode", "(", "src_ip_port", ",", "dst_ip_port", ",", "mail_creds", ")", ":", "try", ":", "decoded", "=", "base64", ".", "b64decode", "(", "mail_creds", ")", ".", "replace", "(", "'\\x00'", ",", "' '", ")", ".", "decode", "(", "'utf8'", ")", "decoded", "=", "decoded", ".", "replace", "(", "'\\x00'", ",", "' '", ")", "except", "TypeError", ":", "decoded", "=", "None", "except", "UnicodeDecodeError", "as", "e", ":", "decoded", "=", "None", "if", "(", "decoded", "!=", "None", ")", ":", "msg", "=", "(", "'Decoded: %s'", "%", "decoded", ")", "printer", "(", "src_ip_port", ",", "dst_ip_port", ",", "msg", ")" ]
decode base64 mail creds .
train
false
24,099
def update_languages(): app = get_app() update_all_languages(apath(app, r=request)) session.flash = T('Language files (static strings) updated') redirect(URL('design', args=app, anchor='languages'))
[ "def", "update_languages", "(", ")", ":", "app", "=", "get_app", "(", ")", "update_all_languages", "(", "apath", "(", "app", ",", "r", "=", "request", ")", ")", "session", ".", "flash", "=", "T", "(", "'Language files (static strings) updated'", ")", "redirect", "(", "URL", "(", "'design'", ",", "args", "=", "app", ",", "anchor", "=", "'languages'", ")", ")" ]
update available languages .
train
false
24,100
def _decimal_to_Rational_prec(dec): if (not dec.is_finite()): raise TypeError(('dec must be finite, got %s.' % dec)) (s, d, e) = dec.as_tuple() prec = len(d) if (e >= 0): rv = Integer(int(dec)) else: s = ((-1) ** s) d = sum([(di * (10 ** i)) for (i, di) in enumerate(reversed(d))]) rv = Rational((s * d), (10 ** (- e))) return (rv, prec)
[ "def", "_decimal_to_Rational_prec", "(", "dec", ")", ":", "if", "(", "not", "dec", ".", "is_finite", "(", ")", ")", ":", "raise", "TypeError", "(", "(", "'dec must be finite, got %s.'", "%", "dec", ")", ")", "(", "s", ",", "d", ",", "e", ")", "=", "dec", ".", "as_tuple", "(", ")", "prec", "=", "len", "(", "d", ")", "if", "(", "e", ">=", "0", ")", ":", "rv", "=", "Integer", "(", "int", "(", "dec", ")", ")", "else", ":", "s", "=", "(", "(", "-", "1", ")", "**", "s", ")", "d", "=", "sum", "(", "[", "(", "di", "*", "(", "10", "**", "i", ")", ")", "for", "(", "i", ",", "di", ")", "in", "enumerate", "(", "reversed", "(", "d", ")", ")", "]", ")", "rv", "=", "Rational", "(", "(", "s", "*", "d", ")", ",", "(", "10", "**", "(", "-", "e", ")", ")", ")", "return", "(", "rv", ",", "prec", ")" ]
convert an ordinary decimal instance to a rational .
train
false
24,101
def test_presentation_init(presentation_model): presentation = presentation_model presentation.initialize_view() assert (presentation.view.heading_title == presentation.model.heading_title) assert (presentation.view.heading_subtitle == presentation.model.heading_subtitle) assert presentation.view.required_section.populate.called assert presentation.view.optional_section.populate.called assert (not presentation.view.set_list_contents.called)
[ "def", "test_presentation_init", "(", "presentation_model", ")", ":", "presentation", "=", "presentation_model", "presentation", ".", "initialize_view", "(", ")", "assert", "(", "presentation", ".", "view", ".", "heading_title", "==", "presentation", ".", "model", ".", "heading_title", ")", "assert", "(", "presentation", ".", "view", ".", "heading_subtitle", "==", "presentation", ".", "model", ".", "heading_subtitle", ")", "assert", "presentation", ".", "view", ".", "required_section", ".", "populate", ".", "called", "assert", "presentation", ".", "view", ".", "optional_section", ".", "populate", ".", "called", "assert", "(", "not", "presentation", ".", "view", ".", "set_list_contents", ".", "called", ")" ]
sanity check that the primary fields are set on init .
train
false
24,102
def adjacency_matrix(G, nodelist=None, weight='weight'): return nx.to_scipy_sparse_matrix(G, nodelist=nodelist, weight=weight)
[ "def", "adjacency_matrix", "(", "G", ",", "nodelist", "=", "None", ",", "weight", "=", "'weight'", ")", ":", "return", "nx", ".", "to_scipy_sparse_matrix", "(", "G", ",", "nodelist", "=", "nodelist", ",", "weight", "=", "weight", ")" ]
return adjacency matrix of g .
train
false
24,103
def decode_unicode(input): if isinstance(input, dict): temp = {} for (key, value) in sorted(six.iteritems(input)): temp[decode_unicode(key)] = decode_unicode(value) return temp elif isinstance(input, (tuple, list)): return [decode_unicode(element) for element in input] elif isinstance(input, six.text_type): return input.encode('utf-8') elif (six.PY3 and isinstance(input, six.binary_type)): return input.decode('utf-8') else: return input
[ "def", "decode_unicode", "(", "input", ")", ":", "if", "isinstance", "(", "input", ",", "dict", ")", ":", "temp", "=", "{", "}", "for", "(", "key", ",", "value", ")", "in", "sorted", "(", "six", ".", "iteritems", "(", "input", ")", ")", ":", "temp", "[", "decode_unicode", "(", "key", ")", "]", "=", "decode_unicode", "(", "value", ")", "return", "temp", "elif", "isinstance", "(", "input", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "[", "decode_unicode", "(", "element", ")", "for", "element", "in", "input", "]", "elif", "isinstance", "(", "input", ",", "six", ".", "text_type", ")", ":", "return", "input", ".", "encode", "(", "'utf-8'", ")", "elif", "(", "six", ".", "PY3", "and", "isinstance", "(", "input", ",", "six", ".", "binary_type", ")", ")", ":", "return", "input", ".", "decode", "(", "'utf-8'", ")", "else", ":", "return", "input" ]
decode the unicode of the message .
train
false
24,106
def isXRDS(xrd_tree): root = xrd_tree.getroot() return (root.tag == root_tag)
[ "def", "isXRDS", "(", "xrd_tree", ")", ":", "root", "=", "xrd_tree", ".", "getroot", "(", ")", "return", "(", "root", ".", "tag", "==", "root_tag", ")" ]
is this document an xrds document? .
train
false
24,107
def _imp_namespace(expr, namespace=None): from sympy.core.function import FunctionClass if (namespace is None): namespace = {} if is_sequence(expr): for arg in expr: _imp_namespace(arg, namespace) return namespace elif isinstance(expr, dict): for (key, val) in expr.items(): _imp_namespace(key, namespace) _imp_namespace(val, namespace) return namespace func = getattr(expr, 'func', None) if isinstance(func, FunctionClass): imp = getattr(func, '_imp_', None) if (imp is not None): name = expr.func.__name__ if ((name in namespace) and (namespace[name] != imp)): raise ValueError(('We found more than one implementation with name "%s"' % name)) namespace[name] = imp if hasattr(expr, 'args'): for arg in expr.args: _imp_namespace(arg, namespace) return namespace
[ "def", "_imp_namespace", "(", "expr", ",", "namespace", "=", "None", ")", ":", "from", "sympy", ".", "core", ".", "function", "import", "FunctionClass", "if", "(", "namespace", "is", "None", ")", ":", "namespace", "=", "{", "}", "if", "is_sequence", "(", "expr", ")", ":", "for", "arg", "in", "expr", ":", "_imp_namespace", "(", "arg", ",", "namespace", ")", "return", "namespace", "elif", "isinstance", "(", "expr", ",", "dict", ")", ":", "for", "(", "key", ",", "val", ")", "in", "expr", ".", "items", "(", ")", ":", "_imp_namespace", "(", "key", ",", "namespace", ")", "_imp_namespace", "(", "val", ",", "namespace", ")", "return", "namespace", "func", "=", "getattr", "(", "expr", ",", "'func'", ",", "None", ")", "if", "isinstance", "(", "func", ",", "FunctionClass", ")", ":", "imp", "=", "getattr", "(", "func", ",", "'_imp_'", ",", "None", ")", "if", "(", "imp", "is", "not", "None", ")", ":", "name", "=", "expr", ".", "func", ".", "__name__", "if", "(", "(", "name", "in", "namespace", ")", "and", "(", "namespace", "[", "name", "]", "!=", "imp", ")", ")", ":", "raise", "ValueError", "(", "(", "'We found more than one implementation with name \"%s\"'", "%", "name", ")", ")", "namespace", "[", "name", "]", "=", "imp", "if", "hasattr", "(", "expr", ",", "'args'", ")", ":", "for", "arg", "in", "expr", ".", "args", ":", "_imp_namespace", "(", "arg", ",", "namespace", ")", "return", "namespace" ]
return namespace dict with function implementations we need to search for functions in anything that can be thrown at us - that is - anything that could be passed as expr .
train
false
24,111
def nanargmax(values, axis=None, skipna=True): (values, mask, dtype, _) = _get_values(values, skipna, fill_value_typ='-inf', isfinite=True) result = values.argmax(axis) result = _maybe_arg_null_out(result, axis, mask, skipna) return result
[ "def", "nanargmax", "(", "values", ",", "axis", "=", "None", ",", "skipna", "=", "True", ")", ":", "(", "values", ",", "mask", ",", "dtype", ",", "_", ")", "=", "_get_values", "(", "values", ",", "skipna", ",", "fill_value_typ", "=", "'-inf'", ",", "isfinite", "=", "True", ")", "result", "=", "values", ".", "argmax", "(", "axis", ")", "result", "=", "_maybe_arg_null_out", "(", "result", ",", "axis", ",", "mask", ",", "skipna", ")", "return", "result" ]
returns -1 in the na case .
train
true
24,112
def with_appcontext(f): @click.pass_context def decorator(__ctx, *args, **kwargs): with __ctx.ensure_object(ScriptInfo).load_app().app_context(): return __ctx.invoke(f, *args, **kwargs) return update_wrapper(decorator, f)
[ "def", "with_appcontext", "(", "f", ")", ":", "@", "click", ".", "pass_context", "def", "decorator", "(", "__ctx", ",", "*", "args", ",", "**", "kwargs", ")", ":", "with", "__ctx", ".", "ensure_object", "(", "ScriptInfo", ")", ".", "load_app", "(", ")", ".", "app_context", "(", ")", ":", "return", "__ctx", ".", "invoke", "(", "f", ",", "*", "args", ",", "**", "kwargs", ")", "return", "update_wrapper", "(", "decorator", ",", "f", ")" ]
wraps a callback so that its guaranteed to be executed with the scripts application context .
train
false
24,113
def _get_int64(data, position, dummy0, dummy1, dummy2): end = (position + 8) return (Int64(_UNPACK_LONG(data[position:end])[0]), end)
[ "def", "_get_int64", "(", "data", ",", "position", ",", "dummy0", ",", "dummy1", ",", "dummy2", ")", ":", "end", "=", "(", "position", "+", "8", ")", "return", "(", "Int64", "(", "_UNPACK_LONG", "(", "data", "[", "position", ":", "end", "]", ")", "[", "0", "]", ")", ",", "end", ")" ]
decode a bson int64 to bson .
train
true
24,114
def ErrorUpdate(msg): PrintUpdate(msg)
[ "def", "ErrorUpdate", "(", "msg", ")", ":", "PrintUpdate", "(", "msg", ")" ]
print an error message to stderr .
train
false
24,115
def test_softsign(): def softsign(x): return np.divide(x, (np.ones_like(x) + np.absolute(x))) x = K.placeholder(ndim=2) f = K.function([x], [activations.softsign(x)]) test_values = get_standard_values() result = f([test_values])[0] expected = softsign(test_values) assert_allclose(result, expected, rtol=1e-05)
[ "def", "test_softsign", "(", ")", ":", "def", "softsign", "(", "x", ")", ":", "return", "np", ".", "divide", "(", "x", ",", "(", "np", ".", "ones_like", "(", "x", ")", "+", "np", ".", "absolute", "(", "x", ")", ")", ")", "x", "=", "K", ".", "placeholder", "(", "ndim", "=", "2", ")", "f", "=", "K", ".", "function", "(", "[", "x", "]", ",", "[", "activations", ".", "softsign", "(", "x", ")", "]", ")", "test_values", "=", "get_standard_values", "(", ")", "result", "=", "f", "(", "[", "test_values", "]", ")", "[", "0", "]", "expected", "=", "softsign", "(", "test_values", ")", "assert_allclose", "(", "result", ",", "expected", ",", "rtol", "=", "1e-05", ")" ]
test using a reference softsign implementation .
train
false
24,116
def _rename_dask(df, names): assert isinstance(df, _Frame) metadata = _rename(names, df._meta) name = 'rename-{0}'.format(tokenize(df, metadata)) dsk = {} for i in range(df.npartitions): dsk[(name, i)] = (_rename, metadata, (df._name, i)) return new_dd_object(merge(dsk, df.dask), name, metadata, df.divisions)
[ "def", "_rename_dask", "(", "df", ",", "names", ")", ":", "assert", "isinstance", "(", "df", ",", "_Frame", ")", "metadata", "=", "_rename", "(", "names", ",", "df", ".", "_meta", ")", "name", "=", "'rename-{0}'", ".", "format", "(", "tokenize", "(", "df", ",", "metadata", ")", ")", "dsk", "=", "{", "}", "for", "i", "in", "range", "(", "df", ".", "npartitions", ")", ":", "dsk", "[", "(", "name", ",", "i", ")", "]", "=", "(", "_rename", ",", "metadata", ",", "(", "df", ".", "_name", ",", "i", ")", ")", "return", "new_dd_object", "(", "merge", "(", "dsk", ",", "df", ".", "dask", ")", ",", "name", ",", "metadata", ",", "df", ".", "divisions", ")" ]
destructively rename columns of dd .
train
false
24,117
def read_file(location, chomp=True): with open(location) as file_handle: contents = file_handle.read() if chomp: return contents.rstrip('\n') else: return contents
[ "def", "read_file", "(", "location", ",", "chomp", "=", "True", ")", ":", "with", "open", "(", "location", ")", "as", "file_handle", ":", "contents", "=", "file_handle", ".", "read", "(", ")", "if", "chomp", ":", "return", "contents", ".", "rstrip", "(", "'\\n'", ")", "else", ":", "return", "contents" ]
read file and decode in py2k .
train
false
24,118
def reorder_to(l, order): return [el[1] for el in sorted(zip(order, l), key=(lambda el: el[0]))]
[ "def", "reorder_to", "(", "l", ",", "order", ")", ":", "return", "[", "el", "[", "1", "]", "for", "el", "in", "sorted", "(", "zip", "(", "order", ",", "l", ")", ",", "key", "=", "(", "lambda", "el", ":", "el", "[", "0", "]", ")", ")", "]" ]
returns a list .
train
false
24,119
def test_completion_interference(): cache.parser_cache.pop(None, None) assert Script('open(').call_signatures() assert Script('from datetime import ').completions() assert Script('open(').call_signatures()
[ "def", "test_completion_interference", "(", ")", ":", "cache", ".", "parser_cache", ".", "pop", "(", "None", ",", "None", ")", "assert", "Script", "(", "'open('", ")", ".", "call_signatures", "(", ")", "assert", "Script", "(", "'from datetime import '", ")", ".", "completions", "(", ")", "assert", "Script", "(", "'open('", ")", ".", "call_signatures", "(", ")" ]
seems to cause problems .
train
false
24,120
def expand_makefile_vars(s, vars): while 1: m = (_findvar1_rx.search(s) or _findvar2_rx.search(s)) if m: (beg, end) = m.span() s = ((s[0:beg] + vars.get(m.group(1))) + s[end:]) else: break return s
[ "def", "expand_makefile_vars", "(", "s", ",", "vars", ")", ":", "while", "1", ":", "m", "=", "(", "_findvar1_rx", ".", "search", "(", "s", ")", "or", "_findvar2_rx", ".", "search", "(", "s", ")", ")", "if", "m", ":", "(", "beg", ",", "end", ")", "=", "m", ".", "span", "(", ")", "s", "=", "(", "(", "s", "[", "0", ":", "beg", "]", "+", "vars", ".", "get", "(", "m", ".", "group", "(", "1", ")", ")", ")", "+", "s", "[", "end", ":", "]", ")", "else", ":", "break", "return", "s" ]
expand makefile-style variables -- "${foo}" or "$" -- in string according to vars .
train
false
24,123
def _clear_special_values(d): l = [d] while l: i = l.pop() pops = [] for (k, v) in i.items(): if (v is REMOVE_THIS_KEY): pops.append(k) elif isinstance(v, dict): l.append(v) for k in pops: i.pop(k)
[ "def", "_clear_special_values", "(", "d", ")", ":", "l", "=", "[", "d", "]", "while", "l", ":", "i", "=", "l", ".", "pop", "(", ")", "pops", "=", "[", "]", "for", "(", "k", ",", "v", ")", "in", "i", ".", "items", "(", ")", ":", "if", "(", "v", "is", "REMOVE_THIS_KEY", ")", ":", "pops", ".", "append", "(", "k", ")", "elif", "isinstance", "(", "v", ",", "dict", ")", ":", "l", ".", "append", "(", "v", ")", "for", "k", "in", "pops", ":", "i", ".", "pop", "(", "k", ")" ]
remove remove_this_key values from dictionary .
train
false
24,124
def all_public(): for l in Layer.objects.all(): l.set_default_permissions() for m in Map.objects.all(): m.set_default_permissions() for d in Document.objects.all(): d.set_default_permissions()
[ "def", "all_public", "(", ")", ":", "for", "l", "in", "Layer", ".", "objects", ".", "all", "(", ")", ":", "l", ".", "set_default_permissions", "(", ")", "for", "m", "in", "Map", ".", "objects", ".", "all", "(", ")", ":", "m", ".", "set_default_permissions", "(", ")", "for", "d", "in", "Document", ".", "objects", ".", "all", "(", ")", ":", "d", ".", "set_default_permissions", "(", ")" ]
ensure all layers .
train
false
24,125
def sort_keys(key): is_special = (key in 'rtxyz') return ((not is_special), key)
[ "def", "sort_keys", "(", "key", ")", ":", "is_special", "=", "(", "key", "in", "'rtxyz'", ")", "return", "(", "(", "not", "is_special", ")", ",", "key", ")" ]
temporary function .
train
false
24,126
def extract_policy(obj_path): try: obj_portion = obj_path[obj_path.rindex(DATADIR_BASE):] obj_dirname = obj_portion[:obj_portion.index('/')] except Exception: return None try: (base, policy) = split_policy_string(obj_dirname) except PolicyError: return None return policy
[ "def", "extract_policy", "(", "obj_path", ")", ":", "try", ":", "obj_portion", "=", "obj_path", "[", "obj_path", ".", "rindex", "(", "DATADIR_BASE", ")", ":", "]", "obj_dirname", "=", "obj_portion", "[", ":", "obj_portion", ".", "index", "(", "'/'", ")", "]", "except", "Exception", ":", "return", "None", "try", ":", "(", "base", ",", "policy", ")", "=", "split_policy_string", "(", "obj_dirname", ")", "except", "PolicyError", ":", "return", "None", "return", "policy" ]
extracts the policy for an object given the device-relative path to the object .
train
false
24,127
def _get_datetime(instant): if (instant is None): return datetime_.utcnow() elif (isinstance(instant, integer_types) or isinstance(instant, float)): return datetime_.utcfromtimestamp(instant) elif isinstance(instant, time): return datetime_.combine(date.today(), instant) elif (isinstance(instant, date) and (not isinstance(instant, datetime))): return datetime_.combine(instant, time()) return instant
[ "def", "_get_datetime", "(", "instant", ")", ":", "if", "(", "instant", "is", "None", ")", ":", "return", "datetime_", ".", "utcnow", "(", ")", "elif", "(", "isinstance", "(", "instant", ",", "integer_types", ")", "or", "isinstance", "(", "instant", ",", "float", ")", ")", ":", "return", "datetime_", ".", "utcfromtimestamp", "(", "instant", ")", "elif", "isinstance", "(", "instant", ",", "time", ")", ":", "return", "datetime_", ".", "combine", "(", "date", ".", "today", "(", ")", ",", "instant", ")", "elif", "(", "isinstance", "(", "instant", ",", "date", ")", "and", "(", "not", "isinstance", "(", "instant", ",", "datetime", ")", ")", ")", ":", "return", "datetime_", ".", "combine", "(", "instant", ",", "time", "(", ")", ")", "return", "instant" ]
get a datetime out of an "instant" .
train
false
24,128
def get_total_run(thing): campaigns = [] if isinstance(thing, Link): campaigns = PromoCampaign._by_link(thing._id) elif isinstance(thing, PromoCampaign): campaigns = [thing] else: campaigns = [] earliest = None latest = None for campaign in campaigns: if (not charged_or_not_needed(campaign)): continue if ((not earliest) or (campaign.start_date < earliest)): earliest = campaign.start_date if ((not latest) or (campaign.end_date > latest)): latest = campaign.end_date if ((not earliest) or (not latest)): latest = datetime.datetime.utcnow() earliest = (latest - datetime.timedelta(days=30)) earliest = (earliest.replace(tzinfo=g.tz) - timezone_offset) latest = (latest.replace(tzinfo=g.tz) - timezone_offset) return (earliest, latest)
[ "def", "get_total_run", "(", "thing", ")", ":", "campaigns", "=", "[", "]", "if", "isinstance", "(", "thing", ",", "Link", ")", ":", "campaigns", "=", "PromoCampaign", ".", "_by_link", "(", "thing", ".", "_id", ")", "elif", "isinstance", "(", "thing", ",", "PromoCampaign", ")", ":", "campaigns", "=", "[", "thing", "]", "else", ":", "campaigns", "=", "[", "]", "earliest", "=", "None", "latest", "=", "None", "for", "campaign", "in", "campaigns", ":", "if", "(", "not", "charged_or_not_needed", "(", "campaign", ")", ")", ":", "continue", "if", "(", "(", "not", "earliest", ")", "or", "(", "campaign", ".", "start_date", "<", "earliest", ")", ")", ":", "earliest", "=", "campaign", ".", "start_date", "if", "(", "(", "not", "latest", ")", "or", "(", "campaign", ".", "end_date", ">", "latest", ")", ")", ":", "latest", "=", "campaign", ".", "end_date", "if", "(", "(", "not", "earliest", ")", "or", "(", "not", "latest", ")", ")", ":", "latest", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "earliest", "=", "(", "latest", "-", "datetime", ".", "timedelta", "(", "days", "=", "30", ")", ")", "earliest", "=", "(", "earliest", ".", "replace", "(", "tzinfo", "=", "g", ".", "tz", ")", "-", "timezone_offset", ")", "latest", "=", "(", "latest", ".", "replace", "(", "tzinfo", "=", "g", ".", "tz", ")", "-", "timezone_offset", ")", "return", "(", "earliest", ",", "latest", ")" ]
return the total time span this link or campaign will run .
train
false
24,130
def tmsiReallocationComplete(): a = TpPd(pd=5) b = MessageType(mesType=27) packet = (a / b) return packet
[ "def", "tmsiReallocationComplete", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "5", ")", "b", "=", "MessageType", "(", "mesType", "=", "27", ")", "packet", "=", "(", "a", "/", "b", ")", "return", "packet" ]
tmsi reallocation complete section 9 .
train
true
24,131
def UTF8ToUTF16BE(instr, setbom=True): outstr = ''.encode() if setbom: outstr += '\xfe\xff'.encode('latin1') if (not isinstance(instr, unicode)): instr = instr.decode('UTF-8') outstr += instr.encode('UTF-16BE') if PY3K: outstr = outstr.decode('latin1') return outstr
[ "def", "UTF8ToUTF16BE", "(", "instr", ",", "setbom", "=", "True", ")", ":", "outstr", "=", "''", ".", "encode", "(", ")", "if", "setbom", ":", "outstr", "+=", "'\\xfe\\xff'", ".", "encode", "(", "'latin1'", ")", "if", "(", "not", "isinstance", "(", "instr", ",", "unicode", ")", ")", ":", "instr", "=", "instr", ".", "decode", "(", "'UTF-8'", ")", "outstr", "+=", "instr", ".", "encode", "(", "'UTF-16BE'", ")", "if", "PY3K", ":", "outstr", "=", "outstr", ".", "decode", "(", "'latin1'", ")", "return", "outstr" ]
converts utf-8 strings to utf16-be .
train
true
24,133
def GetAPIScope(api_name): try: return SCOPES[api_name] except KeyError: raise googleads.errors.GoogleAdsValueError(('Invalid API name "%s" provided. Acceptable values are: %s' % (api_name, SCOPES.keys())))
[ "def", "GetAPIScope", "(", "api_name", ")", ":", "try", ":", "return", "SCOPES", "[", "api_name", "]", "except", "KeyError", ":", "raise", "googleads", ".", "errors", ".", "GoogleAdsValueError", "(", "(", "'Invalid API name \"%s\" provided. Acceptable values are: %s'", "%", "(", "api_name", ",", "SCOPES", ".", "keys", "(", ")", ")", ")", ")" ]
retrieves the scope for the given api name .
train
true
24,134
def list_queues_vhost(vhost, runas=None, *args): if ((runas is None) and (not salt.utils.is_windows())): runas = salt.utils.get_user() cmd = [__context__['rabbitmqctl'], 'list_queues', '-q', '-p', vhost] cmd.extend(args) res = __salt__['cmd.run_all'](cmd, runas=runas, python_shell=False) _check_response(res) return _output_to_dict(res['stdout'])
[ "def", "list_queues_vhost", "(", "vhost", ",", "runas", "=", "None", ",", "*", "args", ")", ":", "if", "(", "(", "runas", "is", "None", ")", "and", "(", "not", "salt", ".", "utils", ".", "is_windows", "(", ")", ")", ")", ":", "runas", "=", "salt", ".", "utils", ".", "get_user", "(", ")", "cmd", "=", "[", "__context__", "[", "'rabbitmqctl'", "]", ",", "'list_queues'", ",", "'-q'", ",", "'-p'", ",", "vhost", "]", "cmd", ".", "extend", "(", "args", ")", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ",", "runas", "=", "runas", ",", "python_shell", "=", "False", ")", "_check_response", "(", "res", ")", "return", "_output_to_dict", "(", "res", "[", "'stdout'", "]", ")" ]
returns queue details of specified virtual host .
train
false
24,135
def tryProxy(handler, URL=None): if (URL is None): URL = 'http://www.google.com' req = urllib.request.Request(URL) opener = urllib.request.build_opener(handler) try: opener.open(req, timeout=2).read(5) return True except urllib.error.URLError as err: return err except urllib.error.HTTPError as err: return err
[ "def", "tryProxy", "(", "handler", ",", "URL", "=", "None", ")", ":", "if", "(", "URL", "is", "None", ")", ":", "URL", "=", "'http://www.google.com'", "req", "=", "urllib", ".", "request", ".", "Request", "(", "URL", ")", "opener", "=", "urllib", ".", "request", ".", "build_opener", "(", "handler", ")", "try", ":", "opener", ".", "open", "(", "req", ",", "timeout", "=", "2", ")", ".", "read", "(", "5", ")", "return", "True", "except", "urllib", ".", "error", ".", "URLError", "as", "err", ":", "return", "err", "except", "urllib", ".", "error", ".", "HTTPError", "as", "err", ":", "return", "err" ]
test whether we can connect to a url with the current proxy settings .
train
false
24,139
def config_(dev=None, **kwargs): if (dev is None): spath = _fspath() else: spath = _bcpath(dev) updates = dict([(key, val) for (key, val) in kwargs.items() if (not key.startswith('__'))]) if updates: endres = 0 for (key, val) in updates.items(): endres += _sysfs_attr([spath, key], val, 'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val)) return (endres > 0) else: result = {} data = _sysfs_parse(spath, config=True, internals=True, options=True) for key in ('other_ro', 'inter_ro'): if (key in data): del data[key] for key in data.keys(): result.update(data[key]) return result
[ "def", "config_", "(", "dev", "=", "None", ",", "**", "kwargs", ")", ":", "if", "(", "dev", "is", "None", ")", ":", "spath", "=", "_fspath", "(", ")", "else", ":", "spath", "=", "_bcpath", "(", "dev", ")", "updates", "=", "dict", "(", "[", "(", "key", ",", "val", ")", "for", "(", "key", ",", "val", ")", "in", "kwargs", ".", "items", "(", ")", "if", "(", "not", "key", ".", "startswith", "(", "'__'", ")", ")", "]", ")", "if", "updates", ":", "endres", "=", "0", "for", "(", "key", ",", "val", ")", "in", "updates", ".", "items", "(", ")", ":", "endres", "+=", "_sysfs_attr", "(", "[", "spath", ",", "key", "]", ",", "val", ",", "'warn'", ",", "'Failed to update {0} with {1}'", ".", "format", "(", "os", ".", "path", ".", "join", "(", "spath", ",", "key", ")", ",", "val", ")", ")", "return", "(", "endres", ">", "0", ")", "else", ":", "result", "=", "{", "}", "data", "=", "_sysfs_parse", "(", "spath", ",", "config", "=", "True", ",", "internals", "=", "True", ",", "options", "=", "True", ")", "for", "key", "in", "(", "'other_ro'", ",", "'inter_ro'", ")", ":", "if", "(", "key", "in", "data", ")", ":", "del", "data", "[", "key", "]", "for", "key", "in", "data", ".", "keys", "(", ")", ":", "result", ".", "update", "(", "data", "[", "key", "]", ")", "return", "result" ]
show or update config of a bcache device .
train
true
24,140
def parse_template(filename, path='views/', context=dict(), lexers={}, delimiters=('{{', '}}')): if isinstance(filename, str): fname = os.path.join(path, filename) try: with open(fname, 'rb') as fp: text = fp.read() except IOError: raise RestrictedError(filename, '', 'Unable to find the file') else: text = filename.read() text = to_native(text) return str(TemplateParser(text, context=context, path=path, lexers=lexers, delimiters=delimiters))
[ "def", "parse_template", "(", "filename", ",", "path", "=", "'views/'", ",", "context", "=", "dict", "(", ")", ",", "lexers", "=", "{", "}", ",", "delimiters", "=", "(", "'{{'", ",", "'}}'", ")", ")", ":", "if", "isinstance", "(", "filename", ",", "str", ")", ":", "fname", "=", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", "try", ":", "with", "open", "(", "fname", ",", "'rb'", ")", "as", "fp", ":", "text", "=", "fp", ".", "read", "(", ")", "except", "IOError", ":", "raise", "RestrictedError", "(", "filename", ",", "''", ",", "'Unable to find the file'", ")", "else", ":", "text", "=", "filename", ".", "read", "(", ")", "text", "=", "to_native", "(", "text", ")", "return", "str", "(", "TemplateParser", "(", "text", ",", "context", "=", "context", ",", "path", "=", "path", ",", "lexers", "=", "lexers", ",", "delimiters", "=", "delimiters", ")", ")" ]
args: filename: can be a view filename in the views folder or an input stream path: is the path of a views folder context: is a dictionary of symbols used to render the template lexers: dict of custom lexers to use delimiters: opening and closing tags .
train
false
24,141
def check_pool(lb, name): if __opts__['load_balancers'].get(lb, None): (username, password) = list(__opts__['load_balancers'][lb].values()) else: raise Exception('Unable to find `{0}` load balancer'.format(lb)) F5 = F5Mgmt(lb, username, password) return F5.check_pool(name)
[ "def", "check_pool", "(", "lb", ",", "name", ")", ":", "if", "__opts__", "[", "'load_balancers'", "]", ".", "get", "(", "lb", ",", "None", ")", ":", "(", "username", ",", "password", ")", "=", "list", "(", "__opts__", "[", "'load_balancers'", "]", "[", "lb", "]", ".", "values", "(", ")", ")", "else", ":", "raise", "Exception", "(", "'Unable to find `{0}` load balancer'", ".", "format", "(", "lb", ")", ")", "F5", "=", "F5Mgmt", "(", "lb", ",", "username", ",", "password", ")", "return", "F5", ".", "check_pool", "(", "name", ")" ]
check to see if a pool exists cli examples: .
train
true
24,142
def get_permission_codename(action, opts): return ('%s_%s' % (action, opts.model_name))
[ "def", "get_permission_codename", "(", "action", ",", "opts", ")", ":", "return", "(", "'%s_%s'", "%", "(", "action", ",", "opts", ".", "model_name", ")", ")" ]
returns the codename of the permission for the specified action .
train
false
24,144
def resolve_references(config, definitions): for (key, value) in config.items(): if isinstance(value, dict): if ((len(value) == 1) and (list(value.keys())[0] == '$ref')): config[key] = definitions[list(value.values())[0]] else: resolve_references(value, definitions)
[ "def", "resolve_references", "(", "config", ",", "definitions", ")", ":", "for", "(", "key", ",", "value", ")", "in", "config", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "if", "(", "(", "len", "(", "value", ")", "==", "1", ")", "and", "(", "list", "(", "value", ".", "keys", "(", ")", ")", "[", "0", "]", "==", "'$ref'", ")", ")", ":", "config", "[", "key", "]", "=", "definitions", "[", "list", "(", "value", ".", "values", "(", ")", ")", "[", "0", "]", "]", "else", ":", "resolve_references", "(", "value", ",", "definitions", ")" ]
recursively replace $ref keys .
train
false
24,145
def travis_branch(): try: return os.environ[TRAVIS_BRANCH_ENV] except KeyError: msg = ('Pull request build does not have an associated branch set (via %s)' % (TRAVIS_BRANCH_ENV,)) raise OSError(msg)
[ "def", "travis_branch", "(", ")", ":", "try", ":", "return", "os", ".", "environ", "[", "TRAVIS_BRANCH_ENV", "]", "except", "KeyError", ":", "msg", "=", "(", "'Pull request build does not have an associated branch set (via %s)'", "%", "(", "TRAVIS_BRANCH_ENV", ",", ")", ")", "raise", "OSError", "(", "msg", ")" ]
get the current branch of the pr .
train
false
24,147
def escape_html_characters(content): return re.sub('<!--.*-->', '', re.sub('<!\\[CDATA\\[.*\\]\\]>', '', re.sub('(\\s|&nbsp;|//)+', ' ', html_to_text(content))))
[ "def", "escape_html_characters", "(", "content", ")", ":", "return", "re", ".", "sub", "(", "'<!--.*-->'", ",", "''", ",", "re", ".", "sub", "(", "'<!\\\\[CDATA\\\\[.*\\\\]\\\\]>'", ",", "''", ",", "re", ".", "sub", "(", "'(\\\\s|&nbsp;|//)+'", ",", "' '", ",", "html_to_text", "(", "content", ")", ")", ")", ")" ]
remove html characters that shouldnt be indexed using elasticsearch indexer this method is complementary to html_to_text method found in xmodule/annotator_mixin .
train
false
24,148
def _loadMacDylib(): try: l = ctypes.CDLL('liblabjackusb.dylib', use_errno=True) except TypeError: l = ctypes.CDLL('liblabjackusb.dylib') l.LJUSB_Stream.errcheck = errcheck l.LJUSB_Read.errcheck = errcheck return l
[ "def", "_loadMacDylib", "(", ")", ":", "try", ":", "l", "=", "ctypes", ".", "CDLL", "(", "'liblabjackusb.dylib'", ",", "use_errno", "=", "True", ")", "except", "TypeError", ":", "l", "=", "ctypes", ".", "CDLL", "(", "'liblabjackusb.dylib'", ")", "l", ".", "LJUSB_Stream", ".", "errcheck", "=", "errcheck", "l", ".", "LJUSB_Read", ".", "errcheck", "=", "errcheck", "return", "l" ]
attempts to load the liblabjackusb .
train
false
24,149
def is_dtype_equal(source, target): try: source = _get_dtype(source) target = _get_dtype(target) return (source == target) except (TypeError, AttributeError): return False
[ "def", "is_dtype_equal", "(", "source", ",", "target", ")", ":", "try", ":", "source", "=", "_get_dtype", "(", "source", ")", "target", "=", "_get_dtype", "(", "target", ")", "return", "(", "source", "==", "target", ")", "except", "(", "TypeError", ",", "AttributeError", ")", ":", "return", "False" ]
return a boolean if the dtypes are equal .
train
true
24,151
def p_expr_stmt(p): if (len(p) == 2): p[0] = ast.Discard(p[1]) else: p[0] = Assign(p[1], p[3])
[ "def", "p_expr_stmt", "(", "p", ")", ":", "if", "(", "len", "(", "p", ")", "==", "2", ")", ":", "p", "[", "0", "]", "=", "ast", ".", "Discard", "(", "p", "[", "1", "]", ")", "else", ":", "p", "[", "0", "]", "=", "Assign", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ")" ]
expr_stmt : testlist assign testlist | testlist .
train
false
24,152
def get_input_source(content): if (not isinstance(content, InputSource)): content = XmlInputSource(content) return content
[ "def", "get_input_source", "(", "content", ")", ":", "if", "(", "not", "isinstance", "(", "content", ",", "InputSource", ")", ")", ":", "content", "=", "XmlInputSource", "(", "content", ")", "return", "content" ]
wrap an xml element in a xmlinputsource if needed .
train
false
24,154
def dump_probes(probes, tofile): with open(tofile, 'w') as stream: stream.writelines(probes)
[ "def", "dump_probes", "(", "probes", ",", "tofile", ")", ":", "with", "open", "(", "tofile", ",", "'w'", ")", "as", "stream", ":", "stream", ".", "writelines", "(", "probes", ")" ]
writes the given list of dtrace probes to a file .
train
false
24,155
@env.catch_exceptions def show_doc(): with RopeContext() as ctx: (source, offset) = env.get_offset_params() try: doc = codeassist.get_doc(ctx.project, source, offset, ctx.resource, maxfixes=3) if (not doc): raise exceptions.BadIdentifierError env.let('l:output', doc.split('\n')) except exceptions.BadIdentifierError: env.error('No documentation found.')
[ "@", "env", ".", "catch_exceptions", "def", "show_doc", "(", ")", ":", "with", "RopeContext", "(", ")", "as", "ctx", ":", "(", "source", ",", "offset", ")", "=", "env", ".", "get_offset_params", "(", ")", "try", ":", "doc", "=", "codeassist", ".", "get_doc", "(", "ctx", ".", "project", ",", "source", ",", "offset", ",", "ctx", ".", "resource", ",", "maxfixes", "=", "3", ")", "if", "(", "not", "doc", ")", ":", "raise", "exceptions", ".", "BadIdentifierError", "env", ".", "let", "(", "'l:output'", ",", "doc", ".", "split", "(", "'\\n'", ")", ")", "except", "exceptions", ".", "BadIdentifierError", ":", "env", ".", "error", "(", "'No documentation found.'", ")" ]
show documentation .
train
false
24,156
def processElementNodeByDerivation(derivation, elementNode): if (derivation == None): derivation = SolidDerivation(elementNode) elementAttributesCopy = elementNode.attributes.copy() for target in derivation.targets: targetAttributesCopy = target.attributes.copy() target.attributes = elementAttributesCopy processTarget(target) target.attributes = targetAttributesCopy
[ "def", "processElementNodeByDerivation", "(", "derivation", ",", "elementNode", ")", ":", "if", "(", "derivation", "==", "None", ")", ":", "derivation", "=", "SolidDerivation", "(", "elementNode", ")", "elementAttributesCopy", "=", "elementNode", ".", "attributes", ".", "copy", "(", ")", "for", "target", "in", "derivation", ".", "targets", ":", "targetAttributesCopy", "=", "target", ".", "attributes", ".", "copy", "(", ")", "target", ".", "attributes", "=", "elementAttributesCopy", "processTarget", "(", "target", ")", "target", ".", "attributes", "=", "targetAttributesCopy" ]
process the xml element by derivation .
train
false
24,157
def memoizemethod(method): @wraps(method) def _wrapper(self, *args, **kwargs): if ('_memoized_results' not in self.__dict__): self._memoized_results = {} memoized_results = self._memoized_results key = (method.__name__, args, tuple(sorted(kwargs.items()))) if (key in memoized_results): return memoized_results[key] else: try: result = method(self, *args, **kwargs) except KeyError as e: if ('__wrapped__' in str(e)): result = None else: raise if (isinstance(result, GeneratorType) or (not isinstance(result, Hashable))): raise TypeError("Can't memoize a generator or non-hashable object!") return memoized_results.setdefault(key, result) return _wrapper
[ "def", "memoizemethod", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "_wrapper", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "(", "'_memoized_results'", "not", "in", "self", ".", "__dict__", ")", ":", "self", ".", "_memoized_results", "=", "{", "}", "memoized_results", "=", "self", ".", "_memoized_results", "key", "=", "(", "method", ".", "__name__", ",", "args", ",", "tuple", "(", "sorted", "(", "kwargs", ".", "items", "(", ")", ")", ")", ")", "if", "(", "key", "in", "memoized_results", ")", ":", "return", "memoized_results", "[", "key", "]", "else", ":", "try", ":", "result", "=", "method", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "except", "KeyError", "as", "e", ":", "if", "(", "'__wrapped__'", "in", "str", "(", "e", ")", ")", ":", "result", "=", "None", "else", ":", "raise", "if", "(", "isinstance", "(", "result", ",", "GeneratorType", ")", "or", "(", "not", "isinstance", "(", "result", ",", "Hashable", ")", ")", ")", ":", "raise", "TypeError", "(", "\"Can't memoize a generator or non-hashable object!\"", ")", "return", "memoized_results", ".", "setdefault", "(", "key", ",", "result", ")", "return", "_wrapper" ]
decorator to cause a method to cache its results in self for each combination of inputs and return the cached result on subsequent calls .
train
true
24,159
def mock_data(n_items=1000, dim=1000, prob_nnz=0.5, lam=1.0): data = [mock_data_row(dim=dim, prob_nnz=prob_nnz, lam=lam) for _ in xrange(n_items)] return data
[ "def", "mock_data", "(", "n_items", "=", "1000", ",", "dim", "=", "1000", ",", "prob_nnz", "=", "0.5", ",", "lam", "=", "1.0", ")", ":", "data", "=", "[", "mock_data_row", "(", "dim", "=", "dim", ",", "prob_nnz", "=", "prob_nnz", ",", "lam", "=", "lam", ")", "for", "_", "in", "xrange", "(", "n_items", ")", "]", "return", "data" ]
create a random gensim-style corpus .
train
false
24,160
@pytest.mark.django_db def test_scan_empty_project_obsolete_dirs(project0_nongnu, store0): tp = store0.translation_project tp.scan_files() for item in tp.directory.child_dirs.all(): assert item.obsolete assert tp.directory.obsolete
[ "@", "pytest", ".", "mark", ".", "django_db", "def", "test_scan_empty_project_obsolete_dirs", "(", "project0_nongnu", ",", "store0", ")", ":", "tp", "=", "store0", ".", "translation_project", "tp", ".", "scan_files", "(", ")", "for", "item", "in", "tp", ".", "directory", ".", "child_dirs", ".", "all", "(", ")", ":", "assert", "item", ".", "obsolete", "assert", "tp", ".", "directory", ".", "obsolete" ]
tests that the in-db directories are marked as obsolete if the on-disk directories are empty .
train
false
24,162
def split_by_type(activity_references): (exploration_ids, collection_ids) = ([], []) for activity_reference in activity_references: if (activity_reference.type == feconf.ACTIVITY_TYPE_EXPLORATION): exploration_ids.append(activity_reference.id) elif (activity_reference.type == feconf.ACTIVITY_TYPE_COLLECTION): collection_ids.append(activity_reference.id) else: raise Exception(('Invalid activity reference: (%s, %s)' % (activity_reference.type, activity_reference.id))) return (exploration_ids, collection_ids)
[ "def", "split_by_type", "(", "activity_references", ")", ":", "(", "exploration_ids", ",", "collection_ids", ")", "=", "(", "[", "]", ",", "[", "]", ")", "for", "activity_reference", "in", "activity_references", ":", "if", "(", "activity_reference", ".", "type", "==", "feconf", ".", "ACTIVITY_TYPE_EXPLORATION", ")", ":", "exploration_ids", ".", "append", "(", "activity_reference", ".", "id", ")", "elif", "(", "activity_reference", ".", "type", "==", "feconf", ".", "ACTIVITY_TYPE_COLLECTION", ")", ":", "collection_ids", ".", "append", "(", "activity_reference", ".", "id", ")", "else", ":", "raise", "Exception", "(", "(", "'Invalid activity reference: (%s, %s)'", "%", "(", "activity_reference", ".", "type", ",", "activity_reference", ".", "id", ")", ")", ")", "return", "(", "exploration_ids", ",", "collection_ids", ")" ]
given a list of activity references .
train
false
24,164
def pseudoinverse_softmax_numpy(x): rval = np.log(x) rval -= rval.mean() return rval
[ "def", "pseudoinverse_softmax_numpy", "(", "x", ")", ":", "rval", "=", "np", ".", "log", "(", "x", ")", "rval", "-=", "rval", ".", "mean", "(", ")", "return", "rval" ]
numpy implementation of a pseudo-inverse of the softmax function .
train
false
24,165
@login_required def component_handler(request, usage_key_string, handler, suffix=''): usage_key = UsageKey.from_string(usage_key_string) descriptor = modulestore().get_item(usage_key) descriptor.xmodule_runtime = StudioEditModuleRuntime(request.user) req = django_to_webob_request(request) try: resp = descriptor.handle(handler, req, suffix) except NoSuchHandlerError: log.info('XBlock %s attempted to access missing handler %r', descriptor, handler, exc_info=True) raise Http404 modulestore().update_item(descriptor, request.user.id) return webob_to_django_response(resp)
[ "@", "login_required", "def", "component_handler", "(", "request", ",", "usage_key_string", ",", "handler", ",", "suffix", "=", "''", ")", ":", "usage_key", "=", "UsageKey", ".", "from_string", "(", "usage_key_string", ")", "descriptor", "=", "modulestore", "(", ")", ".", "get_item", "(", "usage_key", ")", "descriptor", ".", "xmodule_runtime", "=", "StudioEditModuleRuntime", "(", "request", ".", "user", ")", "req", "=", "django_to_webob_request", "(", "request", ")", "try", ":", "resp", "=", "descriptor", ".", "handle", "(", "handler", ",", "req", ",", "suffix", ")", "except", "NoSuchHandlerError", ":", "log", ".", "info", "(", "'XBlock %s attempted to access missing handler %r'", ",", "descriptor", ",", "handler", ",", "exc_info", "=", "True", ")", "raise", "Http404", "modulestore", "(", ")", ".", "update_item", "(", "descriptor", ",", "request", ".", "user", ".", "id", ")", "return", "webob_to_django_response", "(", "resp", ")" ]
dispatch an ajax action to an xblock args: usage_id: the usage-id of the block to dispatch to handler : the handler to execute suffix : the remainder of the url to be passed to the handler returns: :class:django .
train
false
24,167
def fuzz_activity(count): decay = math.exp((float((- count)) / 60)) jitter = round((5 * decay)) return (count + random.randint(0, jitter))
[ "def", "fuzz_activity", "(", "count", ")", ":", "decay", "=", "math", ".", "exp", "(", "(", "float", "(", "(", "-", "count", ")", ")", "/", "60", ")", ")", "jitter", "=", "round", "(", "(", "5", "*", "decay", ")", ")", "return", "(", "count", "+", "random", ".", "randint", "(", "0", ",", "jitter", ")", ")" ]
add some jitter to an activity metric to maintain privacy .
train
false
24,168
def _post_order(node, stack=None): if (stack is None): stack = list() if (type(node) is list): if (len(node) > 3): _post_order(node[3], stack) if (len(node) > 4): _post_order(node[4], stack) stack.append(node[0]) else: stack.append(node) return stack
[ "def", "_post_order", "(", "node", ",", "stack", "=", "None", ")", ":", "if", "(", "stack", "is", "None", ")", ":", "stack", "=", "list", "(", ")", "if", "(", "type", "(", "node", ")", "is", "list", ")", ":", "if", "(", "len", "(", "node", ")", ">", "3", ")", ":", "_post_order", "(", "node", "[", "3", "]", ",", "stack", ")", "if", "(", "len", "(", "node", ")", ">", "4", ")", ":", "_post_order", "(", "node", "[", "4", "]", ",", "stack", ")", "stack", ".", "append", "(", "node", "[", "0", "]", ")", "else", ":", "stack", ".", "append", "(", "node", ")", "return", "stack" ]
generate a stack from a portion of the tree .
train
false
24,169
def length_or_percentage_or_unitless(argument, default=''): try: return get_measure(argument, (length_units + ['%'])) except ValueError: try: return (get_measure(argument, ['']) + default) except ValueError: return get_measure(argument, (length_units + ['%']))
[ "def", "length_or_percentage_or_unitless", "(", "argument", ",", "default", "=", "''", ")", ":", "try", ":", "return", "get_measure", "(", "argument", ",", "(", "length_units", "+", "[", "'%'", "]", ")", ")", "except", "ValueError", ":", "try", ":", "return", "(", "get_measure", "(", "argument", ",", "[", "''", "]", ")", "+", "default", ")", "except", "ValueError", ":", "return", "get_measure", "(", "argument", ",", "(", "length_units", "+", "[", "'%'", "]", ")", ")" ]
return normalized string of a length or percentage unit .
train
false
24,170
def _get_array_mmap(array): if isinstance(array, mmap.mmap): return array base = array while (hasattr(base, 'base') and (base.base is not None)): if isinstance(base.base, mmap.mmap): return base.base base = base.base
[ "def", "_get_array_mmap", "(", "array", ")", ":", "if", "isinstance", "(", "array", ",", "mmap", ".", "mmap", ")", ":", "return", "array", "base", "=", "array", "while", "(", "hasattr", "(", "base", ",", "'base'", ")", "and", "(", "base", ".", "base", "is", "not", "None", ")", ")", ":", "if", "isinstance", "(", "base", ".", "base", ",", "mmap", ".", "mmap", ")", ":", "return", "base", ".", "base", "base", "=", "base", ".", "base" ]
if the array has an mmap .
train
false
24,172
def pkcs_i2osp(x, xLen): fmt = ('%%0%dx' % (2 * xLen)) return (fmt % x).decode('hex')
[ "def", "pkcs_i2osp", "(", "x", ",", "xLen", ")", ":", "fmt", "=", "(", "'%%0%dx'", "%", "(", "2", "*", "xLen", ")", ")", "return", "(", "fmt", "%", "x", ")", ".", "decode", "(", "'hex'", ")" ]
converts a long to the associated byte string representation of length l .
train
false
24,173
def register_security_check(name, cls): _populate_security_checks() if (name in _security_checks): raise KeyError((u'"%s" is already a registered security check' % name)) _security_checks[name] = cls
[ "def", "register_security_check", "(", "name", ",", "cls", ")", ":", "_populate_security_checks", "(", ")", "if", "(", "name", "in", "_security_checks", ")", ":", "raise", "KeyError", "(", "(", "u'\"%s\" is already a registered security check'", "%", "name", ")", ")", "_security_checks", "[", "name", "]", "=", "cls" ]
register a custom security check .
train
false