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
25,142
def on_valid(valid_content_type, on_invalid=json): invalid_kwargs = introspect.generate_accepted_kwargs(on_invalid, 'request', 'response') invalid_takes_response = introspect.takes_all_arguments(on_invalid, 'response') def wrapper(function): valid_kwargs = introspect.generate_accepted_kwargs(function, 'request', '...
[ "def", "on_valid", "(", "valid_content_type", ",", "on_invalid", "=", "json", ")", ":", "invalid_kwargs", "=", "introspect", ".", "generate_accepted_kwargs", "(", "on_invalid", ",", "'request'", ",", "'response'", ")", "invalid_takes_response", "=", "introspect", "....
renders as the specified content type only if no errors are found in the provided data object .
train
true
25,143
def getManipulatedPaths(close, elementNode, loop, prefix, sideLength): if (len(loop) < 1): return [[]] derivation = BottomDerivation(elementNode, prefix) targetMatrix = matrix.getBranchMatrixSetElementNode(elementNode) transformedLoop = matrix.getTransformedVector3s(matrix.getIdentityTetragrid(targetMatrix.tetrag...
[ "def", "getManipulatedPaths", "(", "close", ",", "elementNode", ",", "loop", ",", "prefix", ",", "sideLength", ")", ":", "if", "(", "len", "(", "loop", ")", "<", "1", ")", ":", "return", "[", "[", "]", "]", "derivation", "=", "BottomDerivation", "(", ...
get round loop .
train
false
25,144
def create_comm_note(obj, version, author, body, note_type=comm.NO_ACTION, perms=None, attachments=None): perms = (perms or {}) if (('developer' not in perms) and (note_type in comm.REVIEWER_NOTE_TYPES)): perms['developer'] = False create_perms = dict(((('read_permission_%s' % key), has_perm) for (key, has_perm) i...
[ "def", "create_comm_note", "(", "obj", ",", "version", ",", "author", ",", "body", ",", "note_type", "=", "comm", ".", "NO_ACTION", ",", "perms", "=", "None", ",", "attachments", "=", "None", ")", ":", "perms", "=", "(", "perms", "or", "{", "}", ")",...
creates a note on an obj versions thread .
train
false
25,145
def parse_partial_identifier(word): p = sqlparse.parse(word)[0] n_tok = len(p.tokens) if ((n_tok == 1) and isinstance(p.tokens[0], Identifier)): return p.tokens[0] elif p.token_next_by(m=(Error, '"'))[1]: return parse_partial_identifier((word + '"')) else: return None
[ "def", "parse_partial_identifier", "(", "word", ")", ":", "p", "=", "sqlparse", ".", "parse", "(", "word", ")", "[", "0", "]", "n_tok", "=", "len", "(", "p", ".", "tokens", ")", "if", "(", "(", "n_tok", "==", "1", ")", "and", "isinstance", "(", "...
attempt to parse a word as an identifier word may include a schema qualification .
train
false
25,146
def stub_out_image_service(test): image_service = FakeImageService() test.stub_out('nova.image.glance.get_remote_image_service', (lambda x, y: (image_service, y))) test.stub_out('nova.image.glance.get_default_image_service', (lambda : image_service)) test.useFixture(nova_fixtures.ConfPatcher(group='glance', api_ser...
[ "def", "stub_out_image_service", "(", "test", ")", ":", "image_service", "=", "FakeImageService", "(", ")", "test", ".", "stub_out", "(", "'nova.image.glance.get_remote_image_service'", ",", "(", "lambda", "x", ",", "y", ":", "(", "image_service", ",", "y", ")",...
stubs out the image service for the test with the fakeimageservice .
train
false
25,148
def reorder_title(title, articles=('the',), separators=(',', ', ')): ltitle = title.lower() for article in articles: for separator in separators: suffix = (separator + article) if (ltitle[(- len(suffix)):] == suffix): return ((title[((- len(suffix)) + len(separator)):] + ' ') + title[:(- len(suffix))]) r...
[ "def", "reorder_title", "(", "title", ",", "articles", "=", "(", "'the'", ",", ")", ",", "separators", "=", "(", "','", ",", "', '", ")", ")", ":", "ltitle", "=", "title", ".", "lower", "(", ")", "for", "article", "in", "articles", ":", "for", "sep...
reorder the title .
train
false
25,149
def get_descrs(arrays, col_name_map): out_descrs = [] for (out_name, in_names) in six.iteritems(col_name_map): in_cols = [arr[name] for (arr, name) in zip(arrays, in_names) if (name is not None)] names = [name for name in in_names if (name is not None)] try: dtype = common_dtype(in_cols) except TableMergeE...
[ "def", "get_descrs", "(", "arrays", ",", "col_name_map", ")", ":", "out_descrs", "=", "[", "]", "for", "(", "out_name", ",", "in_names", ")", "in", "six", ".", "iteritems", "(", "col_name_map", ")", ":", "in_cols", "=", "[", "arr", "[", "name", "]", ...
find the dtypes descrs resulting from merging the list of arrays dtypes .
train
false
25,150
def generate_config(hass, passwd): from homeassistant.components.mqtt import PROTOCOL_311 config = {'listeners': {'default': {'max-connections': 50000, 'bind': '0.0.0.0:1883', 'type': 'tcp'}, 'ws-1': {'bind': '0.0.0.0:8080', 'type': 'ws'}}, 'auth': {'allow-anonymous': (hass.config.api.api_password is None)}, 'plugins...
[ "def", "generate_config", "(", "hass", ",", "passwd", ")", ":", "from", "homeassistant", ".", "components", ".", "mqtt", "import", "PROTOCOL_311", "config", "=", "{", "'listeners'", ":", "{", "'default'", ":", "{", "'max-connections'", ":", "50000", ",", "'b...
generate a configuration based on current home assistant instance .
train
false
25,151
def upload_imageattachment(request, obj): return upload_media(request, ImageAttachmentUploadForm, create_imageattachment, obj=obj)
[ "def", "upload_imageattachment", "(", "request", ",", "obj", ")", ":", "return", "upload_media", "(", "request", ",", "ImageAttachmentUploadForm", ",", "create_imageattachment", ",", "obj", "=", "obj", ")" ]
uploads image attachments .
train
false
25,152
def simple_rnn(incoming, n_units, activation='sigmoid', dropout=None, bias=True, weights_init=None, return_seq=False, return_state=False, initial_state=None, dynamic=False, trainable=True, restore=True, reuse=False, scope=None, name='SimpleRNN'): cell = BasicRNNCell(n_units, activation=activation, bias=bias, weights_i...
[ "def", "simple_rnn", "(", "incoming", ",", "n_units", ",", "activation", "=", "'sigmoid'", ",", "dropout", "=", "None", ",", "bias", "=", "True", ",", "weights_init", "=", "None", ",", "return_seq", "=", "False", ",", "return_state", "=", "False", ",", "...
simple rnn .
train
false
25,157
def is_git_dir(d): if osp.isdir(d): if (osp.isdir(osp.join(d, 'objects')) and osp.isdir(osp.join(d, 'refs'))): headref = osp.join(d, 'HEAD') return (osp.isfile(headref) or (osp.islink(headref) and os.readlink(headref).startswith('refs'))) elif (osp.isfile(osp.join(d, 'gitdir')) and osp.isfile(osp.join(d, 'co...
[ "def", "is_git_dir", "(", "d", ")", ":", "if", "osp", ".", "isdir", "(", "d", ")", ":", "if", "(", "osp", ".", "isdir", "(", "osp", ".", "join", "(", "d", ",", "'objects'", ")", ")", "and", "osp", ".", "isdir", "(", "osp", ".", "join", "(", ...
from gits setup .
train
true
25,158
def advantage(cpu_dt, gpu_dt): assert ((gpu_dt >= 0) and (cpu_dt >= 0)) if ((gpu_dt == 0) and (cpu_dt == 0)): return numpy.nan elif (gpu_dt == 0): return numpy.inf else: return (cpu_dt / gpu_dt)
[ "def", "advantage", "(", "cpu_dt", ",", "gpu_dt", ")", ":", "assert", "(", "(", "gpu_dt", ">=", "0", ")", "and", "(", "cpu_dt", ">=", "0", ")", ")", "if", "(", "(", "gpu_dt", "==", "0", ")", "and", "(", "cpu_dt", "==", "0", ")", ")", ":", "re...
return ratio of cpu_dt / gpu_dt .
train
false
25,161
def _validate_connectivity(image_dim, connectivity, offset): if (connectivity is None): connectivity = 1 if np.isscalar(connectivity): c_connectivity = ndi.generate_binary_structure(image_dim, connectivity) else: c_connectivity = np.array(connectivity, bool) if (c_connectivity.ndim != image_dim): raise Va...
[ "def", "_validate_connectivity", "(", "image_dim", ",", "connectivity", ",", "offset", ")", ":", "if", "(", "connectivity", "is", "None", ")", ":", "connectivity", "=", "1", "if", "np", ".", "isscalar", "(", "connectivity", ")", ":", "c_connectivity", "=", ...
convert any valid connectivity to a structuring element and offset .
train
false
25,164
def unlock_file(filename): log.trace('Removing lock for {0}'.format(filename)) lock = (filename + '.lock') try: os.remove(lock) except OSError as exc: log.trace('Unable to remove lock for {0}: {1}'.format(filename, exc))
[ "def", "unlock_file", "(", "filename", ")", ":", "log", ".", "trace", "(", "'Removing lock for {0}'", ".", "format", "(", "filename", ")", ")", "lock", "=", "(", "filename", "+", "'.lock'", ")", "try", ":", "os", ".", "remove", "(", "lock", ")", "excep...
unlock file .
train
true
25,165
def _course_outline_json(request, course_module): return create_xblock_info(course_module, include_child_info=True, course_outline=True, include_children_predicate=(lambda xblock: (not (xblock.category == 'vertical'))), user=request.user)
[ "def", "_course_outline_json", "(", "request", ",", "course_module", ")", ":", "return", "create_xblock_info", "(", "course_module", ",", "include_child_info", "=", "True", ",", "course_outline", "=", "True", ",", "include_children_predicate", "=", "(", "lambda", "x...
returns a json representation of the course module and recursively all of its children .
train
false
25,166
def ip_to_int(ip): ret = 0 for octet in ip.split('.'): ret = ((ret * 256) + int(octet)) return ret
[ "def", "ip_to_int", "(", "ip", ")", ":", "ret", "=", "0", "for", "octet", "in", "ip", ".", "split", "(", "'.'", ")", ":", "ret", "=", "(", "(", "ret", "*", "256", ")", "+", "int", "(", "octet", ")", ")", "return", "ret" ]
converts an ip address to an integer .
train
true
25,169
@testing.requires_testing_data @requires_mayavi @requires_mne @requires_freesurfer def test_subject_source_with_fsaverage(): from mne.gui._file_traits import MRISubjectSource tempdir = _TempDir() mri = MRISubjectSource() assert_false(mri.can_create_fsaverage) assert_raises(RuntimeError, mri.create_fsaverage) mri....
[ "@", "testing", ".", "requires_testing_data", "@", "requires_mayavi", "@", "requires_mne", "@", "requires_freesurfer", "def", "test_subject_source_with_fsaverage", "(", ")", ":", "from", "mne", ".", "gui", ".", "_file_traits", "import", "MRISubjectSource", "tempdir", ...
test subjectselector .
train
false
25,170
def build_versions_form(project): attrs = {'project': project} versions_qs = project.versions.all() active = versions_qs.filter(active=True) if active.exists(): choices = [(version.slug, version.verbose_name) for version in active] attrs['default-version'] = forms.ChoiceField(label=_('Default Version'), choices...
[ "def", "build_versions_form", "(", "project", ")", ":", "attrs", "=", "{", "'project'", ":", "project", "}", "versions_qs", "=", "project", ".", "versions", ".", "all", "(", ")", "active", "=", "versions_qs", ".", "filter", "(", "active", "=", "True", ")...
versions form with a list of versions and version privacy levels .
train
false
25,172
def award(): mode = session.s3.hrm.mode def prep(r): if (mode is not None): auth.permission.fail() return True s3.prep = prep output = s3_rest_controller() return output
[ "def", "award", "(", ")", ":", "mode", "=", "session", ".", "s3", ".", "hrm", ".", "mode", "def", "prep", "(", "r", ")", ":", "if", "(", "mode", "is", "not", "None", ")", ":", "auth", ".", "permission", ".", "fail", "(", ")", "return", "True", ...
volunteer awards controller .
train
false
25,173
def is_iterable(x): try: iter(x) except TypeError: return False else: return True
[ "def", "is_iterable", "(", "x", ")", ":", "try", ":", "iter", "(", "x", ")", "except", "TypeError", ":", "return", "False", "else", ":", "return", "True" ]
are we being asked to look up a list of things .
train
false
25,174
def os_like_constants(): os_like = util.get_systemd_os_like() if os_like: for os_name in os_like: if (os_name in CLI_DEFAULTS.keys()): return CLI_DEFAULTS[os_name] return {}
[ "def", "os_like_constants", "(", ")", ":", "os_like", "=", "util", ".", "get_systemd_os_like", "(", ")", "if", "os_like", ":", "for", "os_name", "in", "os_like", ":", "if", "(", "os_name", "in", "CLI_DEFAULTS", ".", "keys", "(", ")", ")", ":", "return", ...
try to get constants for distribution with similar layout and configuration .
train
false
25,176
def is_standard_module(modname, std_path=None): modname = modname.split('.')[0] try: filename = file_from_modpath([modname]) except ImportError: return False if (filename is None): return True filename = _normalize_path(filename) if filename.startswith(_cache_normalize_path(EXT_LIB_DIR)): return False if...
[ "def", "is_standard_module", "(", "modname", ",", "std_path", "=", "None", ")", ":", "modname", "=", "modname", ".", "split", "(", "'.'", ")", "[", "0", "]", "try", ":", "filename", "=", "file_from_modpath", "(", "[", "modname", "]", ")", "except", "Im...
try to guess if a module is a standard python module :type modname: str .
train
false
25,177
def test_bootstrap_ols(): ols_fit = (lambda X, y: np.dot(np.dot(np.linalg.inv(np.dot(X.T, X)), X.T), y)) X = np.column_stack((rs.randn(50, 4), np.ones(50))) w = [2, 4, 0, 3, 5] y_noisy = (np.dot(X, w) + (rs.randn(50) * 20)) y_lownoise = (np.dot(X, w) + rs.randn(50)) n_boot = 500 w_boot_noisy = algo.bootstrap(X, ...
[ "def", "test_bootstrap_ols", "(", ")", ":", "ols_fit", "=", "(", "lambda", "X", ",", "y", ":", "np", ".", "dot", "(", "np", ".", "dot", "(", "np", ".", "linalg", ".", "inv", "(", "np", ".", "dot", "(", "X", ".", "T", ",", "X", ")", ")", ","...
test bootstrap of ols model fit .
train
false
25,179
@contextlib.contextmanager def report_scope(observation): current = _reporters[(-1)] old = current.observation current.observation = observation (yield) current.observation = old
[ "@", "contextlib", ".", "contextmanager", "def", "report_scope", "(", "observation", ")", ":", "current", "=", "_reporters", "[", "(", "-", "1", ")", "]", "old", "=", "current", ".", "observation", "current", ".", "observation", "=", "observation", "(", "y...
returns a report scope with the current reporter .
train
false
25,180
def test_masked_row_with_object_col(): t = table.Table([[1]], dtype=['O'], masked=True) if NUMPY_LT_1_8: with pytest.raises(ValueError): t['col0'].mask = False t[0].as_void() with pytest.raises(ValueError): t['col0'].mask = True t[0].as_void() else: t['col0'].mask = False assert (t[0]['col0'] == ...
[ "def", "test_masked_row_with_object_col", "(", ")", ":", "t", "=", "table", ".", "Table", "(", "[", "[", "1", "]", "]", ",", "dtype", "=", "[", "'O'", "]", ",", "masked", "=", "True", ")", "if", "NUMPY_LT_1_8", ":", "with", "pytest", ".", "raises", ...
numpy < 1 .
train
false
25,182
def get_organization_courses(organization_id): if (not organizations_enabled()): return [] from organizations import api as organizations_api return organizations_api.get_organization_courses(organization_id)
[ "def", "get_organization_courses", "(", "organization_id", ")", ":", "if", "(", "not", "organizations_enabled", "(", ")", ")", ":", "return", "[", "]", "from", "organizations", "import", "api", "as", "organizations_api", "return", "organizations_api", ".", "get_or...
client api operation adapter/wrapper .
train
false
25,185
def supportsTeams(endpoint): return endpoint.usesExtension(ns_uri)
[ "def", "supportsTeams", "(", "endpoint", ")", ":", "return", "endpoint", ".", "usesExtension", "(", "ns_uri", ")" ]
does the given endpoint advertise support for launchpad teams? .
train
false
25,186
@pytest.mark.django_db @pytest.mark.parametrize('view,model,get_object,service_provider_attr', [(PaymentMethodEditView, PaymentMethod, get_default_payment_method, 'payment_processor'), (ShippingMethodEditView, ShippingMethod, get_default_shipping_method, 'carrier')]) def test_behavior_add_save(rf, admin_user, view, mod...
[ "@", "pytest", ".", "mark", ".", "django_db", "@", "pytest", ".", "mark", ".", "parametrize", "(", "'view,model,get_object,service_provider_attr'", ",", "[", "(", "PaymentMethodEditView", ",", "PaymentMethod", ",", "get_default_payment_method", ",", "'payment_processor'...
to make things little bit more simple lets use only english as a language .
train
false
25,187
def preprocess_file(filename, cpp_path='cpp', cpp_args=''): path_list = [cpp_path] if isinstance(cpp_args, list): path_list += cpp_args elif (cpp_args != ''): path_list += [cpp_args] path_list += [filename] try: pipe = Popen(path_list, stdout=PIPE, universal_newlines=True) text = pipe.communicate()[0] exc...
[ "def", "preprocess_file", "(", "filename", ",", "cpp_path", "=", "'cpp'", ",", "cpp_args", "=", "''", ")", ":", "path_list", "=", "[", "cpp_path", "]", "if", "isinstance", "(", "cpp_args", ",", "list", ")", ":", "path_list", "+=", "cpp_args", "elif", "("...
preprocess a file using cpp .
train
false
25,188
@cli.command() @click.option('--username', prompt=True, help="The developer's shown username.") @click.option('--email', prompt='E-Mail', help="The developer's email address") @click.password_option(help='The login password.') @pass_repo def setuser(repo, username, email, password): repo.set_config('username', usernam...
[ "@", "cli", ".", "command", "(", ")", "@", "click", ".", "option", "(", "'--username'", ",", "prompt", "=", "True", ",", "help", "=", "\"The developer's shown username.\"", ")", "@", "click", ".", "option", "(", "'--email'", ",", "prompt", "=", "'E-Mail'",...
sets the user credentials .
train
false
25,189
def load_pytest_conf(path, parser): namespace = {} exec open(path, 'rb').read() in namespace if ('update_parser' in namespace): namespace['update_parser'](parser) return namespace.get('CustomPyTester', PyTester)
[ "def", "load_pytest_conf", "(", "path", ",", "parser", ")", ":", "namespace", "=", "{", "}", "exec", "open", "(", "path", ",", "'rb'", ")", ".", "read", "(", ")", "in", "namespace", "if", "(", "'update_parser'", "in", "namespace", ")", ":", "namespace"...
loads a pytestconf .
train
false
25,190
def gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries): lib_opts = [] for dir in library_dirs: lib_opts.append(compiler.library_dir_option(dir)) for dir in runtime_library_dirs: opt = compiler.runtime_library_dir_option(dir) if isinstance(opt, list): lib_opts = (lib_opts + opt) else:...
[ "def", "gen_lib_options", "(", "compiler", ",", "library_dirs", ",", "runtime_library_dirs", ",", "libraries", ")", ":", "lib_opts", "=", "[", "]", "for", "dir", "in", "library_dirs", ":", "lib_opts", ".", "append", "(", "compiler", ".", "library_dir_option", ...
generate linker options for searching library directories and linking with specific libraries .
train
false
25,191
def py_encode(symb2freq): heap = [[wt, [sym, u'']] for (sym, wt) in symb2freq.items()] heapify(heap) while (len(heap) > 1): lo = heappop(heap) hi = heappop(heap) for pair in lo[1:]: pair[1] = (u'0' + pair[1]) for pair in hi[1:]: pair[1] = (u'1' + pair[1]) heappush(heap, (([(lo[0] + hi[0])] + lo[1:]) ...
[ "def", "py_encode", "(", "symb2freq", ")", ":", "heap", "=", "[", "[", "wt", ",", "[", "sym", ",", "u''", "]", "]", "for", "(", "sym", ",", "wt", ")", "in", "symb2freq", ".", "items", "(", ")", "]", "heapify", "(", "heap", ")", "while", "(", ...
huffman encode the given dict mapping symbols to weights from rosetta code .
train
false
25,193
def sign_certificate_request(keypair, dn, request, serial, validity_period, digest, start=None, additional_extensions=()): if (start is None): start = datetime.datetime.utcnow() expire = (start + datetime.timedelta(seconds=validity_period)) start = start.strftime('%Y%m%d%H%M%SZ') expire = expire.strftime('%Y%m%d%...
[ "def", "sign_certificate_request", "(", "keypair", ",", "dn", ",", "request", ",", "serial", ",", "validity_period", ",", "digest", ",", "start", "=", "None", ",", "additional_extensions", "=", "(", ")", ")", ":", "if", "(", "start", "is", "None", ")", "...
sign a certificaterequest and return a certificate .
train
false
25,194
def getNewRepository(): return ExportRepository()
[ "def", "getNewRepository", "(", ")", ":", "return", "ExportRepository", "(", ")" ]
get the repository constructor .
train
false
25,195
def remove_profile_images(profile_image_names): storage = get_profile_image_storage() for name in profile_image_names.values(): storage.delete(name)
[ "def", "remove_profile_images", "(", "profile_image_names", ")", ":", "storage", "=", "get_profile_image_storage", "(", ")", "for", "name", "in", "profile_image_names", ".", "values", "(", ")", ":", "storage", ".", "delete", "(", "name", ")" ]
physically remove the image files specified in profile_image_names .
train
false
25,196
def profile_start(name): _profiles_running[name] = time.time() _profiles_stack.append(name)
[ "def", "profile_start", "(", "name", ")", ":", "_profiles_running", "[", "name", "]", "=", "time", ".", "time", "(", ")", "_profiles_stack", ".", "append", "(", "name", ")" ]
starts a profiling interval with specific name profiling data is sent to the client with next data batch .
train
false
25,197
def getLargestCenterOutsetLoopFromLoop(loop, radius, thresholdRatio=0.9): if (radius == 0.0): return loop radius = abs(radius) points = getPointsFromLoop(loop, radius, thresholdRatio) centers = getCentersFromPoints(points, (globalIntercircleMultiplier * radius)) largestCenterOutset = None largestOutsetArea = (-...
[ "def", "getLargestCenterOutsetLoopFromLoop", "(", "loop", ",", "radius", ",", "thresholdRatio", "=", "0.9", ")", ":", "if", "(", "radius", "==", "0.0", ")", ":", "return", "loop", "radius", "=", "abs", "(", "radius", ")", "points", "=", "getPointsFromLoop", ...
get the largest circle outset loop from the loop .
train
false
25,198
def copy_data(data, dest, header=None, use_put=None): ret = None if use_put: udata = data else: udata = urllib.urlencode(data) if utils.is_url(dest): ret = copy_remote(udata, dest, use_put) if header: return ret[header] else: if header: ret = (dest + str(time.time())) dest = (ret + '/_task_resul...
[ "def", "copy_data", "(", "data", ",", "dest", ",", "header", "=", "None", ",", "use_put", "=", "None", ")", ":", "ret", "=", "None", "if", "use_put", ":", "udata", "=", "data", "else", ":", "udata", "=", "urllib", ".", "urlencode", "(", "data", ")"...
copy data to a destination to aid in debugging .
train
false
25,199
def _any_pandas_objects(terms): return any((isinstance(term.value, pd.core.generic.PandasObject) for term in terms))
[ "def", "_any_pandas_objects", "(", "terms", ")", ":", "return", "any", "(", "(", "isinstance", "(", "term", ".", "value", ",", "pd", ".", "core", ".", "generic", ".", "PandasObject", ")", "for", "term", "in", "terms", ")", ")" ]
check a sequence of terms for instances of pandasobject .
train
true
25,200
def make_dataset(X, y, sample_weight, random_state=None): rng = check_random_state(random_state) seed = rng.randint(1, np.iinfo(np.int32).max) if sp.issparse(X): dataset = CSRDataset(X.data, X.indptr, X.indices, y, sample_weight, seed=seed) intercept_decay = SPARSE_INTERCEPT_DECAY else: dataset = ArrayDataset...
[ "def", "make_dataset", "(", "X", ",", "y", ",", "sample_weight", ",", "random_state", "=", "None", ")", ":", "rng", "=", "check_random_state", "(", "random_state", ")", "seed", "=", "rng", ".", "randint", "(", "1", ",", "np", ".", "iinfo", "(", "np", ...
create dataset abstraction for sparse and dense inputs .
train
false
25,201
def askUser(text, parent=None, help='', defaultno=False, msgfunc=None, title='Anki'): if (not parent): parent = aqt.mw.app.activeWindow() if (not msgfunc): msgfunc = QMessageBox.question sb = (QMessageBox.Yes | QMessageBox.No) if help: sb |= QMessageBox.Help while 1: if defaultno: default = QMessageBox....
[ "def", "askUser", "(", "text", ",", "parent", "=", "None", ",", "help", "=", "''", ",", "defaultno", "=", "False", ",", "msgfunc", "=", "None", ",", "title", "=", "'Anki'", ")", ":", "if", "(", "not", "parent", ")", ":", "parent", "=", "aqt", "."...
show a yes/no question .
train
false
25,203
def broadcast_to_sharejs(action, sharejs_uuid, node=None, wiki_name='home', data=None): url = 'http://{host}:{port}/{action}/{id}/'.format(host=wiki_settings.SHAREJS_HOST, port=wiki_settings.SHAREJS_PORT, action=action, id=sharejs_uuid) if ((action == 'redirect') or (action == 'delete')): redirect_url = urllib.quot...
[ "def", "broadcast_to_sharejs", "(", "action", ",", "sharejs_uuid", ",", "node", "=", "None", ",", "wiki_name", "=", "'home'", ",", "data", "=", "None", ")", ":", "url", "=", "'http://{host}:{port}/{action}/{id}/'", ".", "format", "(", "host", "=", "wiki_settin...
broadcast an action to all documents connected to a wiki .
train
false
25,204
def dict_formatter(view, value): return json.dumps(value, ensure_ascii=False)
[ "def", "dict_formatter", "(", "view", ",", "value", ")", ":", "return", "json", ".", "dumps", "(", "value", ",", "ensure_ascii", "=", "False", ")" ]
removes unicode entities when displaying dict as string .
train
false
25,205
def test_eppstein_matching(): G = nx.Graph() G.add_nodes_from(['a', 2, 3, 4], bipartite=0) G.add_nodes_from([1, 'b', 'c'], bipartite=1) G.add_edges_from([('a', 1), ('a', 'b'), (2, 'b'), (2, 'c'), (3, 'c'), (4, 1)]) matching = eppstein_matching(G) assert_true((len(matching) == len(maximum_matching(G)))) assert al...
[ "def", "test_eppstein_matching", "(", ")", ":", "G", "=", "nx", ".", "Graph", "(", ")", "G", ".", "add_nodes_from", "(", "[", "'a'", ",", "2", ",", "3", ",", "4", "]", ",", "bipartite", "=", "0", ")", "G", ".", "add_nodes_from", "(", "[", "1", ...
test in accordance to issue #1927 .
train
false
25,206
def clashing(): ns = {} exec_('from sympy import *', ns) clash1 = {} clash2 = {} while ns: (k, _) = ns.popitem() if (k in _greek): clash2[k] = Symbol(k) _greek.remove(k) elif (k in _latin): clash1[k] = Symbol(k) _latin.remove(k) clash = {} clash.update(clash1) clash.update(clash2) return (cla...
[ "def", "clashing", "(", ")", ":", "ns", "=", "{", "}", "exec_", "(", "'from sympy import *'", ",", "ns", ")", "clash1", "=", "{", "}", "clash2", "=", "{", "}", "while", "ns", ":", "(", "k", ",", "_", ")", "=", "ns", ".", "popitem", "(", ")", ...
return the clashing-symbols dictionaries .
train
false
25,207
@handle_response_format @treeio_login_required def item_view(request, folderPath, itemPath, response_format='html'): try: item = KnowledgeItem.by_path(folderPath, itemPath) except KnowledgeItem.DoesNotExist: raise Http404 if (not item): raise Http404 items = Object.filter_permitted(manager=KnowledgeItem.objec...
[ "@", "handle_response_format", "@", "treeio_login_required", "def", "item_view", "(", "request", ",", "folderPath", ",", "itemPath", ",", "response_format", "=", "'html'", ")", ":", "try", ":", "item", "=", "KnowledgeItem", ".", "by_path", "(", "folderPath", ","...
item view .
train
false
25,208
@before.each_scenario def process_requires_tags(scenario): tag_re = re.compile('requires_stub_(?P<server>[^_]+)') for tag in scenario.tags: requires = tag_re.match(tag) if requires: if (requires.group('server') == 'youtube'): if (not is_youtube_available(YOUTUBE_API_URLS)): scenario.steps = [] re...
[ "@", "before", ".", "each_scenario", "def", "process_requires_tags", "(", "scenario", ")", ":", "tag_re", "=", "re", ".", "compile", "(", "'requires_stub_(?P<server>[^_]+)'", ")", "for", "tag", "in", "scenario", ".", "tags", ":", "requires", "=", "tag_re", "."...
process the scenario tags to make sure that any requirements are met prior to that scenario being executed .
train
false
25,209
def api_prefix(url_prefix=None, api_version=None): if (url_prefix is None): url_prefix = config.URL_PREFIX if (api_version is None): api_version = config.API_VERSION prefix = (('/%s' % url_prefix) if url_prefix else '') version = (('/%s' % api_version) if api_version else '') return (prefix + version)
[ "def", "api_prefix", "(", "url_prefix", "=", "None", ",", "api_version", "=", "None", ")", ":", "if", "(", "url_prefix", "is", "None", ")", ":", "url_prefix", "=", "config", ".", "URL_PREFIX", "if", "(", "api_version", "is", "None", ")", ":", "api_versio...
returns the prefix to api endpoints .
train
false
25,212
def test_human_readable_custom(): f = formatters.HumanReadable() assert (f(None) == u('\xe2\x88\x85')) f = formatters.HumanReadable(none_char='/') assert (f(None) == '/')
[ "def", "test_human_readable_custom", "(", ")", ":", "f", "=", "formatters", ".", "HumanReadable", "(", ")", "assert", "(", "f", "(", "None", ")", "==", "u", "(", "'\\xe2\\x88\\x85'", ")", ")", "f", "=", "formatters", ".", "HumanReadable", "(", "none_char",...
test human_readable formatter option .
train
false
25,213
def gather_bootstrap_script(bootstrap=None): if (not HAS_CLOUD): return (False, 'config.gather_bootstrap_script is unavailable') ret = salt.utils.cloud.update_bootstrap(__opts__, url=bootstrap) if (('Success' in ret) and (len(ret['Success']['Files updated']) > 0)): return ret['Success']['Files updated'][0]
[ "def", "gather_bootstrap_script", "(", "bootstrap", "=", "None", ")", ":", "if", "(", "not", "HAS_CLOUD", ")", ":", "return", "(", "False", ",", "'config.gather_bootstrap_script is unavailable'", ")", "ret", "=", "salt", ".", "utils", ".", "cloud", ".", "updat...
download the salt-bootstrap script .
train
true
25,214
def float_to_byte(value, mantissabits=5, zeroexp=2): fzero = ((63 - zeroexp) << mantissabits) bits = unpack('i', pack('f', value))[0] smallfloat = (bits >> (24 - mantissabits)) if (smallfloat < fzero): if (bits <= 0): result = chr(0) else: result = chr(1) elif (smallfloat >= (fzero + 256)): result = ch...
[ "def", "float_to_byte", "(", "value", ",", "mantissabits", "=", "5", ",", "zeroexp", "=", "2", ")", ":", "fzero", "=", "(", "(", "63", "-", "zeroexp", ")", "<<", "mantissabits", ")", "bits", "=", "unpack", "(", "'i'", ",", "pack", "(", "'f'", ",", ...
encodes a floating point number in a single byte .
train
false
25,216
def test_sigmoid(): def ref_sigmoid(x): if (x >= 0): return (1 / (1 + np.exp((- x)))) else: z = np.exp(x) return (z / (1 + z)) sigmoid = np.vectorize(ref_sigmoid) x = K.placeholder(ndim=2) f = K.function([x], [activations.sigmoid(x)]) test_values = get_standard_values() result = f([test_values])[0] ...
[ "def", "test_sigmoid", "(", ")", ":", "def", "ref_sigmoid", "(", "x", ")", ":", "if", "(", "x", ">=", "0", ")", ":", "return", "(", "1", "/", "(", "1", "+", "np", ".", "exp", "(", "(", "-", "x", ")", ")", ")", ")", "else", ":", "z", "=", ...
test using a numerically stable reference sigmoid implementation .
train
false
25,217
def generate_tasks(**kwargs): tasks = _local_tasks() for (fun, args) in tasks: fun(*args) tasks.clear()
[ "def", "generate_tasks", "(", "**", "kwargs", ")", ":", "tasks", "=", "_local_tasks", "(", ")", "for", "(", "fun", ",", "args", ")", "in", "tasks", ":", "fun", "(", "*", "args", ")", "tasks", ".", "clear", "(", ")" ]
goes through thread local index update tasks set and generates celery tasks for all tasks in the set .
train
false
25,220
def get_cursor_position(fd=1): csbi = get_console_screen_buffer_info(fd=fd) coord = csbi.dwCursorPosition return (coord.X, coord.Y)
[ "def", "get_cursor_position", "(", "fd", "=", "1", ")", ":", "csbi", "=", "get_console_screen_buffer_info", "(", "fd", "=", "fd", ")", "coord", "=", "csbi", ".", "dwCursorPosition", "return", "(", "coord", ".", "X", ",", "coord", ".", "Y", ")" ]
gets the current cursor position as an tuple .
train
false
25,222
def get_local_facts_from_file(filename): local_facts = dict() try: ini_facts = configparser.SafeConfigParser() ini_facts.read(filename) for section in ini_facts.sections(): local_facts[section] = dict() for (key, value) in ini_facts.items(section): local_facts[section][key] = value except (configpars...
[ "def", "get_local_facts_from_file", "(", "filename", ")", ":", "local_facts", "=", "dict", "(", ")", "try", ":", "ini_facts", "=", "configparser", ".", "SafeConfigParser", "(", ")", "ini_facts", ".", "read", "(", "filename", ")", "for", "section", "in", "ini...
retrieve local facts from fact file args: filename : local facts file returns: dict: the retrieved facts .
train
false
25,223
def miniEditImages(): return {'Select': BitmapImage(file='/usr/include/X11/bitmaps/left_ptr'), 'Switch': PhotoImage(data='\nR0lGODlhLgAgAPcAAB2ZxGq61imex4zH3RWWwmK41tzd3vn9/jCiyfX7/Q6SwFay0gBlmtnZ2snJ\nyr+2tAuMu6rY6D6kyfHx8XO/2Uqszjmly6DU5uXz+JLN4uz3+kSrzlKx0ZeZm2K21BuYw67a6QB9\nr+Xl5rW2uHW61On1+UGpzbrf6xiXwny9166vsML...
[ "def", "miniEditImages", "(", ")", ":", "return", "{", "'Select'", ":", "BitmapImage", "(", "file", "=", "'/usr/include/X11/bitmaps/left_ptr'", ")", ",", "'Switch'", ":", "PhotoImage", "(", "data", "=", "'\\nR0lGODlhLgAgAPcAAB2ZxGq61imex4zH3RWWwmK41tzd3vn9/jCiyfX7/Q6SwFay...
create and return images for miniedit .
train
false
25,224
def unpack_ext(ext_path): modcache = os.path.join(OPTIONS.saltdir, 'running_data', 'var', 'cache', 'salt', 'minion', 'extmods') tfile = tarfile.TarFile.gzopen(ext_path) old_umask = os.umask(63) tfile.extractall(path=modcache) tfile.close() os.umask(old_umask) os.unlink(ext_path) ver_path = os.path.join(modcache...
[ "def", "unpack_ext", "(", "ext_path", ")", ":", "modcache", "=", "os", ".", "path", ".", "join", "(", "OPTIONS", ".", "saltdir", ",", "'running_data'", ",", "'var'", ",", "'cache'", ",", "'salt'", ",", "'minion'", ",", "'extmods'", ")", "tfile", "=", "...
unpack the external modules .
train
true
25,225
def _stringsToObjects(strings, arglist, proto): objects = {} myStrings = strings.copy() for (argname, argparser) in arglist: argparser.fromBox(argname, myStrings, objects, proto) return objects
[ "def", "_stringsToObjects", "(", "strings", ",", "arglist", ",", "proto", ")", ":", "objects", "=", "{", "}", "myStrings", "=", "strings", ".", "copy", "(", ")", "for", "(", "argname", ",", "argparser", ")", "in", "arglist", ":", "argparser", ".", "fro...
convert an ampbox to a dictionary of python objects .
train
true
25,226
def _find_closest_point_on_path(lc, point): ds = np.sum(((lc - point[None, :]) ** 2), 1) imin = np.argmin(ds) dmin = np.inf xcmin = None legmin = (None, None) closed = mlab.is_closed_polygon(lc) legs = [] if ((imin > 0) or closed): legs.append((((imin - 1) % len(lc)), imin)) if ((imin < (len(lc) - 1)) or clo...
[ "def", "_find_closest_point_on_path", "(", "lc", ",", "point", ")", ":", "ds", "=", "np", ".", "sum", "(", "(", "(", "lc", "-", "point", "[", "None", ",", ":", "]", ")", "**", "2", ")", ",", "1", ")", "imin", "=", "np", ".", "argmin", "(", "d...
lc: coordinates of vertices point: coordinates of test point .
train
false
25,227
def flushdb(host=None, port=None, db=None, password=None): server = _connect(host, port, db, password) return server.flushdb()
[ "def", "flushdb", "(", "host", "=", "None", ",", "port", "=", "None", ",", "db", "=", "None", ",", "password", "=", "None", ")", ":", "server", "=", "_connect", "(", "host", ",", "port", ",", "db", ",", "password", ")", "return", "server", ".", "...
remove all keys from the selected database cli example: .
train
true
25,228
def _addHeaderToRequest(request, header): requestHeaders = request.requestHeaders (name, value) = header values = requestHeaders.getRawHeaders(name) if (values is not None): values.append(value) else: requestHeaders.setRawHeaders(name, [value]) if (name == 'content-length'): request.gotLength(int(value)) ...
[ "def", "_addHeaderToRequest", "(", "request", ",", "header", ")", ":", "requestHeaders", "=", "request", ".", "requestHeaders", "(", "name", ",", "value", ")", "=", "header", "values", "=", "requestHeaders", ".", "getRawHeaders", "(", "name", ")", "if", "(",...
add a header tuple to a request header object .
train
false
25,229
def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): auth(profile, **connection_args) if (_OS_IDENTITY_API_VERSION > 2): return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) el...
[ "def", "project_update", "(", "project_id", "=", "None", ",", "name", "=", "None", ",", "description", "=", "None", ",", "enabled", "=", "None", ",", "profile", "=", "None", ",", "**", "connection_args", ")", ":", "auth", "(", "profile", ",", "**", "co...
update a tenants information the following fields may be updated: name .
train
true
25,230
def v7(method_v7): frame = currentframe().f_back return frame.f_locals.get(method_v7.__name__, method_v7)
[ "def", "v7", "(", "method_v7", ")", ":", "frame", "=", "currentframe", "(", ")", ".", "f_back", "return", "frame", ".", "f_locals", ".", "get", "(", "method_v7", ".", "__name__", ",", "method_v7", ")" ]
decorate a method that supports the old-style api only .
train
false
25,232
def format_jnlp_file_lines(web_flag, url, tep_fp): lines = [jnlp_top_block] if web_flag: lines += ['http://topiaryexplorer.sourceforge.net/app/'] else: topiaryexplorer_project_dir = load_qiime_config()['topiaryexplorer_project_dir'] if topiaryexplorer_project_dir: lines += [('file:' + topiaryexplorer_projec...
[ "def", "format_jnlp_file_lines", "(", "web_flag", ",", "url", ",", "tep_fp", ")", ":", "lines", "=", "[", "jnlp_top_block", "]", "if", "web_flag", ":", "lines", "+=", "[", "'http://topiaryexplorer.sourceforge.net/app/'", "]", "else", ":", "topiaryexplorer_project_di...
format the jnlp file for topiaryexplorer .
train
false
25,233
@core_helper def sorted_extras(package_extras, auto_clean=False, subs=None, exclude=None): if (not exclude): exclude = config.get('package_hide_extras', []) output = [] for extra in sorted(package_extras, key=(lambda x: x['key'])): if (extra.get('state') == 'deleted'): continue (k, v) = (extra['key'], extra...
[ "@", "core_helper", "def", "sorted_extras", "(", "package_extras", ",", "auto_clean", "=", "False", ",", "subs", "=", "None", ",", "exclude", "=", "None", ")", ":", "if", "(", "not", "exclude", ")", ":", "exclude", "=", "config", ".", "get", "(", "'pac...
used for outputting package extras .
train
false
25,236
def getitem(a, b): return a[b]
[ "def", "getitem", "(", "a", ",", "b", ")", ":", "return", "a", "[", "b", "]" ]
get item from an iterable at index .
train
false
25,237
def normalize_spaces(s): return ' '.join(s.split())
[ "def", "normalize_spaces", "(", "s", ")", ":", "return", "' '", ".", "join", "(", "s", ".", "split", "(", ")", ")" ]
replace any sequence of whitespace characters with a single space .
train
false
25,238
def test_solve_rational(): assert (solve(((x - (y ** 3)) / ((y ** 2) * sqrt((1 - (y ** 2))))), x) == [(y ** 3)])
[ "def", "test_solve_rational", "(", ")", ":", "assert", "(", "solve", "(", "(", "(", "x", "-", "(", "y", "**", "3", ")", ")", "/", "(", "(", "y", "**", "2", ")", "*", "sqrt", "(", "(", "1", "-", "(", "y", "**", "2", ")", ")", ")", ")", "...
test solve for rational functions .
train
false
25,239
def backup_create(context, values): return IMPL.backup_create(context, values)
[ "def", "backup_create", "(", "context", ",", "values", ")", ":", "return", "IMPL", ".", "backup_create", "(", "context", ",", "values", ")" ]
create a backup from the values dictionary .
train
false
25,240
def _delete_asset(course_key, asset_key_string): if asset_key_string: try: asset_key = AssetKey.from_string(asset_key_string) except InvalidKeyError: if ('/' == asset_key_string[0]): asset_key_string = asset_key_string[1:] try: asset_key = AssetKey.from_string(asset_key_string) except Invali...
[ "def", "_delete_asset", "(", "course_key", ",", "asset_key_string", ")", ":", "if", "asset_key_string", ":", "try", ":", "asset_key", "=", "AssetKey", ".", "from_string", "(", "asset_key_string", ")", "except", "InvalidKeyError", ":", "if", "(", "'/'", "==", "...
internal method used to create asset key from string and remove asset by calling delete_asset method of assets module .
train
false
25,241
def no_os_popen(logical_line): if ('os.popen(' in logical_line): (yield (0, 'N348 Deprecated library function os.popen(). Replace it using subprocess module. '))
[ "def", "no_os_popen", "(", "logical_line", ")", ":", "if", "(", "'os.popen('", "in", "logical_line", ")", ":", "(", "yield", "(", "0", ",", "'N348 Deprecated library function os.popen(). Replace it using subprocess module. '", ")", ")" ]
disallow os .
train
false
25,243
def instance_metadata_update(context, instance_uuid, metadata, delete): return IMPL.instance_metadata_update(context, instance_uuid, metadata, delete)
[ "def", "instance_metadata_update", "(", "context", ",", "instance_uuid", ",", "metadata", ",", "delete", ")", ":", "return", "IMPL", ".", "instance_metadata_update", "(", "context", ",", "instance_uuid", ",", "metadata", ",", "delete", ")" ]
update metadata if it exists .
train
false
25,244
@utils.arg('fixed_ip', metavar='<fixed_ip>', help=_('Fixed IP Address.')) @deprecated_network def do_fixed_ip_reserve(cs, args): cs.fixed_ips.reserve(args.fixed_ip)
[ "@", "utils", ".", "arg", "(", "'fixed_ip'", ",", "metavar", "=", "'<fixed_ip>'", ",", "help", "=", "_", "(", "'Fixed IP Address.'", ")", ")", "@", "deprecated_network", "def", "do_fixed_ip_reserve", "(", "cs", ",", "args", ")", ":", "cs", ".", "fixed_ips"...
reserve a fixed ip .
train
false
25,245
def getWrappedInteger(integer, modulo): if (integer >= modulo): return modulo if (integer >= 0): return integer return (integer % modulo)
[ "def", "getWrappedInteger", "(", "integer", ",", "modulo", ")", ":", "if", "(", "integer", ">=", "modulo", ")", ":", "return", "modulo", "if", "(", "integer", ">=", "0", ")", ":", "return", "integer", "return", "(", "integer", "%", "modulo", ")" ]
get wrapped integer .
train
false
25,246
def Std(xs, mu=None, ddof=0): var = Var(xs, mu, ddof) return math.sqrt(var)
[ "def", "Std", "(", "xs", ",", "mu", "=", "None", ",", "ddof", "=", "0", ")", ":", "var", "=", "Var", "(", "xs", ",", "mu", ",", "ddof", ")", "return", "math", ".", "sqrt", "(", "var", ")" ]
computes standard deviation .
train
false
25,247
@hook.command() def shorten(text): args = text.split() url = args[0] custom = (args[1] if (len(args) > 1) else None) try: return web.shorten(url, custom=custom) except web.ServiceError as e: return e.message
[ "@", "hook", ".", "command", "(", ")", "def", "shorten", "(", "text", ")", ":", "args", "=", "text", ".", "split", "(", ")", "url", "=", "args", "[", "0", "]", "custom", "=", "(", "args", "[", "1", "]", "if", "(", "len", "(", "args", ")", "...
smartly shorten a given string .
train
false
25,248
def clientresp(data, **kwargs): creds = config.get_credentials() cfg = config.get_config() dumps_kwargs = {'sort_keys': True, 'cls': utils.PlotlyJSONEncoder} payload = {'platform': 'python', 'version': version.__version__, 'args': _json.dumps(data, **dumps_kwargs), 'un': creds['username'], 'key': creds['api_key'], ...
[ "def", "clientresp", "(", "data", ",", "**", "kwargs", ")", ":", "creds", "=", "config", ".", "get_credentials", "(", ")", "cfg", "=", "config", ".", "get_config", "(", ")", "dumps_kwargs", "=", "{", "'sort_keys'", ":", "True", ",", "'cls'", ":", "util...
deprecated endpoint .
train
false
25,250
def _check_header_magic_bytes(file_obj): file_obj.seek(0, 0) magic = file_obj.read(4) return (magic == 'PAR1')
[ "def", "_check_header_magic_bytes", "(", "file_obj", ")", ":", "file_obj", ".", "seek", "(", "0", ",", "0", ")", "magic", "=", "file_obj", ".", "read", "(", "4", ")", "return", "(", "magic", "==", "'PAR1'", ")" ]
check if the file-like obj has the par1 magic bytes at the header .
train
false
25,252
def cliques_containing_node(G, nodes=None, cliques=None): if (cliques is None): cliques = list(find_cliques(G)) if (nodes is None): nodes = list(G.nodes()) if (not isinstance(nodes, list)): v = nodes vcliques = [c for c in cliques if (v in c)] else: vcliques = {} for v in nodes: vcliques[v] = [c for ...
[ "def", "cliques_containing_node", "(", "G", ",", "nodes", "=", "None", ",", "cliques", "=", "None", ")", ":", "if", "(", "cliques", "is", "None", ")", ":", "cliques", "=", "list", "(", "find_cliques", "(", "G", ")", ")", "if", "(", "nodes", "is", "...
returns a list of cliques containing the given node .
train
false
25,253
def _add_retry_host(filter_properties, host, node): retry = filter_properties.get('retry', None) if (not retry): return hosts = retry['hosts'] hosts.append([host, node])
[ "def", "_add_retry_host", "(", "filter_properties", ",", "host", ",", "node", ")", ":", "retry", "=", "filter_properties", ".", "get", "(", "'retry'", ",", "None", ")", "if", "(", "not", "retry", ")", ":", "return", "hosts", "=", "retry", "[", "'hosts'",...
add a retry entry for the selected compute node .
train
false
25,254
def mirror_y(clip, apply_to='mask'): return clip.fl_image((lambda f: f[::(-1)]), apply_to=apply_to)
[ "def", "mirror_y", "(", "clip", ",", "apply_to", "=", "'mask'", ")", ":", "return", "clip", ".", "fl_image", "(", "(", "lambda", "f", ":", "f", "[", ":", ":", "(", "-", "1", ")", "]", ")", ",", "apply_to", "=", "apply_to", ")" ]
flips the clip vertically .
train
false
25,256
def make_derivative_operator(M, z): def doit(C): r = ((z * C.diff(z)) + (C * M)) r = r.applyfunc(make_simp(z)) return r return doit
[ "def", "make_derivative_operator", "(", "M", ",", "z", ")", ":", "def", "doit", "(", "C", ")", ":", "r", "=", "(", "(", "z", "*", "C", ".", "diff", "(", "z", ")", ")", "+", "(", "C", "*", "M", ")", ")", "r", "=", "r", ".", "applyfunc", "(...
create a derivative operator .
train
false
25,257
def hmc_move(s_rng, positions, energy_fn, stepsize, n_steps): initial_vel = s_rng.normal(size=positions.shape) (final_pos, final_vel) = simulate_dynamics(initial_pos=positions, initial_vel=initial_vel, stepsize=stepsize, n_steps=n_steps, energy_fn=energy_fn) accept = metropolis_hastings_accept(energy_prev=hamiltonia...
[ "def", "hmc_move", "(", "s_rng", ",", "positions", ",", "energy_fn", ",", "stepsize", ",", "n_steps", ")", ":", "initial_vel", "=", "s_rng", ".", "normal", "(", "size", "=", "positions", ".", "shape", ")", "(", "final_pos", ",", "final_vel", ")", "=", ...
this function performs one-step of hybrid monte-carlo sampling .
train
false
25,258
def _zpklp2lp(z, p, k, wo=1): degree = _relative_degree(z, p) z_lp = [(wo * z1) for z1 in z] p_lp = [(wo * p1) for p1 in p] k_lp = (k * (wo ** degree)) return (z_lp, p_lp, k_lp)
[ "def", "_zpklp2lp", "(", "z", ",", "p", ",", "k", ",", "wo", "=", "1", ")", ":", "degree", "=", "_relative_degree", "(", "z", ",", "p", ")", "z_lp", "=", "[", "(", "wo", "*", "z1", ")", "for", "z1", "in", "z", "]", "p_lp", "=", "[", "(", ...
transform a lowpass filter prototype to a different frequency .
train
false
25,260
def __get_tags(vm_): t = config.get_cloud_config_value('tags', vm_, __opts__, default='[]', search_global=False) try: tags = literal_eval(t) except Exception: tags = None if ((not tags) or (not isinstance(tags, list))): tags = None return tags
[ "def", "__get_tags", "(", "vm_", ")", ":", "t", "=", "config", ".", "get_cloud_config_value", "(", "'tags'", ",", "vm_", ",", "__opts__", ",", "default", "=", "'[]'", ",", "search_global", "=", "False", ")", "try", ":", "tags", "=", "literal_eval", "(", ...
get configured tags .
train
true
25,261
def reset(): _runtime.reset()
[ "def", "reset", "(", ")", ":", "_runtime", ".", "reset", "(", ")" ]
interface to git-reset(1)_ .
train
false
25,262
def test_allknn_sk_estimator(): check_estimator(AllKNN)
[ "def", "test_allknn_sk_estimator", "(", ")", ":", "check_estimator", "(", "AllKNN", ")" ]
test the sklearn estimator compatibility .
train
false
25,263
def compareSegmentLength(endpoint, otherEndpoint): if (endpoint.segmentLength > otherEndpoint.segmentLength): return 1 if (endpoint.segmentLength < otherEndpoint.segmentLength): return (-1) return 0
[ "def", "compareSegmentLength", "(", "endpoint", ",", "otherEndpoint", ")", ":", "if", "(", "endpoint", ".", "segmentLength", ">", "otherEndpoint", ".", "segmentLength", ")", ":", "return", "1", "if", "(", "endpoint", ".", "segmentLength", "<", "otherEndpoint", ...
get comparison in order to sort endpoints in ascending order of segment length .
train
false
25,265
def _stdin_ready_other(): return True
[ "def", "_stdin_ready_other", "(", ")", ":", "return", "True" ]
return true .
train
false
25,267
def get_bind_data(zone_id, profile): conn = _get_driver(profile=profile) zone = conn.get_zone(zone_id) return conn.export_zone_to_bind_format(zone)
[ "def", "get_bind_data", "(", "zone_id", ",", "profile", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "zone", "=", "conn", ".", "get_zone", "(", "zone_id", ")", "return", "conn", ".", "export_zone_to_bind_format", "(", "zone", ...
export zone to the bind compatible format .
train
true
25,269
def manage_entries(options, selection, approved): approved_text = (u'approved' if approved else u'pending') with Session() as session: if (selection == u'all'): entries = list_pending_entries(session=session, approved=(not approved)) else: try: entry = get_entry_by_id(session, selection) if (entry.a...
[ "def", "manage_entries", "(", "options", ",", "selection", ",", "approved", ")", ":", "approved_text", "=", "(", "u'approved'", "if", "approved", "else", "u'pending'", ")", "with", "Session", "(", ")", "as", "session", ":", "if", "(", "selection", "==", "u...
manage pending entries .
train
false
25,270
def inthread(func): @wraps(func) def wrapped(*a, **kw): return threads.deferToThread(func, *a, **kw) return wrapped
[ "def", "inthread", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapped", "(", "*", "a", ",", "**", "kw", ")", ":", "return", "threads", ".", "deferToThread", "(", "func", ",", "*", "a", ",", "**", "kw", ")", "return", "wrapped"...
decorator to call a function in a thread and return a deferred with the result .
train
false
25,272
def validateMasterOption(master): try: (hostname, port) = master.split(':') port = int(port) except (TypeError, ValueError): raise usage.UsageError("master must have the form 'hostname:port'")
[ "def", "validateMasterOption", "(", "master", ")", ":", "try", ":", "(", "hostname", ",", "port", ")", "=", "master", ".", "split", "(", "':'", ")", "port", "=", "int", "(", "port", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise...
validate master command line option .
train
true
25,273
def is_cnf(expr): return _is_form(expr, And, Or)
[ "def", "is_cnf", "(", "expr", ")", ":", "return", "_is_form", "(", "expr", ",", "And", ",", "Or", ")" ]
test whether or not an expression is in conjunctive normal form .
train
false
25,275
def cachedir_index_del(minion_id, base=None): base = init_cachedir(base) index_file = os.path.join(base, 'index.p') lock_file(index_file) if os.path.exists(index_file): with salt.utils.fopen(index_file, 'r') as fh_: index = msgpack.load(fh_) else: return if (minion_id in index): del index[minion_id] wit...
[ "def", "cachedir_index_del", "(", "minion_id", ",", "base", "=", "None", ")", ":", "base", "=", "init_cachedir", "(", "base", ")", "index_file", "=", "os", ".", "path", ".", "join", "(", "base", ",", "'index.p'", ")", "lock_file", "(", "index_file", ")",...
delete an entry from the cachedir index .
train
false
25,276
def config(conf_path='/etc/rsyncd.conf'): ret = '' try: with salt.utils.fopen(conf_path, 'r') as fp_: for line in fp_: ret += line except IOError as exc: if (exc.errno == errno.ENOENT): raise CommandExecutionError('{0} does not exist'.format(conf_path)) elif (exc.errno == errno.EACCES): raise Comm...
[ "def", "config", "(", "conf_path", "=", "'/etc/rsyncd.conf'", ")", ":", "ret", "=", "''", "try", ":", "with", "salt", ".", "utils", ".", "fopen", "(", "conf_path", ",", "'r'", ")", "as", "fp_", ":", "for", "line", "in", "fp_", ":", "ret", "+=", "li...
set traffic server configuration variable values .
train
true
25,277
def _createPluginDummy(entrypath, pluginContent, real, pluginModule): entrypath.createDirectory() pkg = entrypath.child('plugindummy') pkg.createDirectory() if real: pkg.child('__init__.py').setContent('') plugs = pkg.child('plugins') plugs.createDirectory() if real: plugs.child('__init__.py').setContent(plu...
[ "def", "_createPluginDummy", "(", "entrypath", ",", "pluginContent", ",", "real", ",", "pluginModule", ")", ":", "entrypath", ".", "createDirectory", "(", ")", "pkg", "=", "entrypath", ".", "child", "(", "'plugindummy'", ")", "pkg", ".", "createDirectory", "("...
create a plugindummy package .
train
false
25,278
def one(method): def loop(method, self, *args, **kwargs): result = [method(rec, *args, **kwargs) for rec in self] return aggregate(method, result, self) wrapper = decorator(loop, method) wrapper._api = 'one' return wrapper
[ "def", "one", "(", "method", ")", ":", "def", "loop", "(", "method", ",", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "result", "=", "[", "method", "(", "rec", ",", "*", "args", ",", "**", "kwargs", ")", "for", "rec", "in", "self",...
one returns a single game matching the given criteria .
train
false
25,279
def contains_exact_files(directory, expected_files, ignore_links=False): return (sorted(expected_files) == sorted(exact_files(directory, ignore_links=ignore_links)))
[ "def", "contains_exact_files", "(", "directory", ",", "expected_files", ",", "ignore_links", "=", "False", ")", ":", "return", "(", "sorted", "(", "expected_files", ")", "==", "sorted", "(", "exact_files", "(", "directory", ",", "ignore_links", "=", "ignore_link...
check if the only files which directory contains are expected_files .
train
false