id_within_dataset
int64
1
55.5k
snippet
stringlengths
19
14.2k
tokens
listlengths
6
1.63k
nl
stringlengths
6
352
split_within_dataset
stringclasses
1 value
is_duplicated
bool
2 classes
34,846
def make_search_form(*args, **kwargs): request = kwargs.pop('request', None) if (request is not None): sparams_cookie = request.COOKIES.get('pootle-search') if sparams_cookie: import json import urllib try: initial_sparams = json.loads(urllib.unquote(sparams_cookie)) except ValueError: pass else: if (isinstance(initial_sparams, dict) and ('sfields' in initial_sparams)): kwargs.update({'initial': initial_sparams}) return SearchForm(*args, **kwargs)
[ "def", "make_search_form", "(", "*", "args", ",", "**", "kwargs", ")", ":", "request", "=", "kwargs", ".", "pop", "(", "'request'", ",", "None", ")", "if", "(", "request", "is", "not", "None", ")", ":", "sparams_cookie", "=", "request", ".", "COOKIES",...
factory that instantiates one of the search forms below .
train
false
34,848
def deltaE_cie76(lab1, lab2): lab1 = np.asarray(lab1) lab2 = np.asarray(lab2) (L1, a1, b1) = np.rollaxis(lab1, (-1))[:3] (L2, a2, b2) = np.rollaxis(lab2, (-1))[:3] return np.sqrt(((((L2 - L1) ** 2) + ((a2 - a1) ** 2)) + ((b2 - b1) ** 2)))
[ "def", "deltaE_cie76", "(", "lab1", ",", "lab2", ")", ":", "lab1", "=", "np", ".", "asarray", "(", "lab1", ")", "lab2", "=", "np", ".", "asarray", "(", "lab2", ")", "(", "L1", ",", "a1", ",", "b1", ")", "=", "np", ".", "rollaxis", "(", "lab1", ...
euclidean distance between two points in lab color space parameters lab1 : array_like reference color lab2 : array_like comparison color returns de : array_like distance between colors lab1 and lab2 references .
train
false
34,849
def _get_unit_format(config): if (config.get(u'unit_format') is None): format = _get_default_unit_format(config) else: format = config[u'unit_format'] return format
[ "def", "_get_unit_format", "(", "config", ")", ":", "if", "(", "config", ".", "get", "(", "u'unit_format'", ")", "is", "None", ")", ":", "format", "=", "_get_default_unit_format", "(", "config", ")", "else", ":", "format", "=", "config", "[", "u'unit_forma...
get the unit format based on the configuration .
train
false
34,853
def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item, raw_lines_no_comments, linenum): is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments, linenum) if (not (is_namespace_indent_item or is_forward_declaration)): return False if IsMacroDefinition(raw_lines_no_comments, linenum): return False return IsBlockInNameSpace(nesting_state, is_forward_declaration)
[ "def", "ShouldCheckNamespaceIndentation", "(", "nesting_state", ",", "is_namespace_indent_item", ",", "raw_lines_no_comments", ",", "linenum", ")", ":", "is_forward_declaration", "=", "IsForwardClassDeclaration", "(", "raw_lines_no_comments", ",", "linenum", ")", "if", "(",...
this method determines if we should apply our namespace indentation check .
train
true
34,855
@utils.arg('id', metavar='<id>', nargs='+', help=_('Unique ID(s) of the server group to delete.')) def do_server_group_delete(cs, args): failure_count = 0 for sg in args.id: try: cs.server_groups.delete(sg) print((_('Server group %s has been successfully deleted.') % sg)) except Exception as e: failure_count += 1 print((_('Delete for server group %(sg)s failed: %(e)s') % {'sg': sg, 'e': e})) if (failure_count == len(args.id)): raise exceptions.CommandError(_('Unable to delete any of the specified server groups.'))
[ "@", "utils", ".", "arg", "(", "'id'", ",", "metavar", "=", "'<id>'", ",", "nargs", "=", "'+'", ",", "help", "=", "_", "(", "'Unique ID(s) of the server group to delete.'", ")", ")", "def", "do_server_group_delete", "(", "cs", ",", "args", ")", ":", "failu...
delete specific server group(s) .
train
false
34,858
def ilcm(*args): if (len(args) < 2): raise TypeError(('ilcm() takes at least 2 arguments (%s given)' % len(args))) if (0 in args): return 0 a = args[0] for b in args[1:]: a = ((a * b) // igcd(a, b)) return a
[ "def", "ilcm", "(", "*", "args", ")", ":", "if", "(", "len", "(", "args", ")", "<", "2", ")", ":", "raise", "TypeError", "(", "(", "'ilcm() takes at least 2 arguments (%s given)'", "%", "len", "(", "args", ")", ")", ")", "if", "(", "0", "in", "args",...
computes integer least common multiple .
train
false
34,861
def get_metadata_changeset_revisions(repository, repo): changeset_tups = [] for repository_metadata in repository.downloadable_revisions: ctx = hg_util.get_changectx_for_changeset(repo, repository_metadata.changeset_revision) if ctx: rev = ctx.rev() else: rev = (-1) changeset_tups.append((rev, repository_metadata.changeset_revision)) return sorted(changeset_tups)
[ "def", "get_metadata_changeset_revisions", "(", "repository", ",", "repo", ")", ":", "changeset_tups", "=", "[", "]", "for", "repository_metadata", "in", "repository", ".", "downloadable_revisions", ":", "ctx", "=", "hg_util", ".", "get_changectx_for_changeset", "(", ...
return an unordered list of changeset_revisions and changeset numbers that are defined as installable .
train
false
34,862
@mock_s3 def test_create_existing_bucket_in_us_east_1(): u'"\n http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html\n Your previous request to create the named bucket succeeded and you already\n own it. You get this error in all AWS regions except US Standard,\n us-east-1. In us-east-1 region, you will get 200 OK, but it is no-op (if\n bucket exists it Amazon S3 will not do anything).\n ' conn = boto.s3.connect_to_region(u'us-east-1') conn.create_bucket(u'foobar') bucket = conn.create_bucket(u'foobar') bucket.name.should.equal(u'foobar')
[ "@", "mock_s3", "def", "test_create_existing_bucket_in_us_east_1", "(", ")", ":", "conn", "=", "boto", ".", "s3", ".", "connect_to_region", "(", "u'us-east-1'", ")", "conn", ".", "create_bucket", "(", "u'foobar'", ")", "bucket", "=", "conn", ".", "create_bucket"...
trying to create a bucket that already exists in us-east-1 returns the bucket .
train
false
34,863
@with_setup(step_runner_environ) def test_can_count_steps_and_its_states(): f = Feature.from_string(FEATURE1) feature_result = f.run() scenario_result = feature_result.scenario_results[0] assert_equals(len(scenario_result.steps_passed), 1) assert_equals(len(scenario_result.steps_failed), 1) assert_equals(len(scenario_result.steps_undefined), 1) assert_equals(len(scenario_result.steps_skipped), 1) assert_equals(scenario_result.total_steps, 4)
[ "@", "with_setup", "(", "step_runner_environ", ")", "def", "test_can_count_steps_and_its_states", "(", ")", ":", "f", "=", "Feature", ".", "from_string", "(", "FEATURE1", ")", "feature_result", "=", "f", ".", "run", "(", ")", "scenario_result", "=", "feature_res...
the scenario result has the steps passed .
train
false
34,866
def _find_lineage_for_domains_and_certname(config, domains, certname): if (not certname): return _find_lineage_for_domains(config, domains) else: lineage = cert_manager.lineage_for_certname(config, certname) if lineage: if domains: if (set(cert_manager.domains_for_certname(config, certname)) != set(domains)): _ask_user_to_confirm_new_names(config, domains, certname, lineage.names()) return ('renew', lineage) return _handle_identical_cert_request(config, lineage) elif domains: return ('newcert', None) else: raise errors.ConfigurationError('No certificate with name {0} found. Use -d to specify domains, or run certbot --certificates to see possible certificate names.'.format(certname))
[ "def", "_find_lineage_for_domains_and_certname", "(", "config", ",", "domains", ",", "certname", ")", ":", "if", "(", "not", "certname", ")", ":", "return", "_find_lineage_for_domains", "(", "config", ",", "domains", ")", "else", ":", "lineage", "=", "cert_manag...
find appropriate lineage based on given domains and/or certname .
train
false
34,868
def getConsumer(request): return consumer.Consumer(request.session, getOpenIDStore())
[ "def", "getConsumer", "(", "request", ")", ":", "return", "consumer", ".", "Consumer", "(", "request", ".", "session", ",", "getOpenIDStore", "(", ")", ")" ]
get a consumer object to perform openid authentication .
train
false
34,869
def _process_entries(l, entries): old = OrderedDict() new = OrderedDict() for entries_dict in entries: for (dn, directives_seq) in six.iteritems(entries_dict): olde = new.get(dn, None) if (olde is None): results = __salt__['ldap3.search'](l, dn, 'base') if (len(results) == 1): attrs = results[dn] olde = dict(((attr, set(attrs[attr])) for attr in attrs if len(attrs[attr]))) else: assert (len(results) == 0) olde = {} old[dn] = olde newe = copy.deepcopy(olde) new[dn] = newe entry_status = {'delete_others': False, 'mentioned_attributes': set()} for directives in directives_seq: _update_entry(newe, entry_status, directives) if entry_status['delete_others']: to_delete = set() for attr in newe: if (attr not in entry_status['mentioned_attributes']): to_delete.add(attr) for attr in to_delete: del newe[attr] return (old, new)
[ "def", "_process_entries", "(", "l", ",", "entries", ")", ":", "old", "=", "OrderedDict", "(", ")", "new", "=", "OrderedDict", "(", ")", "for", "entries_dict", "in", "entries", ":", "for", "(", "dn", ",", "directives_seq", ")", "in", "six", ".", "iteri...
helper for managed() to process entries and return before/after views collect the current database state and update it according to the data in :py:func:manageds entries parameter .
train
true
34,870
def test_threshold_without_refitting(): clf = SGDClassifier(alpha=0.1, n_iter=10, shuffle=True, random_state=0) model = SelectFromModel(clf, threshold=0.1) model.fit(data, y) X_transform = model.transform(data) model.threshold = 1.0 assert_greater(X_transform.shape[1], model.transform(data).shape[1])
[ "def", "test_threshold_without_refitting", "(", ")", ":", "clf", "=", "SGDClassifier", "(", "alpha", "=", "0.1", ",", "n_iter", "=", "10", ",", "shuffle", "=", "True", ",", "random_state", "=", "0", ")", "model", "=", "SelectFromModel", "(", "clf", ",", ...
test that the threshold can be set without refitting the model .
train
false
34,871
def copyartifact(registry, xml_parent, data): copyartifact = XML.SubElement(xml_parent, 'hudson.plugins.copyartifact.CopyArtifactPermissionProperty', plugin='copyartifact') if ((not data) or (not data.get('projects', None))): raise JenkinsJobsException('projects string must exist and not be empty') projectlist = XML.SubElement(copyartifact, 'projectNameList') for project in str(data.get('projects')).split(','): XML.SubElement(projectlist, 'string').text = project
[ "def", "copyartifact", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "copyartifact", "=", "XML", ".", "SubElement", "(", "xml_parent", ",", "'hudson.plugins.copyartifact.CopyArtifactPermissionProperty'", ",", "plugin", "=", "'copyartifact'", ")", "if", ...
yaml: copyartifact specify a list of projects that have access to copy the artifacts of this project .
train
false
34,872
def _get_staff_lock_from(xblock): source = find_staff_lock_source(xblock) return (_xblock_type_and_display_name(source) if source else None)
[ "def", "_get_staff_lock_from", "(", "xblock", ")", ":", "source", "=", "find_staff_lock_source", "(", "xblock", ")", "return", "(", "_xblock_type_and_display_name", "(", "source", ")", "if", "source", "else", "None", ")" ]
returns a string representation of the section or subsection that sets the xblocks release date .
train
false
34,875
def read_dtype(mat_stream, a_dtype): num_bytes = a_dtype.itemsize arr = np.ndarray(shape=(), dtype=a_dtype, buffer=mat_stream.read(num_bytes), order='F') return arr
[ "def", "read_dtype", "(", "mat_stream", ",", "a_dtype", ")", ":", "num_bytes", "=", "a_dtype", ".", "itemsize", "arr", "=", "np", ".", "ndarray", "(", "shape", "=", "(", ")", ",", "dtype", "=", "a_dtype", ",", "buffer", "=", "mat_stream", ".", "read", ...
generic get of byte stream data of known type parameters mat_stream : file_like object matlab mat file stream a_dtype : dtype dtype of array to read .
train
false
34,876
def mcnemar(x, y=None, exact=True, correction=True): warnings.warn('Deprecated, use stats.TableSymmetry instead', DeprecationWarning) x = np.asarray(x) if ((y is None) and (x.shape[0] == x.shape[1])): if (x.shape[0] != 2): raise ValueError('table needs to be 2 by 2') (n1, n2) = (x[(1, 0)], x[(0, 1)]) else: n1 = np.sum((x < y), 0) n2 = np.sum((x > y), 0) if exact: stat = np.minimum(n1, n2) pval = (stats.binom.cdf(stat, (n1 + n2), 0.5) * 2) pval = np.minimum(pval, 1) else: corr = int(correction) stat = (((np.abs((n1 - n2)) - corr) ** 2) / (1.0 * (n1 + n2))) df = 1 pval = stats.chi2.sf(stat, df) return (stat, pval)
[ "def", "mcnemar", "(", "x", ",", "y", "=", "None", ",", "exact", "=", "True", ",", "correction", "=", "True", ")", ":", "warnings", ".", "warn", "(", "'Deprecated, use stats.TableSymmetry instead'", ",", "DeprecationWarning", ")", "x", "=", "np", ".", "asa...
mcnemar test of homogeneity .
train
false
34,877
@needs('pavelib.prereqs.install_prereqs') @cmdopts(BOKCHOY_OPTS) @PassthroughTask @timed def test_a11y(options, passthrough_options): options.test_a11y.report_dir = Env.BOK_CHOY_A11Y_REPORT_DIR options.test_a11y.coveragerc = Env.BOK_CHOY_A11Y_COVERAGERC options.test_a11y.extra_args = (options.get('extra_args', '') + ' -a "a11y" ') run_bokchoy(options.test_a11y, passthrough_options)
[ "@", "needs", "(", "'pavelib.prereqs.install_prereqs'", ")", "@", "cmdopts", "(", "BOKCHOY_OPTS", ")", "@", "PassthroughTask", "@", "timed", "def", "test_a11y", "(", "options", ",", "passthrough_options", ")", ":", "options", ".", "test_a11y", ".", "report_dir", ...
run accessibility tests that use the bok-choy framework .
train
false
34,880
def record_exchange_result(db, exchange_id, status, error, participant): with db.get_cursor() as cursor: (amount, fee, username, route) = cursor.one(u'\n UPDATE exchanges e\n SET status=%(status)s\n , note=%(error)s\n WHERE id=%(exchange_id)s\n AND status <> %(status)s\n RETURNING amount, fee, participant\n , ( SELECT r.*::exchange_routes\n FROM exchange_routes r\n WHERE r.id = e.route\n ) AS route\n ', locals()) assert (participant.username == username) assert isinstance(route, ExchangeRoute) route.set_attributes(participant=participant) if (amount < 0): amount -= fee amount = (amount if (status == u'failed') else 0) propagate_exchange(cursor, participant, route, error, (- amount)) else: amount = (amount if (status == u'succeeded') else 0) propagate_exchange(cursor, participant, route, error, amount)
[ "def", "record_exchange_result", "(", "db", ",", "exchange_id", ",", "status", ",", "error", ",", "participant", ")", ":", "with", "db", ".", "get_cursor", "(", ")", "as", "cursor", ":", "(", "amount", ",", "fee", ",", "username", ",", "route", ")", "=...
updates the status of an exchange .
train
false
34,883
def test_cmd_args(fake_proc): cmd = 'does_not_exist' args = ['arg1', 'arg2'] fake_proc.start(cmd, args) assert ((fake_proc.cmd, fake_proc.args) == (cmd, args))
[ "def", "test_cmd_args", "(", "fake_proc", ")", ":", "cmd", "=", "'does_not_exist'", "args", "=", "[", "'arg1'", ",", "'arg2'", "]", "fake_proc", ".", "start", "(", "cmd", ",", "args", ")", "assert", "(", "(", "fake_proc", ".", "cmd", ",", "fake_proc", ...
test the cmd and args attributes .
train
false
34,884
def touch_journal(filename): if (not os.path.exists(filename)): log.debug(u'Creating journal file %s', filename) util.prompt(u'[Journal created at {0}]'.format(filename)) open(filename, u'a').close()
[ "def", "touch_journal", "(", "filename", ")", ":", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ")", ":", "log", ".", "debug", "(", "u'Creating journal file %s'", ",", "filename", ")", "util", ".", "prompt", "(", "u'[Journal ...
if filename does not exist .
train
false
34,885
def yule_walker_acov(acov, order=1, method='unbiased', df=None, inv=False): R = toeplitz(r[:(-1)]) rho = np.linalg.solve(R, r[1:]) sigmasq = (r[0] - (r[1:] * rho).sum()) if (inv == True): return (rho, np.sqrt(sigmasq), np.linalg.inv(R)) else: return (rho, np.sqrt(sigmasq))
[ "def", "yule_walker_acov", "(", "acov", ",", "order", "=", "1", ",", "method", "=", "'unbiased'", ",", "df", "=", "None", ",", "inv", "=", "False", ")", ":", "R", "=", "toeplitz", "(", "r", "[", ":", "(", "-", "1", ")", "]", ")", "rho", "=", ...
estimate ar(p) parameters from acovf using yule-walker equation .
train
false
34,886
def get_local_ip_for(target): try: target_ipaddr = socket.gethostbyname(target) except socket.gaierror: return None udpprot = DatagramProtocol() port = reactor.listenUDP(0, udpprot) try: udpprot.transport.connect(target_ipaddr, 7) localip = udpprot.transport.getHost().host except socket.error: localip = None port.stopListening() return localip
[ "def", "get_local_ip_for", "(", "target", ")", ":", "try", ":", "target_ipaddr", "=", "socket", ".", "gethostbyname", "(", "target", ")", "except", "socket", ".", "gaierror", ":", "return", "None", "udpprot", "=", "DatagramProtocol", "(", ")", "port", "=", ...
find out what our ip address is for use by a given target .
train
false
34,887
def write_complex64(fid, kind, data): data_size = 8 data = np.array(data, dtype='>c8').T _write(fid, data, kind, data_size, FIFF.FIFFT_COMPLEX_FLOAT, '>c8')
[ "def", "write_complex64", "(", "fid", ",", "kind", ",", "data", ")", ":", "data_size", "=", "8", "data", "=", "np", ".", "array", "(", "data", ",", "dtype", "=", "'>c8'", ")", ".", "T", "_write", "(", "fid", ",", "data", ",", "kind", ",", "data_s...
write a 64 bit complex floating point tag to a fif file .
train
false
34,888
def CDLIDENTICAL3CROWS(barDs, count): return call_talib_with_ohlc(barDs, count, talib.CDLIDENTICAL3CROWS)
[ "def", "CDLIDENTICAL3CROWS", "(", "barDs", ",", "count", ")", ":", "return", "call_talib_with_ohlc", "(", "barDs", ",", "count", ",", "talib", ".", "CDLIDENTICAL3CROWS", ")" ]
identical three crows .
train
false
34,890
def format_user(user, show_url=True): out = '\x02{}\x02'.format(user['username']) if user['description']: out += ': "{}"'.format(formatting.truncate(user['description'])) if user['city']: out += ': {}'.format(user['city']) if user['country']: out += ', {}'.format(formatting.truncate(user['country'])) out += ' - \x02{track_count:,}\x02 tracks, \x02{playlist_count:,}\x02 playlists, \x02{followers_count:,}\x02 followers, \x02{followings_count:,}\x02 followed'.format(**user) if show_url: out += ' - {}'.format(web.try_shorten(user['permalink_url'])) return out
[ "def", "format_user", "(", "user", ",", "show_url", "=", "True", ")", ":", "out", "=", "'\\x02{}\\x02'", ".", "format", "(", "user", "[", "'username'", "]", ")", "if", "user", "[", "'description'", "]", ":", "out", "+=", "': \"{}\"'", ".", "format", "(...
takes a soundcloud user item and returns a formatted string .
train
false
34,891
def _gluster_ok(xml_data): return (int(xml_data.find('opRet').text) == 0)
[ "def", "_gluster_ok", "(", "xml_data", ")", ":", "return", "(", "int", "(", "xml_data", ".", "find", "(", "'opRet'", ")", ".", "text", ")", "==", "0", ")" ]
extract boolean return value from glusters xml output .
train
false
34,892
def update_subject_interests(user_id, subject_interests): if (not isinstance(subject_interests, list)): raise utils.ValidationError('Expected subject_interests to be a list.') else: for interest in subject_interests: if (not isinstance(interest, basestring)): raise utils.ValidationError('Expected each subject interest to be a string.') elif (not interest): raise utils.ValidationError('Expected each subject interest to be non-empty.') elif (not re.match(feconf.TAG_REGEX, interest)): raise utils.ValidationError('Expected each subject interest to consist only of lowercase alphabetic characters and spaces.') if (len(set(subject_interests)) != len(subject_interests)): raise utils.ValidationError('Expected each subject interest to be distinct.') user_settings = get_user_settings(user_id, strict=True) user_settings.subject_interests = subject_interests _save_user_settings(user_settings)
[ "def", "update_subject_interests", "(", "user_id", ",", "subject_interests", ")", ":", "if", "(", "not", "isinstance", "(", "subject_interests", ",", "list", ")", ")", ":", "raise", "utils", ".", "ValidationError", "(", "'Expected subject_interests to be a list.'", ...
updates subject_interests of user with given user_id .
train
false
34,893
@mobile_template('users/{mobile/}pw_reset_complete.html') def password_reset_complete(request, template): form = AuthenticationForm() return render(request, template, {'form': form})
[ "@", "mobile_template", "(", "'users/{mobile/}pw_reset_complete.html'", ")", "def", "password_reset_complete", "(", "request", ",", "template", ")", ":", "form", "=", "AuthenticationForm", "(", ")", "return", "render", "(", "request", ",", "template", ",", "{", "'...
password reset complete .
train
false
34,894
def pull_session(session_id=None, url='default', app_path='/', io_loop=None): coords = _SessionCoordinates(dict(session_id=session_id, url=url, app_path=app_path)) session = ClientSession(session_id=session_id, websocket_url=coords.websocket_url, io_loop=io_loop) session.pull() return session
[ "def", "pull_session", "(", "session_id", "=", "None", ",", "url", "=", "'default'", ",", "app_path", "=", "'/'", ",", "io_loop", "=", "None", ")", ":", "coords", "=", "_SessionCoordinates", "(", "dict", "(", "session_id", "=", "session_id", ",", "url", ...
create a session by loading the current server-side document .
train
false
34,895
def addons_reviewer_required(f): @login_required @functools.wraps(f) def wrapper(request, *args, **kw): if (_view_on_get(request) or acl.check_addons_reviewer(request)): return f(request, *args, **kw) raise PermissionDenied return wrapper
[ "def", "addons_reviewer_required", "(", "f", ")", ":", "@", "login_required", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "request", ",", "*", "args", ",", "**", "kw", ")", ":", "if", "(", "_view_on_get", "(", "request", ")", ...
require an addons reviewer user .
train
false
34,896
def choose_int(g1, g2): (v1, c1) = g1 (v2, c2) = g2 if (v1 == v2): return (v1, (1 - ((1 - c1) * (1 - c2)))) elif (c1 > c2): return (v1, (c1 - c2)) else: return (v2, (c2 - c1))
[ "def", "choose_int", "(", "g1", ",", "g2", ")", ":", "(", "v1", ",", "c1", ")", "=", "g1", "(", "v2", ",", "c2", ")", "=", "g2", "if", "(", "v1", "==", "v2", ")", ":", "return", "(", "v1", ",", "(", "1", "-", "(", "(", "1", "-", "c1", ...
function used by merge_similar_guesses to choose between 2 possible properties when they are integers .
train
false
34,897
def should_compress(filename): for extension in EXCLUDE_TYPES: if filename.endswith(extension): return False return True
[ "def", "should_compress", "(", "filename", ")", ":", "for", "extension", "in", "EXCLUDE_TYPES", ":", "if", "filename", ".", "endswith", "(", "extension", ")", ":", "return", "False", "return", "True" ]
check if the filename is a type of file that should be compressed .
train
false
34,898
def test_preprocess(): try: keys = [('PYLEARN2_' + str(uuid.uuid1())[:8]) for _ in xrange(3)] strs = [('${%s}' % k) for k in keys] os.environ[keys[0]] = keys[1] assert (preprocess(strs[0]) == keys[1]) assert (preprocess(strs[1], environ={keys[1]: keys[2]}) == keys[2]) assert (preprocess(strs[0], environ={keys[0]: keys[2]}) == keys[2]) raised = False try: preprocess(strs[2], environ={keys[1]: keys[0]}) except ValueError: raised = True assert raised finally: for key in keys: if (key in os.environ): del os.environ[key]
[ "def", "test_preprocess", "(", ")", ":", "try", ":", "keys", "=", "[", "(", "'PYLEARN2_'", "+", "str", "(", "uuid", ".", "uuid1", "(", ")", ")", "[", ":", "8", "]", ")", "for", "_", "in", "xrange", "(", "3", ")", "]", "strs", "=", "[", "(", ...
tests that preprocess fills in environment variables using various interfaces and raises a valueerror if a needed environment variable definition is missing .
train
false
34,899
def delete_all(context, stack_id, traversal_id): return sync_point_object.SyncPoint.delete_all_by_stack_and_traversal(context, stack_id, traversal_id)
[ "def", "delete_all", "(", "context", ",", "stack_id", ",", "traversal_id", ")", ":", "return", "sync_point_object", ".", "SyncPoint", ".", "delete_all_by_stack_and_traversal", "(", "context", ",", "stack_id", ",", "traversal_id", ")" ]
deletes all sync points of a stack associated with a traversal_id .
train
false
34,901
@Node.subscribe('before_save') def validate_visible_contributors(schema, instance): node = instance for user_id in node.visible_contributor_ids: if (user_id not in node.contributors): raise ValidationValueError('User {0} is in `visible_contributor_ids` but not in `contributors` on node {1}'.format(user_id, node._id))
[ "@", "Node", ".", "subscribe", "(", "'before_save'", ")", "def", "validate_visible_contributors", "(", "schema", ",", "instance", ")", ":", "node", "=", "instance", "for", "user_id", "in", "node", ".", "visible_contributor_ids", ":", "if", "(", "user_id", "not...
ensure that user ids in contributors and visible_contributor_ids match .
train
false
34,902
def dmp_degree_list(f, u): degs = ([(- oo)] * (u + 1)) _rec_degree_list(f, u, 0, degs) return tuple(degs)
[ "def", "dmp_degree_list", "(", "f", ",", "u", ")", ":", "degs", "=", "(", "[", "(", "-", "oo", ")", "]", "*", "(", "u", "+", "1", ")", ")", "_rec_degree_list", "(", "f", ",", "u", ",", "0", ",", "degs", ")", "return", "tuple", "(", "degs", ...
return a list of degrees of f in k[x] .
train
false
34,905
@json_view @non_atomic_requests def site_events(request, start, end): (start, end) = get_daterange_or_404(start, end) qs = SiteEvent.objects.filter((Q(start__gte=start, start__lte=end) | Q(end__gte=start, end__lte=end))) events = list(site_event_format(request, qs)) type_pretty = unicode(amo.SITE_EVENT_CHOICES[amo.SITE_EVENT_RELEASE]) releases = product_details.firefox_history_major_releases for (version, date_) in releases.items(): events.append({'start': date_, 'type_pretty': type_pretty, 'type': amo.SITE_EVENT_RELEASE, 'description': ('Firefox %s released' % version)}) return events
[ "@", "json_view", "@", "non_atomic_requests", "def", "site_events", "(", "request", ",", "start", ",", "end", ")", ":", "(", "start", ",", "end", ")", "=", "get_daterange_or_404", "(", "start", ",", "end", ")", "qs", "=", "SiteEvent", ".", "objects", "."...
return site events in the given timeframe .
train
false
34,907
def copy_remote(data, dest, use_put=None): ret = None req = urllib2.Request(dest, data=data) if use_put: req.add_header('Content-Type', 'application/octet-stream') end = ((use_put['start'] + use_put['size']) - 1) req.add_header('Content-Range', ('bytes %s-%s/%s' % (use_put['start'], end, use_put['total']))) req.add_header('Content-Length', ('%s' % use_put['size'])) req.get_method = (lambda : 'PUT') try: res = utils.urlopen(req) ret = res.info() res.close() except urllib2.HTTPError as e: if (e.code == 500): raise BkrProxyException('We have been aborted!!!') elif ((e.code == 400) and use_put): log.error(('Error(%s) failed to upload file %s' % (e.code, dest))) return ret
[ "def", "copy_remote", "(", "data", ",", "dest", ",", "use_put", "=", "None", ")", ":", "ret", "=", "None", "req", "=", "urllib2", ".", "Request", "(", "dest", ",", "data", "=", "data", ")", "if", "use_put", ":", "req", ".", "add_header", "(", "'Con...
copy data to a remote server using http calls post or put using http post and put methods .
train
false
34,908
def create_login_url(dest_url=None, _auth_domain=None, federated_identity=None): req = user_service_pb.CreateLoginURLRequest() resp = user_service_pb.CreateLoginURLResponse() req.set_destination_url(dest_url) if _auth_domain: req.set_auth_domain(_auth_domain) if federated_identity: req.set_federated_identity(federated_identity) try: apiproxy_stub_map.MakeSyncCall('user', 'CreateLoginURL', req, resp) except apiproxy_errors.ApplicationError as e: if (e.application_error == user_service_pb.UserServiceError.REDIRECT_URL_TOO_LONG): raise RedirectTooLongError elif (e.application_error == user_service_pb.UserServiceError.NOT_ALLOWED): raise NotAllowedError else: raise e return resp.login_url()
[ "def", "create_login_url", "(", "dest_url", "=", "None", ",", "_auth_domain", "=", "None", ",", "federated_identity", "=", "None", ")", ":", "req", "=", "user_service_pb", ".", "CreateLoginURLRequest", "(", ")", "resp", "=", "user_service_pb", ".", "CreateLoginU...
computes the login url for redirection .
train
false
34,909
def working_copy(remote_url, path=None, branch='master', update=True, use_sudo=False, user=None): command() if (path is None): path = remote_url.split('/')[(-1)] if path.endswith('.git'): path = path[:(-4)] if is_dir(path, use_sudo=use_sudo): git.fetch(path=path, use_sudo=use_sudo, user=user) git.checkout(path=path, branch=branch, use_sudo=use_sudo, user=user) if update: git.pull(path=path, use_sudo=use_sudo, user=user) elif (not is_dir(path, use_sudo=use_sudo)): git.clone(remote_url, path=path, use_sudo=use_sudo, user=user) git.checkout(path=path, branch=branch, use_sudo=use_sudo, user=user) else: raise ValueError('Invalid combination of parameters.')
[ "def", "working_copy", "(", "remote_url", ",", "path", "=", "None", ",", "branch", "=", "'master'", ",", "update", "=", "True", ",", "use_sudo", "=", "False", ",", "user", "=", "None", ")", ":", "command", "(", ")", "if", "(", "path", "is", "None", ...
require a working copy of the repository from the remote_url .
train
false
34,910
def compareEvents(test, actualEvents, expectedEvents): if (len(actualEvents) != len(expectedEvents)): test.assertEqual(actualEvents, expectedEvents) allMergedKeys = set() for event in expectedEvents: allMergedKeys |= set(event.keys()) def simplify(event): copy = event.copy() for key in event.keys(): if (key not in allMergedKeys): copy.pop(key) return copy simplifiedActual = [simplify(event) for event in actualEvents] test.assertEqual(simplifiedActual, expectedEvents)
[ "def", "compareEvents", "(", "test", ",", "actualEvents", ",", "expectedEvents", ")", ":", "if", "(", "len", "(", "actualEvents", ")", "!=", "len", "(", "expectedEvents", ")", ")", ":", "test", ".", "assertEqual", "(", "actualEvents", ",", "expectedEvents", ...
compare two sequences of log events .
train
false
34,912
def dict_diff(left, right): dummy = object() return dict(filter((lambda (k, v): (left.get(k, dummy) != v)), right.iteritems()))
[ "def", "dict_diff", "(", "left", ",", "right", ")", ":", "dummy", "=", "object", "(", ")", "return", "dict", "(", "filter", "(", "(", "lambda", "(", "k", ",", "v", ")", ":", "(", "left", ".", "get", "(", "k", ",", "dummy", ")", "!=", "v", ")"...
computes a dictionary with the elements that are in the right but not or different in the left .
train
false
34,915
def default_providers(): return [PROVIDER_LOOKUP_INVERTED[p] for p in settings.PAYMENT_PROVIDERS]
[ "def", "default_providers", "(", ")", ":", "return", "[", "PROVIDER_LOOKUP_INVERTED", "[", "p", "]", "for", "p", "in", "settings", ".", "PAYMENT_PROVIDERS", "]" ]
returns a list of the default providers from the settings as the appropriate constants .
train
false
34,916
def nonzero_values(a): return a.flatten()[flatnonzero(a)]
[ "def", "nonzero_values", "(", "a", ")", ":", "return", "a", ".", "flatten", "(", ")", "[", "flatnonzero", "(", "a", ")", "]" ]
return a vector of non-zero elements contained in the input array .
train
false
34,917
def copy_kwargs(kwargs): vi = sys.version_info if ((vi[0] == 2) and (vi[1] <= 6) and (vi[3] < 5)): copy_kwargs = {} for key in kwargs: copy_kwargs[key.encode('utf-8')] = kwargs[key] else: copy_kwargs = copy.copy(kwargs) return copy_kwargs
[ "def", "copy_kwargs", "(", "kwargs", ")", ":", "vi", "=", "sys", ".", "version_info", "if", "(", "(", "vi", "[", "0", "]", "==", "2", ")", "and", "(", "vi", "[", "1", "]", "<=", "6", ")", "and", "(", "vi", "[", "3", "]", "<", "5", ")", ")...
there is a bug in python versions < 2 .
train
false
34,918
def cut_levels(nodes, level): if nodes: if (nodes[0].level == level): return nodes return sum((cut_levels(node.children, level) for node in nodes), [])
[ "def", "cut_levels", "(", "nodes", ",", "level", ")", ":", "if", "nodes", ":", "if", "(", "nodes", "[", "0", "]", ".", "level", "==", "level", ")", ":", "return", "nodes", "return", "sum", "(", "(", "cut_levels", "(", "node", ".", "children", ",", ...
for cutting the nav_extender levels if you have a from_level in the navigation .
train
false
34,920
def dnsdomain_register_for_zone(context, fqdomain, zone): return IMPL.dnsdomain_register_for_zone(context, fqdomain, zone)
[ "def", "dnsdomain_register_for_zone", "(", "context", ",", "fqdomain", ",", "zone", ")", ":", "return", "IMPL", ".", "dnsdomain_register_for_zone", "(", "context", ",", "fqdomain", ",", "zone", ")" ]
associated a dns domain with an availability zone .
train
false
34,921
def validate_user_access_to_subscribers_helper(user_profile, stream_dict, check_user_subscribed): if (user_profile is None): raise ValidationError('Missing user to validate access for') if (user_profile.realm_id != stream_dict['realm_id']): raise ValidationError('Requesting user not in given realm') if (user_profile.realm.is_zephyr_mirror_realm and (not stream_dict['invite_only'])): raise JsonableError(_('You cannot get subscribers for public streams in this realm')) if (stream_dict['invite_only'] and (not check_user_subscribed())): raise JsonableError(_('Unable to retrieve subscribers for invite-only stream'))
[ "def", "validate_user_access_to_subscribers_helper", "(", "user_profile", ",", "stream_dict", ",", "check_user_subscribed", ")", ":", "if", "(", "user_profile", "is", "None", ")", ":", "raise", "ValidationError", "(", "'Missing user to validate access for'", ")", "if", ...
helper for validate_user_access_to_subscribers that doesnt require a full stream object * check_user_subscribed is a function that when called with no arguments .
train
false
34,922
@require_backend('aws') def ebsblockdeviceapi_for_test(test_case): return get_blockdeviceapi_with_cleanup(test_case)
[ "@", "require_backend", "(", "'aws'", ")", "def", "ebsblockdeviceapi_for_test", "(", "test_case", ")", ":", "return", "get_blockdeviceapi_with_cleanup", "(", "test_case", ")" ]
create an ebsblockdeviceapi for use by tests .
train
false
34,923
def _get_host_non_ssds(host_reference): return _get_host_disks(host_reference).get('Non-SSDs')
[ "def", "_get_host_non_ssds", "(", "host_reference", ")", ":", "return", "_get_host_disks", "(", "host_reference", ")", ".", "get", "(", "'Non-SSDs'", ")" ]
helper function that returns a list of non-ssd objects for a given host .
train
false
34,924
def _has_ipv6(host): sock = None has_ipv6 = False if socket.has_ipv6: try: sock = socket.socket(socket.AF_INET6) sock.bind((host, 0)) has_ipv6 = True except Exception: pass if sock: sock.close() return has_ipv6
[ "def", "_has_ipv6", "(", "host", ")", ":", "sock", "=", "None", "has_ipv6", "=", "False", "if", "socket", ".", "has_ipv6", ":", "try", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET6", ")", "sock", ".", "bind", "(", "(", "h...
returns true if the system can bind an ipv6 address .
train
true
34,925
def test_main_tables(): main_tables_path = os.path.join(os.path.dirname(__file__), '../../doc/main-tables.rst') with open(main_tables_path) as f: doc_class_names = set(re.findall('^\\.\\. dex-table:: (\\w+)$', f.read(), re.MULTILINE)) mapped_class_names = set((cls.__name__ for cls in mapped_classes)) assert (mapped_class_names == doc_class_names)
[ "def", "test_main_tables", "(", ")", ":", "main_tables_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'../../doc/main-tables.rst'", ")", "with", "open", "(", "main_tables_path", ")", "as", "f...
check that tables .
train
false
34,926
def _is_notify_empty(notify_db): if (not notify_db): return True return (not (notify_db.on_complete or notify_db.on_success or notify_db.on_failure))
[ "def", "_is_notify_empty", "(", "notify_db", ")", ":", "if", "(", "not", "notify_db", ")", ":", "return", "True", "return", "(", "not", "(", "notify_db", ".", "on_complete", "or", "notify_db", ".", "on_success", "or", "notify_db", ".", "on_failure", ")", "...
notify_db is considered to be empty if notify_db is none and neither of on_complete .
train
false
34,927
def get_containing_library_from_library_dataset(trans, library_dataset): folder = library_dataset.folder while folder.parent: folder = folder.parent for library in trans.sa_session.query(trans.model.Library).filter(and_((trans.model.Library.table.c.deleted == false()), (trans.model.Library.table.c.name == folder.name))): if (library.root_folder == folder): return library return None
[ "def", "get_containing_library_from_library_dataset", "(", "trans", ",", "library_dataset", ")", ":", "folder", "=", "library_dataset", ".", "folder", "while", "folder", ".", "parent", ":", "folder", "=", "folder", ".", "parent", "for", "library", "in", "trans", ...
given a library_dataset .
train
false
34,928
def histeq(im, nbr_bins=256): (imhist, bins) = histogram(im.flatten(), nbr_bins, normed=True) cdf = imhist.cumsum() cdf = ((255 * cdf) / cdf[(-1)]) im2 = interp(im.flatten(), bins[:(-1)], cdf) return (im2.reshape(im.shape), cdf)
[ "def", "histeq", "(", "im", ",", "nbr_bins", "=", "256", ")", ":", "(", "imhist", ",", "bins", ")", "=", "histogram", "(", "im", ".", "flatten", "(", ")", ",", "nbr_bins", ",", "normed", "=", "True", ")", "cdf", "=", "imhist", ".", "cumsum", "(",...
histogram equalization of a grayscale image .
train
false
34,931
def dict_constructor_with_sequence_copy(logical_line): MESSAGE = 'K008 Must use a dict comprehension instead of a dict constructor with a sequence of key-value pairs.' dict_constructor_with_sequence_re = re.compile('.*\\bdict\\((\\[)?(\\(|\\[)(?!\\{)') if dict_constructor_with_sequence_re.match(logical_line): (yield (0, MESSAGE))
[ "def", "dict_constructor_with_sequence_copy", "(", "logical_line", ")", ":", "MESSAGE", "=", "'K008 Must use a dict comprehension instead of a dict constructor with a sequence of key-value pairs.'", "dict_constructor_with_sequence_re", "=", "re", ".", "compile", "(", "'.*\\\\bdict\\\\(...
should use a dict comprehension instead of a dict constructor .
train
false
34,933
def dynamic_string_scriptler_param(registry, xml_parent, data): dynamic_scriptler_param_common(registry, xml_parent, data, 'ScriptlerStringParameterDefinition')
[ "def", "dynamic_string_scriptler_param", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "dynamic_scriptler_param_common", "(", "registry", ",", "xml_parent", ",", "data", ",", "'ScriptlerStringParameterDefinition'", ")" ]
yaml: dynamic-string-scriptler dynamic parameter requires the jenkins :jenkins-wiki:jenkins dynamic parameter plug-in <dynamic+parameter+plug-in> .
train
false
34,935
def similarity(string1, string2, metric=LEVENSHTEIN): if (metric == LEVENSHTEIN): return levenshtein_similarity(string1, string2) if (metric == DICE): return dice_coefficient(string1, string2)
[ "def", "similarity", "(", "string1", ",", "string2", ",", "metric", "=", "LEVENSHTEIN", ")", ":", "if", "(", "metric", "==", "LEVENSHTEIN", ")", ":", "return", "levenshtein_similarity", "(", "string1", ",", "string2", ")", "if", "(", "metric", "==", "DICE"...
returns the similarity of string1 and string2 as a number between 0 .
train
false
34,936
def alloca_once_value(builder, value, name=''): storage = alloca_once(builder, value.type) builder.store(value, storage) return storage
[ "def", "alloca_once_value", "(", "builder", ",", "value", ",", "name", "=", "''", ")", ":", "storage", "=", "alloca_once", "(", "builder", ",", "value", ".", "type", ")", "builder", ".", "store", "(", "value", ",", "storage", ")", "return", "storage" ]
like alloca_once() .
train
false
34,937
def get_class_for_auth_version(auth_version): if (auth_version == '1.0'): cls = OpenStackIdentity_1_0_Connection elif (auth_version == '1.1'): cls = OpenStackIdentity_1_1_Connection elif ((auth_version == '2.0') or (auth_version == '2.0_apikey')): cls = OpenStackIdentity_2_0_Connection elif (auth_version == '2.0_password'): cls = OpenStackIdentity_2_0_Connection elif (auth_version == '2.0_voms'): cls = OpenStackIdentity_2_0_Connection_VOMS elif (auth_version == '3.x_password'): cls = OpenStackIdentity_3_0_Connection elif (auth_version == '3.x_oidc_access_token'): cls = OpenStackIdentity_3_0_Connection_OIDC_access_token else: raise LibcloudError('Unsupported Auth Version requested') return cls
[ "def", "get_class_for_auth_version", "(", "auth_version", ")", ":", "if", "(", "auth_version", "==", "'1.0'", ")", ":", "cls", "=", "OpenStackIdentity_1_0_Connection", "elif", "(", "auth_version", "==", "'1.1'", ")", ":", "cls", "=", "OpenStackIdentity_1_1_Connectio...
retrieve class for the provided auth version .
train
false
34,938
def format_stackdriver_json(record, message): (subsecond, second) = math.modf(record.created) payload = {'message': message, 'timestamp': {'seconds': int(second), 'nanos': int((subsecond * 1000000000.0))}, 'thread': record.thread, 'severity': record.levelname} return json.dumps(payload)
[ "def", "format_stackdriver_json", "(", "record", ",", "message", ")", ":", "(", "subsecond", ",", "second", ")", "=", "math", ".", "modf", "(", "record", ".", "created", ")", "payload", "=", "{", "'message'", ":", "message", ",", "'timestamp'", ":", "{",...
helper to format a logrecord in in stackdriver fluentd format .
train
true
34,939
def _draw_outlines(ax, outlines): outlines_ = dict([(k, v) for (k, v) in outlines.items() if (k not in ['patch', 'autoshrink'])]) for (key, (x_coord, y_coord)) in outlines_.items(): if ('mask' in key): continue ax.plot(x_coord, y_coord, color='k', linewidth=1, clip_on=False) return outlines_
[ "def", "_draw_outlines", "(", "ax", ",", "outlines", ")", ":", "outlines_", "=", "dict", "(", "[", "(", "k", ",", "v", ")", "for", "(", "k", ",", "v", ")", "in", "outlines", ".", "items", "(", ")", "if", "(", "k", "not", "in", "[", "'patch'", ...
draw the outlines for a topomap .
train
false
34,941
def weekday(year, month, day): return datetime.date(year, month, day).weekday()
[ "def", "weekday", "(", "year", ",", "month", ",", "day", ")", ":", "return", "datetime", ".", "date", "(", "year", ",", "month", ",", "day", ")", ".", "weekday", "(", ")" ]
return the position of a weekday: 0 - 7 .
train
false
34,942
def get_driver(type, provider): try: return DriverTypeFactoryMap[type](provider) except KeyError: raise DriverTypeNotFoundError(type)
[ "def", "get_driver", "(", "type", ",", "provider", ")", ":", "try", ":", "return", "DriverTypeFactoryMap", "[", "type", "]", "(", "provider", ")", "except", "KeyError", ":", "raise", "DriverTypeNotFoundError", "(", "type", ")" ]
get the db api object for the specific database type .
train
false
34,943
@cli.command('crop') @click.option('-b', '--border', type=int, help='Crop the image from all sides by this amount.') @processor def crop_cmd(images, border): for image in images: box = [0, 0, image.size[0], image.size[1]] if (border is not None): for (idx, val) in enumerate(box): box[idx] = max(0, (val - border)) click.echo(('Cropping "%s" by %dpx' % (image.filename, border))) (yield copy_filename(image.crop(box), image)) else: (yield image)
[ "@", "cli", ".", "command", "(", "'crop'", ")", "@", "click", ".", "option", "(", "'-b'", ",", "'--border'", ",", "type", "=", "int", ",", "help", "=", "'Crop the image from all sides by this amount.'", ")", "@", "processor", "def", "crop_cmd", "(", "images"...
crops an image from all edges .
train
false
34,944
def getIP(domain): try: return socket.gethostbyname(domain) except Exception: return False
[ "def", "getIP", "(", "domain", ")", ":", "try", ":", "return", "socket", ".", "gethostbyname", "(", "domain", ")", "except", "Exception", ":", "return", "False" ]
this method returns the first ip address string that responds as the given domain name .
train
false
34,947
def base64_url_decode_php_style(inp): import base64 padding_factor = ((4 - (len(inp) % 4)) % 4) inp += ('=' * padding_factor) return base64.b64decode(unicode(inp).translate(dict(zip(map(ord, u'-_'), u'+/'))))
[ "def", "base64_url_decode_php_style", "(", "inp", ")", ":", "import", "base64", "padding_factor", "=", "(", "(", "4", "-", "(", "len", "(", "inp", ")", "%", "4", ")", ")", "%", "4", ")", "inp", "+=", "(", "'='", "*", "padding_factor", ")", "return", ...
php follows a slightly different protocol for base64 url decode .
train
false
34,948
def get_supported_platform(): plat = get_build_platform() m = macosVersionString.match(plat) if ((m is not None) and (sys.platform == 'darwin')): try: plat = ('macosx-%s-%s' % ('.'.join(_macosx_vers()[:2]), m.group(3))) except ValueError: pass return plat
[ "def", "get_supported_platform", "(", ")", ":", "plat", "=", "get_build_platform", "(", ")", "m", "=", "macosVersionString", ".", "match", "(", "plat", ")", "if", "(", "(", "m", "is", "not", "None", ")", "and", "(", "sys", ".", "platform", "==", "'darw...
return this platforms maximum compatible version .
train
true
34,949
def abort_host_queue_entries(**filter_data): query = models.HostQueueEntry.query_objects(filter_data) query = query.filter(complete=False) models.AclGroup.check_abort_permissions(query) host_queue_entries = list(query.select_related()) rpc_utils.check_abort_synchronous_jobs(host_queue_entries) for queue_entry in host_queue_entries: queue_entry.abort()
[ "def", "abort_host_queue_entries", "(", "**", "filter_data", ")", ":", "query", "=", "models", ".", "HostQueueEntry", ".", "query_objects", "(", "filter_data", ")", "query", "=", "query", ".", "filter", "(", "complete", "=", "False", ")", "models", ".", "Acl...
abort a set of host queue entries .
train
false
34,950
def compute_optional_conf(conf_name, default_value, **all_config): conf_value = all_config.get(conf_name) if (conf_value is not None): conf_value = get_validator(conf_name)(conf_value) else: conf_value = default_value return conf_value
[ "def", "compute_optional_conf", "(", "conf_name", ",", "default_value", ",", "**", "all_config", ")", ":", "conf_value", "=", "all_config", ".", "get", "(", "conf_name", ")", "if", "(", "conf_value", "is", "not", "None", ")", ":", "conf_value", "=", "get_val...
returns *conf_name* settings if provided in *all_config* .
train
true
34,953
def validate_extra_file(val): try: (val % {'language': 'cs'}) except Exception as error: raise ValidationError((_('Bad format string (%s)') % str(error)))
[ "def", "validate_extra_file", "(", "val", ")", ":", "try", ":", "(", "val", "%", "{", "'language'", ":", "'cs'", "}", ")", "except", "Exception", "as", "error", ":", "raise", "ValidationError", "(", "(", "_", "(", "'Bad format string (%s)'", ")", "%", "s...
validates extra file to commit .
train
false
34,954
def test_for_compile_error(): try: can_compile(u'(fn [] (for)') except LexException as e: assert (e.message == u'Premature end of input') else: assert False try: can_compile(u'(fn [] (for)))') except LexException as e: assert (e.message == u"Ran into a RPAREN where it wasn't expected.") else: assert False try: can_compile(u'(fn [] (for [x] x))') except HyTypeError as e: assert (e.message == u"`for' requires an even number of args.") else: assert False try: can_compile(u'(fn [] (for [x xx]))') except HyTypeError as e: assert (e.message == u"`for' requires a body to evaluate") else: assert False try: can_compile(u'(fn [] (for [x xx] (else 1)))') except HyTypeError as e: assert (e.message == u"`for' requires a body to evaluate") else: assert False
[ "def", "test_for_compile_error", "(", ")", ":", "try", ":", "can_compile", "(", "u'(fn [] (for)'", ")", "except", "LexException", "as", "e", ":", "assert", "(", "e", ".", "message", "==", "u'Premature end of input'", ")", "else", ":", "assert", "False", "try",...
ensure we get compile error in tricky for cases .
train
false
34,955
def get_hardware_prefix(): with open('/proc/cmdline', 'r') as f: line = f.readline() settings = line.split(' ') prefix = None for setting in settings: if setting.startswith('osmcdev='): return setting[len('osmcdev='):] return None
[ "def", "get_hardware_prefix", "(", ")", ":", "with", "open", "(", "'/proc/cmdline'", ",", "'r'", ")", "as", "f", ":", "line", "=", "f", ".", "readline", "(", ")", "settings", "=", "line", ".", "split", "(", "' '", ")", "prefix", "=", "None", "for", ...
returns the prefix for the hardware type .
train
false
34,956
def refine(video, **kwargs): if (not isinstance(video, Episode)): logger.error('Cannot refine episodes') return if (video.series_tvdb_id and video.tvdb_id): logger.debug('No need to search') return logger.info('Searching series %r', video.series) results = search_series(video.series.lower()) if (not results): logger.warning('No results for series') return logger.debug('Found %d results', len(results)) matching_results = [] for result in results: matching_result = {} series_names = [result['seriesName']] series_names.extend(result['aliases']) original_match = series_re.match(result['seriesName']).groupdict() series_year = None if result['firstAired']: series_year = datetime.strptime(result['firstAired'], '%Y-%m-%d').year if (video.year and series_year and (video.year != series_year)): logger.debug('Discarding series %r mismatch on year %d', result['seriesName'], series_year) continue for series_name in series_names: (series, year, country) = series_re.match(series_name).groups() if year: year = int(year) if (year and (video.original_series or (video.year != year))): logger.debug('Discarding series name %r mismatch on year %d', series, year) continue if (sanitize(series) == sanitize(video.series)): logger.debug('Found exact match on series %r', series_name) matching_result['match'] = {'series': original_match['series'], 'year': series_year, 'original_series': (original_match['year'] is None)} break if matching_result: matching_result['data'] = result matching_results.append(matching_result) if (not matching_results): logger.error('No matching series found') return if (len(matching_results) > 1): logger.error('Multiple matches found') return matching_result = matching_results[0] series = get_series(matching_result['data']['id']) logger.debug('Found series %r', series) video.series = matching_result['match']['series'] video.year = matching_result['match']['year'] video.original_series = matching_result['match']['original_series'] video.series_tvdb_id = series['id'] video.series_imdb_id = (series['imdbId'] or None) logger.info('Getting series episode %dx%d', video.season, video.episode) episode = get_series_episode(video.series_tvdb_id, video.season, video.episode) if (not episode): logger.warning('No results for episode') return logger.debug('Found episode %r', episode) video.tvdb_id = episode['id'] video.title = (episode['episodeName'] or None) video.imdb_id = (episode['imdbId'] or None)
[ "def", "refine", "(", "video", ",", "**", "kwargs", ")", ":", "if", "(", "not", "isinstance", "(", "video", ",", "Episode", ")", ")", ":", "logger", ".", "error", "(", "'Cannot refine episodes'", ")", "return", "if", "(", "video", ".", "series_tvdb_id", ...
simplify an expression using assumptions .
train
true
34,957
def read_footer(filename): with open(filename, u'rb') as file_obj: if ((not _check_header_magic_bytes(file_obj)) or (not _check_footer_magic_bytes(file_obj))): raise ParquetFormatException(u'{0} is not a valid parquet file (missing magic bytes)'.format(filename)) return _read_footer(file_obj)
[ "def", "read_footer", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "u'rb'", ")", "as", "file_obj", ":", "if", "(", "(", "not", "_check_header_magic_bytes", "(", "file_obj", ")", ")", "or", "(", "not", "_check_footer_magic_bytes", "(", "...
read the footer and return the filemetadata for the specified filename .
train
true
34,958
def nts(s): p = s.find('\x00') if (p == (-1)): return s return s[:p]
[ "def", "nts", "(", "s", ")", ":", "p", "=", "s", ".", "find", "(", "'\\x00'", ")", "if", "(", "p", "==", "(", "-", "1", ")", ")", ":", "return", "s", "return", "s", "[", ":", "p", "]" ]
convert a null-terminated string field to a python string .
train
true
34,959
def calc_shared_phylotypes(otu_table, reference_sample=None): if reference_sample: ref_idx = reference_sample sample_ids = otu_table.ids() num_samples = len(sample_ids) result_array = zeros((num_samples, num_samples), dtype=int) for (i, samp1_id) in enumerate(sample_ids): for (j, samp2_id) in enumerate(sample_ids[:(i + 1)]): if reference_sample: result_array[(i, j)] = result_array[(j, i)] = _calc_shared_phylotypes_multiple(otu_table, [samp1_id, samp2_id, ref_idx]) else: result_array[(i, j)] = result_array[(j, i)] = _calc_shared_phylotypes_pairwise(otu_table, samp1_id, samp2_id) return (format_distance_matrix(sample_ids, result_array) + '\n')
[ "def", "calc_shared_phylotypes", "(", "otu_table", ",", "reference_sample", "=", "None", ")", ":", "if", "reference_sample", ":", "ref_idx", "=", "reference_sample", "sample_ids", "=", "otu_table", ".", "ids", "(", ")", "num_samples", "=", "len", "(", "sample_id...
calculates number of shared phylotypes for each pair of sample .
train
false
34,960
def ellipse_extent(a, b, theta): t = np.arctan2(((- b) * np.tan(theta)), a) dx = (((a * np.cos(t)) * np.cos(theta)) - ((b * np.sin(t)) * np.sin(theta))) t = np.arctan2(b, (a * np.tan(theta))) dy = (((b * np.sin(t)) * np.cos(theta)) + ((a * np.cos(t)) * np.sin(theta))) return np.abs([dx, dy])
[ "def", "ellipse_extent", "(", "a", ",", "b", ",", "theta", ")", ":", "t", "=", "np", ".", "arctan2", "(", "(", "(", "-", "b", ")", "*", "np", ".", "tan", "(", "theta", ")", ")", ",", "a", ")", "dx", "=", "(", "(", "(", "a", "*", "np", "...
calculates the extent of a box encapsulating a rotated 2d ellipse .
train
false
34,961
def GroupEncoder(field_number, is_repeated, is_packed): start_tag = TagBytes(field_number, wire_format.WIRETYPE_START_GROUP) end_tag = TagBytes(field_number, wire_format.WIRETYPE_END_GROUP) assert (not is_packed) if is_repeated: def EncodeRepeatedField(write, value): for element in value: write(start_tag) element._InternalSerialize(write) write(end_tag) return EncodeRepeatedField else: def EncodeField(write, value): write(start_tag) value._InternalSerialize(write) return write(end_tag) return EncodeField
[ "def", "GroupEncoder", "(", "field_number", ",", "is_repeated", ",", "is_packed", ")", ":", "start_tag", "=", "TagBytes", "(", "field_number", ",", "wire_format", ".", "WIRETYPE_START_GROUP", ")", "end_tag", "=", "TagBytes", "(", "field_number", ",", "wire_format"...
returns an encoder for a group field .
train
true
34,962
def get_po_filepath(lang_code, filename=None): base_dirpath = os.path.join(get_locale_path(lang_code=lang_code), 'LC_MESSAGES') return ((filename and os.path.join(base_dirpath, filename)) or base_dirpath)
[ "def", "get_po_filepath", "(", "lang_code", ",", "filename", "=", "None", ")", ":", "base_dirpath", "=", "os", ".", "path", ".", "join", "(", "get_locale_path", "(", "lang_code", "=", "lang_code", ")", ",", "'LC_MESSAGES'", ")", "return", "(", "(", "filena...
return the lc_messages directory for the language code .
train
false
34,964
def parse_directive(d): dir = d.strip() if (not dir.startswith('.')): return (dir, '') m = dir_sig_re.match(dir) if (not m): return (dir, '') (parsed_dir, parsed_args) = m.groups() return (parsed_dir.strip(), (' ' + parsed_args.strip()))
[ "def", "parse_directive", "(", "d", ")", ":", "dir", "=", "d", ".", "strip", "(", ")", "if", "(", "not", "dir", ".", "startswith", "(", "'.'", ")", ")", ":", "return", "(", "dir", ",", "''", ")", "m", "=", "dir_sig_re", ".", "match", "(", "dir"...
parse a directive signature .
train
false
34,965
def validate_directories(args): if (args.logdir and args.logdir_root): raise ValueError('--logdir and --logdir_root cannot be specified at the same time.') if (args.logdir and args.restore_from): raise ValueError('--logdir and --restore_from cannot be specified at the same time. This is to keep your previous model from unexpected overwrites.\nUse --logdir_root to specify the root of the directory which will be automatically created with current date and time, or use only --logdir to just continue the training from the last checkpoint.') logdir_root = args.logdir_root if (logdir_root is None): logdir_root = LOGDIR_ROOT logdir = args.logdir if (logdir is None): logdir = get_default_logdir(logdir_root) print('Using default logdir: {}'.format(logdir)) restore_from = args.restore_from if (restore_from is None): restore_from = logdir return {'logdir': logdir, 'logdir_root': args.logdir_root, 'restore_from': restore_from}
[ "def", "validate_directories", "(", "args", ")", ":", "if", "(", "args", ".", "logdir", "and", "args", ".", "logdir_root", ")", ":", "raise", "ValueError", "(", "'--logdir and --logdir_root cannot be specified at the same time.'", ")", "if", "(", "args", ".", "log...
validate and arrange directory related arguments .
train
false
34,966
def _pluck_classes(modules, classnames): klasses = [] for classname in classnames: klass = None for module in modules: if hasattr(module, classname): klass = getattr(module, classname) break if (not klass): packages = [m.__name__ for m in modules if (m is not None)] raise ClassNotFoundError(("No class '%s' found in %s" % (classname, ', '.join(packages)))) klasses.append(klass) return klasses
[ "def", "_pluck_classes", "(", "modules", ",", "classnames", ")", ":", "klasses", "=", "[", "]", "for", "classname", "in", "classnames", ":", "klass", "=", "None", "for", "module", "in", "modules", ":", "if", "hasattr", "(", "module", ",", "classname", ")...
gets a list of class names and a list of modules to pick from .
train
false
34,967
def get_stock_adjustment_div(request, supplier, product): latest_adjustment = StockAdjustment.objects.filter(product=product, supplier=supplier, type=StockAdjustmentType.INVENTORY).last() purchase_price = (latest_adjustment.purchase_price_value if latest_adjustment else Decimal('0.00')) context = {'product': product, 'supplier': supplier, 'delta_step': pow(0.1, product.sales_unit.decimals), 'adjustment_form': StockAdjustmentForm(initial={'purchase_price': purchase_price, 'delta': None})} if ('shuup.notify' in settings.INSTALLED_APPS): from shuup.notify.models import Notification context['alert_limit_form'] = AlertLimitForm(initial={'alert_limit': 0}) if (not get_missing_permissions(request.user, get_default_model_permissions(Notification))): context['notify_url'] = reverse('shuup_admin:notify.script.list') else: context['notify_url'] = '' return render_to_string('shuup/simple_supplier/admin/add_stock_form.jinja', context=context, request=request)
[ "def", "get_stock_adjustment_div", "(", "request", ",", "supplier", ",", "product", ")", ":", "latest_adjustment", "=", "StockAdjustment", ".", "objects", ".", "filter", "(", "product", "=", "product", ",", "supplier", "=", "supplier", ",", "type", "=", "Stock...
get html string to adjust stock values contains inputs for purchase_price_value and delta .
train
false
34,968
def MACD(ds, count, fastperiod=(- (2 ** 31)), slowperiod=(- (2 ** 31)), signalperiod=(- (2 ** 31))): ret = call_talib_with_ds(ds, count, talib.MACD, fastperiod, slowperiod, signalperiod) if (ret is None): ret = (None, None, None) return ret
[ "def", "MACD", "(", "ds", ",", "count", ",", "fastperiod", "=", "(", "-", "(", "2", "**", "31", ")", ")", ",", "slowperiod", "=", "(", "-", "(", "2", "**", "31", ")", ")", ",", "signalperiod", "=", "(", "-", "(", "2", "**", "31", ")", ")", ...
moving average convergence/divergence .
train
false
34,969
def get_ptb_words(): train = _retrieve_ptb_words('train.npz', _train_url) valid = _retrieve_ptb_words('valid.npz', _valid_url) test = _retrieve_ptb_words('test.npz', _test_url) return (train, valid, test)
[ "def", "get_ptb_words", "(", ")", ":", "train", "=", "_retrieve_ptb_words", "(", "'train.npz'", ",", "_train_url", ")", "valid", "=", "_retrieve_ptb_words", "(", "'valid.npz'", ",", "_valid_url", ")", "test", "=", "_retrieve_ptb_words", "(", "'test.npz'", ",", "...
gets the penn tree bank dataset as long word sequences .
train
false
34,971
@require_GET def document_revisions(request, document_slug, contributor_form=None): locale = request.GET.get('locale', request.LANGUAGE_CODE) try: doc = Document.objects.get(locale=locale, slug=document_slug) except Document.DoesNotExist: parent_doc = get_object_or_404(Document, locale=settings.WIKI_DEFAULT_LANGUAGE, slug=document_slug) translation = parent_doc.translated_to(locale) if translation: url = reverse('wiki.document_revisions', args=[translation.slug], locale=locale) return HttpResponseRedirect(url) else: raise Http404 revs = Revision.objects.filter(document=doc).order_by('-created', '-id') if request.is_ajax(): template = 'wiki/includes/revision_list.html' else: template = 'wiki/history.html' form = (contributor_form or AddContributorForm()) return render(request, template, {'revisions': revs, 'document': doc, 'contributor_form': form})
[ "@", "require_GET", "def", "document_revisions", "(", "request", ",", "document_slug", ",", "contributor_form", "=", "None", ")", ":", "locale", "=", "request", ".", "GET", ".", "get", "(", "'locale'", ",", "request", ".", "LANGUAGE_CODE", ")", "try", ":", ...
list all the revisions of a given document .
train
false
34,972
def lazy_gettext(string, **variables): return support.LazyProxy(gettext, string, **variables)
[ "def", "lazy_gettext", "(", "string", ",", "**", "variables", ")", ":", "return", "support", ".", "LazyProxy", "(", "gettext", ",", "string", ",", "**", "variables", ")" ]
a lazy version of gettext .
train
false
34,973
def sha1_mangle_key(key): return sha1(key).hexdigest()
[ "def", "sha1_mangle_key", "(", "key", ")", ":", "return", "sha1", "(", "key", ")", ".", "hexdigest", "(", ")" ]
wrapper for dogpiles sha1_mangle_key .
train
false
34,974
def set_virt_auto_boot(self, num): if (num == '<<inherit>>'): self.virt_auto_boot = '<<inherit>>' return try: inum = int(num) if ((inum == 0) or (inum == 1)): self.virt_auto_boot = inum return raise CX(_(("invalid virt_auto_boot value (%s): value must be either '0' (disabled) or '1' (enabled)" % inum))) except: raise CX(_(("invalid virt_auto_boot value (%s): value must be either '0' (disabled) or '1' (enabled)" % num)))
[ "def", "set_virt_auto_boot", "(", "self", ",", "num", ")", ":", "if", "(", "num", "==", "'<<inherit>>'", ")", ":", "self", ".", "virt_auto_boot", "=", "'<<inherit>>'", "return", "try", ":", "inum", "=", "int", "(", "num", ")", "if", "(", "(", "inum", ...
for virt only .
train
false
34,976
@task def psql(sql, show=True): out = postgres((u'psql -c "%s"' % sql)) if show: print_command(sql) return out
[ "@", "task", "def", "psql", "(", "sql", ",", "show", "=", "True", ")", ":", "out", "=", "postgres", "(", "(", "u'psql -c \"%s\"'", "%", "sql", ")", ")", "if", "show", ":", "print_command", "(", "sql", ")", "return", "out" ]
runs sql against the projects database .
train
false
34,977
def _build_dict(data): result = {} result['jid'] = data[0] result['tgt_type'] = data[1] result['cmd'] = data[2] result['tgt'] = data[3] result['kwargs'] = data[4] result['ret'] = data[5] result['user'] = data[6] result['arg'] = data[7] result['fun'] = data[8] return result
[ "def", "_build_dict", "(", "data", ")", ":", "result", "=", "{", "}", "result", "[", "'jid'", "]", "=", "data", "[", "0", "]", "result", "[", "'tgt_type'", "]", "=", "data", "[", "1", "]", "result", "[", "'cmd'", "]", "=", "data", "[", "2", "]"...
rebuild dict .
train
true
34,978
def _send_firebase_message(u_id, message=None): url = '{}/channels/{}.json'.format(_get_firebase_db_url(), u_id) if message: return _get_http().request(url, 'PATCH', body=message) else: return _get_http().request(url, 'DELETE')
[ "def", "_send_firebase_message", "(", "u_id", ",", "message", "=", "None", ")", ":", "url", "=", "'{}/channels/{}.json'", ".", "format", "(", "_get_firebase_db_url", "(", ")", ",", "u_id", ")", "if", "message", ":", "return", "_get_http", "(", ")", ".", "r...
updates data in firebase .
train
false
34,980
def case_sensitive(stem, word): ch = [] for i in range(len(stem)): if (word[i] == word[i].upper()): ch.append(stem[i].upper()) else: ch.append(stem[i]) return ''.join(ch)
[ "def", "case_sensitive", "(", "stem", ",", "word", ")", ":", "ch", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "stem", ")", ")", ":", "if", "(", "word", "[", "i", "]", "==", "word", "[", "i", "]", ".", "upper", "(", ")", ")",...
check whether the filesystem at the given path is case sensitive .
train
false
34,981
@pytest.mark.parametrize('orgname, expected', [(None, ''), ('test', 'test')]) def test_unset_organization(qapp, orgname, expected): qapp.setOrganizationName(orgname) assert (qapp.organizationName() == expected) with qtutils.unset_organization(): assert (qapp.organizationName() == '') assert (qapp.organizationName() == expected)
[ "@", "pytest", ".", "mark", ".", "parametrize", "(", "'orgname, expected'", ",", "[", "(", "None", ",", "''", ")", ",", "(", "'test'", ",", "'test'", ")", "]", ")", "def", "test_unset_organization", "(", "qapp", ",", "orgname", ",", "expected", ")", ":...
test unset_organization .
train
false
34,982
def addPointsAtZ(edgePair, points, radius, vertexes, z): carveIntersectionFirst = getCarveIntersectionFromEdge(edgePair.edges[0], vertexes, z) carveIntersectionSecond = getCarveIntersectionFromEdge(edgePair.edges[1], vertexes, z) intercircle.addPointsFromSegment(carveIntersectionFirst, carveIntersectionSecond, points, radius, 0.3)
[ "def", "addPointsAtZ", "(", "edgePair", ",", "points", ",", "radius", ",", "vertexes", ",", "z", ")", ":", "carveIntersectionFirst", "=", "getCarveIntersectionFromEdge", "(", "edgePair", ".", "edges", "[", "0", "]", ",", "vertexes", ",", "z", ")", "carveInte...
add point complexes on the segment between the edge intersections with z .
train
false
34,983
def insert_sql(project, default_dataset, sql_path): client = bigquery.Client(project=project) with open(sql_path) as f: for line in f: line = line.strip() if (not line.startswith('INSERT')): continue print 'Running query: {}{}'.format(line[:60], ('...' if (len(line) > 60) else '')) query = client.run_sync_query(line) query.use_legacy_sql = False query.default_dataset = client.dataset(default_dataset) query.run()
[ "def", "insert_sql", "(", "project", ",", "default_dataset", ",", "sql_path", ")", ":", "client", "=", "bigquery", ".", "Client", "(", "project", "=", "project", ")", "with", "open", "(", "sql_path", ")", "as", "f", ":", "for", "line", "in", "f", ":", ...
run all the sql statements in a sql file .
train
false
34,984
def is_numlike(obj): try: (obj + 1) except TypeError: return False else: return True
[ "def", "is_numlike", "(", "obj", ")", ":", "try", ":", "(", "obj", "+", "1", ")", "except", "TypeError", ":", "return", "False", "else", ":", "return", "True" ]
return true if *obj* looks like a number .
train
false
34,985
def get_tap_device_name(interface_id): if (not interface_id): LOG.warning(_LW('Invalid Interface ID, will lead to incorrect tap device name')) tap_device_name = (n_const.TAP_DEVICE_PREFIX + interface_id[:constants.RESOURCE_ID_LENGTH]) return tap_device_name
[ "def", "get_tap_device_name", "(", "interface_id", ")", ":", "if", "(", "not", "interface_id", ")", ":", "LOG", ".", "warning", "(", "_LW", "(", "'Invalid Interface ID, will lead to incorrect tap device name'", ")", ")", "tap_device_name", "=", "(", "n_const", ".", ...
convert port id into device name format expected by linux bridge .
train
false