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
19,828
def select(rlist, wlist, xlist, timeout=None): allevents = [] timeout = Timeout.start_new(timeout) result = SelectResult() try: try: for readfd in rlist: allevents.append(core.read_event(get_fileno(readfd), result.update, arg=readfd)) for writefd in wlist: allevents.append(core.write_event(get_fileno(writefd), result.update, arg=writefd)) except IOError as ex: raise error(*ex.args) result.event.wait(timeout=timeout) return (result.read, result.write, []) finally: for evt in allevents: evt.cancel() timeout.cancel()
[ "def", "select", "(", "rlist", ",", "wlist", ",", "xlist", ",", "timeout", "=", "None", ")", ":", "allevents", "=", "[", "]", "timeout", "=", "Timeout", ".", "start_new", "(", "timeout", ")", "result", "=", "SelectResult", "(", ")", "try", ":", "try"...
returns the ith order statistic in array a in linear time .
train
false
19,829
def _rescale_data(X, y, sample_weight): n_samples = X.shape[0] sample_weight = (sample_weight * np.ones(n_samples)) sample_weight = np.sqrt(sample_weight) sw_matrix = sparse.dia_matrix((sample_weight, 0), shape=(n_samples, n_samples)) X = safe_sparse_dot(sw_matrix, X) y = safe_sparse_dot(sw_matrix, y) return (X, y)
[ "def", "_rescale_data", "(", "X", ",", "y", ",", "sample_weight", ")", ":", "n_samples", "=", "X", ".", "shape", "[", "0", "]", "sample_weight", "=", "(", "sample_weight", "*", "np", ".", "ones", "(", "n_samples", ")", ")", "sample_weight", "=", "np", ...
rescale data so as to support sample_weight .
train
false
19,830
def copy_files_to(address, client, username, password, port, local_path, remote_path, limit='', log_filename=None, verbose=False, timeout=600, interface=None): if (client == 'scp'): scp_to_remote(address, port, username, password, local_path, remote_path, limit, log_filename, timeout, interface=interface) elif (client == 'rss'): log_func = None if verbose: log_func = logging.debug c = rss_client.FileUploadClient(address, port, log_func) c.upload(local_path, remote_path, timeout) c.close()
[ "def", "copy_files_to", "(", "address", ",", "client", ",", "username", ",", "password", ",", "port", ",", "local_path", ",", "remote_path", ",", "limit", "=", "''", ",", "log_filename", "=", "None", ",", "verbose", "=", "False", ",", "timeout", "=", "60...
copy files to a remote host using the selected client .
train
false
19,832
def make_dir_obsolete(directory): p = directory.parent if ((p is not None) and (p.child_dirs.filter(obsolete=False).count() == 1)): make_dir_obsolete(p) directory.obsolete = True directory.save()
[ "def", "make_dir_obsolete", "(", "directory", ")", ":", "p", "=", "directory", ".", "parent", "if", "(", "(", "p", "is", "not", "None", ")", "and", "(", "p", ".", "child_dirs", ".", "filter", "(", "obsolete", "=", "False", ")", ".", "count", "(", "...
make directory and its parents obsolete if a parent contains one empty directory only .
train
false
19,833
def test_undefined_function(caplog): with caplog.at_level(logging.ERROR): data = jinja.render('undef.html') assert ('There was an error while rendering undef.html' in data) assert ("'does_not_exist' is undefined" in data) assert data.startswith('<!DOCTYPE html>') assert (len(caplog.records) == 1) assert (caplog.records[0].msg == 'UndefinedError while rendering undef.html')
[ "def", "test_undefined_function", "(", "caplog", ")", ":", "with", "caplog", ".", "at_level", "(", "logging", ".", "ERROR", ")", ":", "data", "=", "jinja", ".", "render", "(", "'undef.html'", ")", "assert", "(", "'There was an error while rendering undef.html'", ...
make sure we dont crash if an undefined function is called .
train
false
19,836
def detect_logos(path): vision_client = vision.Client() with io.open(path, 'rb') as image_file: content = image_file.read() image = vision_client.image(content=content) logos = image.detect_logos() print 'Logos:' for logo in logos: print logo.description
[ "def", "detect_logos", "(", "path", ")", ":", "vision_client", "=", "vision", ".", "Client", "(", ")", "with", "io", ".", "open", "(", "path", ",", "'rb'", ")", "as", "image_file", ":", "content", "=", "image_file", ".", "read", "(", ")", "image", "=...
detects logos in the file .
train
false
19,838
def check_bcs_lengths(header, mapping_data, warnings): len_counts = defaultdict(int) header_field_to_check = 'BarcodeSequence' try: check_ix = header.index(header_field_to_check) except ValueError: return warnings for curr_data in range(len(mapping_data)): len_counts[len(mapping_data[curr_data][check_ix])] += 1 expected_bc_len = max(len_counts.iteritems(), key=itemgetter(1))[0] correction_ix = 1 for curr_data in range(len(mapping_data)): if (len(mapping_data[curr_data][check_ix]) != expected_bc_len): warnings.append(('Barcode %s differs than length %d DCTB %d,%d' % (mapping_data[curr_data][check_ix], expected_bc_len, (curr_data + correction_ix), check_ix))) return warnings
[ "def", "check_bcs_lengths", "(", "header", ",", "mapping_data", ",", "warnings", ")", ":", "len_counts", "=", "defaultdict", "(", "int", ")", "header_field_to_check", "=", "'BarcodeSequence'", "try", ":", "check_ix", "=", "header", ".", "index", "(", "header_fie...
adds warnings if barcodes have different lengths as this is mostly intended to find typos in barcodes .
train
false
19,840
def sum_layout_dimensions(dimensions): min = sum([d.min for d in dimensions if (d.min is not None)]) max = sum([d.max for d in dimensions if (d.max is not None)]) preferred = sum([d.preferred for d in dimensions]) return LayoutDimension(min=min, max=max, preferred=preferred)
[ "def", "sum_layout_dimensions", "(", "dimensions", ")", ":", "min", "=", "sum", "(", "[", "d", ".", "min", "for", "d", "in", "dimensions", "if", "(", "d", ".", "min", "is", "not", "None", ")", "]", ")", "max", "=", "sum", "(", "[", "d", ".", "m...
sum a list of :class: .
train
true
19,841
def _adapt_smtp_secure(value): if isinstance(value, basestring): return (value,) if isinstance(value, config.Config): assert (set(value.keys()) <= set(['keyfile', 'certfile'])) return (value.keyfile, value.certfile) if value: return ()
[ "def", "_adapt_smtp_secure", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "basestring", ")", ":", "return", "(", "value", ",", ")", "if", "isinstance", "(", "value", ",", "config", ".", "Config", ")", ":", "assert", "(", "set", "(", ...
adapt the value to arguments of smtp .
train
false
19,843
def test_entity_id(): schema = vol.Schema(cv.entity_id) with pytest.raises(vol.MultipleInvalid): schema('invalid_entity') assert (schema('sensor.LIGHT') == 'sensor.light')
[ "def", "test_entity_id", "(", ")", ":", "schema", "=", "vol", ".", "Schema", "(", "cv", ".", "entity_id", ")", "with", "pytest", ".", "raises", "(", "vol", ".", "MultipleInvalid", ")", ":", "schema", "(", "'invalid_entity'", ")", "assert", "(", "schema",...
test entity id validation .
train
false
19,844
def texture_image(canvas, texture): if canvas.hasAlphaChannel(): canvas = blend_image(canvas) return imageops.texture_image(canvas, texture)
[ "def", "texture_image", "(", "canvas", ",", "texture", ")", ":", "if", "canvas", ".", "hasAlphaChannel", "(", ")", ":", "canvas", "=", "blend_image", "(", "canvas", ")", "return", "imageops", ".", "texture_image", "(", "canvas", ",", "texture", ")" ]
repeatedly tile the image texture across and down the image canvas .
train
false
19,845
def _read_ssh_ed25519_pubkey(keydata): if (type(keydata) != six.text_type): raise Exception('invalid type {} for keydata'.format(type(keydata))) parts = keydata.strip().split() if (len(parts) != 3): raise Exception('invalid SSH Ed25519 public key') (algo, keydata, comment) = parts if (algo != u'ssh-ed25519'): raise Exception('not a Ed25519 SSH public key (but {})'.format(algo)) blob = binascii.a2b_base64(keydata) try: key = _unpack(blob)[1] except Exception as e: raise Exception('could not parse key ({})'.format(e)) if (len(key) != 32): raise Exception('invalid length {} for embedded raw key (must be 32 bytes)'.format(len(key))) return (key, comment)
[ "def", "_read_ssh_ed25519_pubkey", "(", "keydata", ")", ":", "if", "(", "type", "(", "keydata", ")", "!=", "six", ".", "text_type", ")", ":", "raise", "Exception", "(", "'invalid type {} for keydata'", ".", "format", "(", "type", "(", "keydata", ")", ")", ...
parse an openssh ed25519 public key from a string into a raw public key .
train
false
19,846
def sysprint(command): print_debug(('command: %s' % command)) output = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT) for line in output.splitlines(): if line.endswith('command not found'): raise NotFound(output) elif (line == 'Warning: Using a password on the command line interface can be insecure.'): pass else: print line
[ "def", "sysprint", "(", "command", ")", ":", "print_debug", "(", "(", "'command: %s'", "%", "command", ")", ")", "output", "=", "subprocess", ".", "check_output", "(", "command", ",", "shell", "=", "True", ",", "stderr", "=", "subprocess", ".", "STDOUT", ...
helper to print all system commands in debug mode .
train
false
19,847
def ErrorDocuments(app, global_conf, mapper, **kw): if (global_conf is None): global_conf = {} return RecursiveMiddleware(StatusBasedForward(app, global_conf=global_conf, mapper=mapper, **kw))
[ "def", "ErrorDocuments", "(", "app", ",", "global_conf", ",", "mapper", ",", "**", "kw", ")", ":", "if", "(", "global_conf", "is", "None", ")", ":", "global_conf", "=", "{", "}", "return", "RecursiveMiddleware", "(", "StatusBasedForward", "(", "app", ",", ...
wraps the app in error docs using paste recursivemiddleware and errordocumentsmiddleware .
train
false
19,849
def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile))
[ "def", "nat_gateway_exists", "(", "nat_gateway_id", "=", "None", ",", "subnet_id", "=", "None", ",", "subnet_name", "=", "None", ",", "vpc_id", "=", "None", ",", "vpc_name", "=", "None", ",", "states", "=", "(", "'pending'", ",", "'available'", ")", ",", ...
checks if a nat gateway exists .
train
true
19,851
def improve_memory_error_message(error, msg=''): assert isinstance(error, MemoryError) if str(error): raise error else: raise TypicalMemoryError(msg)
[ "def", "improve_memory_error_message", "(", "error", ",", "msg", "=", "''", ")", ":", "assert", "isinstance", "(", "error", ",", "MemoryError", ")", "if", "str", "(", "error", ")", ":", "raise", "error", "else", ":", "raise", "TypicalMemoryError", "(", "ms...
raises a typicalmemoryerror if the memoryerror has no messages parameters error: memoryerror an instance of memoryerror msg: string a message explaining what possibly happened .
train
false
19,853
def get_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:sns:'): return name account_id = __salt__['boto_iam.get_account_id'](region=region, key=key, keyid=keyid, profile=profile) return 'arn:aws:sns:{0}:{1}:{2}'.format(_get_region(region, profile), account_id, name)
[ "def", "get_arn", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "if", "name", ".", "startswith", "(", "'arn:aws:sns:'", ")", ":", "return", "name", "account_id", "=...
returns the full arn for a given topic name .
train
true
19,854
def test_can_get_sentence_from_string(): step = Step.from_string(I_HAVE_TASTY_BEVERAGES) assert isinstance(step, Step) assert_equals(step.sentence, string.split(I_HAVE_TASTY_BEVERAGES, '\n')[0])
[ "def", "test_can_get_sentence_from_string", "(", ")", ":", "step", "=", "Step", ".", "from_string", "(", "I_HAVE_TASTY_BEVERAGES", ")", "assert", "isinstance", "(", "step", ",", "Step", ")", "assert_equals", "(", "step", ".", "sentence", ",", "string", ".", "s...
it should extract the sentence string from the whole step .
train
false
19,855
def add_dicts(*args): counters = [Counter(arg) for arg in args] return dict(reduce(operator.add, counters))
[ "def", "add_dicts", "(", "*", "args", ")", ":", "counters", "=", "[", "Counter", "(", "arg", ")", "for", "arg", "in", "args", "]", "return", "dict", "(", "reduce", "(", "operator", ".", "add", ",", "counters", ")", ")" ]
adds two or more dicts together .
train
true
19,856
def ShiftedGompertz(name, b, eta): return rv(name, ShiftedGompertzDistribution, (b, eta))
[ "def", "ShiftedGompertz", "(", "name", ",", "b", ",", "eta", ")", ":", "return", "rv", "(", "name", ",", "ShiftedGompertzDistribution", ",", "(", "b", ",", "eta", ")", ")" ]
create a continuous random variable with a shifted gompertz distribution .
train
false
19,857
@pytest.mark.django_db def test_linkcolumn_non_field_based(): class Table(tables.Table, ): first_name = tables.Column() delete_link = tables.LinkColumn(u'person_delete', text=u'delete', kwargs={u'pk': tables.A(u'id')}) willem = Person.objects.create(first_name=u'Willem', last_name=u'Wever') html = Table(Person.objects.all()).as_html(build_request()) expected = u'<td class="delete_link"><a href="{}">delete</a></td>'.format(reverse(u'person_delete', kwargs={u'pk': willem.pk})) assert (expected in html)
[ "@", "pytest", ".", "mark", ".", "django_db", "def", "test_linkcolumn_non_field_based", "(", ")", ":", "class", "Table", "(", "tables", ".", "Table", ",", ")", ":", "first_name", "=", "tables", ".", "Column", "(", ")", "delete_link", "=", "tables", ".", ...
test for issue 257 .
train
false
19,858
def get_master_event(opts, sock_dir, listen=True, io_loop=None, raise_errors=False): if (opts['transport'] in ('zeromq', 'tcp', 'detect')): return MasterEvent(sock_dir, opts, listen=listen, io_loop=io_loop, raise_errors=raise_errors) elif (opts['transport'] == 'raet'): import salt.utils.raetevent return salt.utils.raetevent.MasterEvent(opts=opts, sock_dir=sock_dir, listen=listen)
[ "def", "get_master_event", "(", "opts", ",", "sock_dir", ",", "listen", "=", "True", ",", "io_loop", "=", "None", ",", "raise_errors", "=", "False", ")", ":", "if", "(", "opts", "[", "'transport'", "]", "in", "(", "'zeromq'", ",", "'tcp'", ",", "'detec...
return an event object suitable for the named transport .
train
false
19,860
def make_executable(script_path): status = os.stat(script_path) os.chmod(script_path, (status.st_mode | stat.S_IEXEC))
[ "def", "make_executable", "(", "script_path", ")", ":", "status", "=", "os", ".", "stat", "(", "script_path", ")", "os", ".", "chmod", "(", "script_path", ",", "(", "status", ".", "st_mode", "|", "stat", ".", "S_IEXEC", ")", ")" ]
makes script_path executable .
train
true
19,861
def _CalculateWritesForCompositeIndex(index, unique_old_properties, unique_new_properties, common_properties): old_count = 1 new_count = 1 common_count = 1 for prop in index.property_list(): old_count *= len(unique_old_properties[prop.name()]) new_count *= len(unique_new_properties[prop.name()]) common_count *= common_properties[prop.name()] return ((old_count - common_count) + (new_count - common_count))
[ "def", "_CalculateWritesForCompositeIndex", "(", "index", ",", "unique_old_properties", ",", "unique_new_properties", ",", "common_properties", ")", ":", "old_count", "=", "1", "new_count", "=", "1", "common_count", "=", "1", "for", "prop", "in", "index", ".", "pr...
calculate the number of writes required to maintain a specific index .
train
false
19,863
def get_internaldate(date, received): if (date is None): (other, date) = received.split(';') parsed_date = parsedate_tz(date) timestamp = mktime_tz(parsed_date) dt = datetime.utcfromtimestamp(timestamp) return dt
[ "def", "get_internaldate", "(", "date", ",", "received", ")", ":", "if", "(", "date", "is", "None", ")", ":", "(", "other", ",", "date", ")", "=", "received", ".", "split", "(", "';'", ")", "parsed_date", "=", "parsedate_tz", "(", "date", ")", "times...
get the date from the headers .
train
false
19,864
def getVersionFileName(): return getFabmetheusUtilitiesPath('version.txt')
[ "def", "getVersionFileName", "(", ")", ":", "return", "getFabmetheusUtilitiesPath", "(", "'version.txt'", ")" ]
get the file name of the version date .
train
false
19,865
def full_scorers_processors(): scorers = [fuzz.ratio] processors = [(lambda x: x), partial(utils.full_process, force_ascii=False), partial(utils.full_process, force_ascii=True)] splist = list(product(scorers, processors)) splist.extend([(fuzz.WRatio, partial(utils.full_process, force_ascii=True)), (fuzz.QRatio, partial(utils.full_process, force_ascii=True)), (fuzz.UWRatio, partial(utils.full_process, force_ascii=False)), (fuzz.UQRatio, partial(utils.full_process, force_ascii=False))]) return splist
[ "def", "full_scorers_processors", "(", ")", ":", "scorers", "=", "[", "fuzz", ".", "ratio", "]", "processors", "=", "[", "(", "lambda", "x", ":", "x", ")", ",", "partial", "(", "utils", ".", "full_process", ",", "force_ascii", "=", "False", ")", ",", ...
generate a list of pairs for testing for scorers that use the full string only :return: [ .
train
false
19,868
def monkeypatch_django(): from django.contrib.staticfiles.management.commands.runserver import Command as StaticRunserverCommand from .management.commands.runserver import Command as RunserverCommand StaticRunserverCommand.__bases__ = (RunserverCommand,)
[ "def", "monkeypatch_django", "(", ")", ":", "from", "django", ".", "contrib", ".", "staticfiles", ".", "management", ".", "commands", ".", "runserver", "import", "Command", "as", "StaticRunserverCommand", "from", ".", "management", ".", "commands", ".", "runserv...
monkeypatches support for us into parts of django .
train
false
19,871
def aitchison_aitken_reg(h, Xi, x): kernel_value = np.ones(Xi.size) ix = (Xi != x) inDom = (ix * h) kernel_value[ix] = inDom[ix] return kernel_value
[ "def", "aitchison_aitken_reg", "(", "h", ",", "Xi", ",", "x", ")", ":", "kernel_value", "=", "np", ".", "ones", "(", "Xi", ".", "size", ")", "ix", "=", "(", "Xi", "!=", "x", ")", "inDom", "=", "(", "ix", "*", "h", ")", "kernel_value", "[", "ix"...
a version for the aitchison-aitken kernel for nonparametric regression .
train
false
19,872
@testing.requires_testing_data def test_read_source_spaces(): src = read_source_spaces(fname, patch_stats=True) lh_points = src[0]['rr'] lh_faces = src[0]['tris'] lh_use_faces = src[0]['use_tris'] rh_points = src[1]['rr'] rh_faces = src[1]['tris'] rh_use_faces = src[1]['use_tris'] assert_true((lh_faces.min() == 0)) assert_true((lh_faces.max() == (lh_points.shape[0] - 1))) assert_true((lh_use_faces.min() >= 0)) assert_true((lh_use_faces.max() <= (lh_points.shape[0] - 1))) assert_true((rh_faces.min() == 0)) assert_true((rh_faces.max() == (rh_points.shape[0] - 1))) assert_true((rh_use_faces.min() >= 0)) assert_true((rh_use_faces.max() <= (rh_points.shape[0] - 1)))
[ "@", "testing", ".", "requires_testing_data", "def", "test_read_source_spaces", "(", ")", ":", "src", "=", "read_source_spaces", "(", "fname", ",", "patch_stats", "=", "True", ")", "lh_points", "=", "src", "[", "0", "]", "[", "'rr'", "]", "lh_faces", "=", ...
test reading of source space meshes .
train
false
19,874
def _unicode_output(cursor, name, default_type, size, precision, scale): if (default_type in (cx_Oracle.STRING, cx_Oracle.LONG_STRING, cx_Oracle.FIXED_CHAR, cx_Oracle.CLOB)): return cursor.var(six.text_type, size, cursor.arraysize)
[ "def", "_unicode_output", "(", "cursor", ",", "name", ",", "default_type", ",", "size", ",", "precision", ",", "scale", ")", ":", "if", "(", "default_type", "in", "(", "cx_Oracle", ".", "STRING", ",", "cx_Oracle", ".", "LONG_STRING", ",", "cx_Oracle", ".",...
return strings values as python unicode string URL .
train
true
19,875
def _loop_lift_modify_blocks(func_ir, loopinfo, blocks, typingctx, targetctx, flags, locals): from numba.dispatcher import LiftedLoop loop = loopinfo.loop loopblockkeys = ((set(loop.body) | set(loop.entries)) | set(loop.exits)) loopblocks = dict(((k, blocks[k].copy()) for k in loopblockkeys)) _loop_lift_prepare_loop_func(loopinfo, loopblocks) lifted_ir = func_ir.derive(blocks=loopblocks, arg_names=tuple(loopinfo.inputs), arg_count=len(loopinfo.inputs), force_non_generator=True) liftedloop = LiftedLoop(lifted_ir, typingctx, targetctx, flags, locals) callblock = _loop_lift_modify_call_block(liftedloop, blocks[loopinfo.callfrom], loopinfo.inputs, loopinfo.outputs, loopinfo.returnto) for k in loopblockkeys: del blocks[k] blocks[loopinfo.callfrom] = callblock return liftedloop
[ "def", "_loop_lift_modify_blocks", "(", "func_ir", ",", "loopinfo", ",", "blocks", ",", "typingctx", ",", "targetctx", ",", "flags", ",", "locals", ")", ":", "from", "numba", ".", "dispatcher", "import", "LiftedLoop", "loop", "=", "loopinfo", ".", "loop", "l...
modify the block inplace to call to the lifted-loop .
train
false
19,876
def print_inventory(a_device): fields = ['device_name', 'ip_address', 'device_class', 'ssh_port', 'api_port', 'vendor', 'model', 'device_type', 'os_version', 'serial_number', 'uptime_seconds'] print print ('#' * 80) for a_field in fields: value = getattr(a_device, a_field) print '{:>15s}: {:<65s}'.format(a_field, str(value)) print ('#' * 80) print
[ "def", "print_inventory", "(", "a_device", ")", ":", "fields", "=", "[", "'device_name'", ",", "'ip_address'", ",", "'device_class'", ",", "'ssh_port'", ",", "'api_port'", ",", "'vendor'", ",", "'model'", ",", "'device_type'", ",", "'os_version'", ",", "'serial_...
print network device inventory information .
train
false
19,877
def sentMessage(ignored, group, avatar): l = group.leave() l.addCallback(leftGroup, avatar) return l
[ "def", "sentMessage", "(", "ignored", ",", "group", ",", "avatar", ")", ":", "l", "=", "group", ".", "leave", "(", ")", "l", ".", "addCallback", "(", "leftGroup", ",", "avatar", ")", "return", "l" ]
sent the message successfully .
train
false
19,878
def revdep_rebuild(lib=None): cmd = 'revdep-rebuild -i --quiet --no-progress' if (lib is not None): cmd += ' --library={0}'.format(lib) return (__salt__['cmd.retcode'](cmd, python_shell=False) == 0)
[ "def", "revdep_rebuild", "(", "lib", "=", "None", ")", ":", "cmd", "=", "'revdep-rebuild -i --quiet --no-progress'", "if", "(", "lib", "is", "not", "None", ")", ":", "cmd", "+=", "' --library={0}'", ".", "format", "(", "lib", ")", "return", "(", "__salt__", ...
fix up broken reverse dependencies lib search for reverse dependencies for a particular library rather than every library on the system .
train
true
19,879
@Profiler.profile def test_orm_flush(n): session = Session(bind=engine) for chunk in range(0, n, 1000): customers = session.query(Customer).filter(Customer.id.between(chunk, (chunk + 1000))).all() for customer in customers: customer.description += 'updated' session.flush() session.commit()
[ "@", "Profiler", ".", "profile", "def", "test_orm_flush", "(", "n", ")", ":", "session", "=", "Session", "(", "bind", "=", "engine", ")", "for", "chunk", "in", "range", "(", "0", ",", "n", ",", "1000", ")", ":", "customers", "=", "session", ".", "q...
update statements via the orm flush process .
train
false
19,880
def to_255(vals_01): try: ret = [(v * 255) for v in vals_01] if (type(vals_01) is tuple): return tuple(ret) else: return ret except TypeError: return (vals_01 * 255)
[ "def", "to_255", "(", "vals_01", ")", ":", "try", ":", "ret", "=", "[", "(", "v", "*", "255", ")", "for", "v", "in", "vals_01", "]", "if", "(", "type", "(", "vals_01", ")", "is", "tuple", ")", ":", "return", "tuple", "(", "ret", ")", "else", ...
convert vals in [0 .
train
false
19,881
def getNewRepository(): return ExportRepository()
[ "def", "getNewRepository", "(", ")", ":", "return", "ExportRepository", "(", ")" ]
get the repository constructor .
train
false
19,882
def DeleteEntity(key): if (key.kind() in MAPREDUCE_OBJECTS): entity = datastore.Get(key) if (entity and (not entity['active'])): (yield operation.db.Delete(key)) elif (key.kind() == utils.DatastoreAdminOperation.kind()): entity = datastore.Get(key) if (entity and (not entity['active_jobs'])): (yield operation.db.Delete(key)) else: (yield operation.db.Delete(key))
[ "def", "DeleteEntity", "(", "key", ")", ":", "if", "(", "key", ".", "kind", "(", ")", "in", "MAPREDUCE_OBJECTS", ")", ":", "entity", "=", "datastore", ".", "Get", "(", "key", ")", "if", "(", "entity", "and", "(", "not", "entity", "[", "'active'", "...
delete function which deletes all processed entities .
train
false
19,883
def map_subproject_slug(view_func): @wraps(view_func) def inner_view(request, subproject=None, subproject_slug=None, *args, **kwargs): if ((subproject is None) and subproject_slug): try: subproject = Project.objects.get(slug=subproject_slug) except Project.DoesNotExist: try: rel = ProjectRelationship.objects.get(parent=kwargs['project'], alias=subproject_slug) subproject = rel.child except (ProjectRelationship.DoesNotExist, KeyError): raise Http404 return view_func(request, subproject=subproject, *args, **kwargs) return inner_view
[ "def", "map_subproject_slug", "(", "view_func", ")", ":", "@", "wraps", "(", "view_func", ")", "def", "inner_view", "(", "request", ",", "subproject", "=", "None", ",", "subproject_slug", "=", "None", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if"...
a decorator that maps a subproject_slug url param into a project .
train
false
19,884
def is_opentype_cff_font(filename): if (os.path.splitext(filename)[1].lower() == u'.otf'): result = _is_opentype_cff_font_cache.get(filename) if (result is None): with open(filename, u'rb') as fd: tag = fd.read(4) result = (tag == 'OTTO') _is_opentype_cff_font_cache[filename] = result return result return False
[ "def", "is_opentype_cff_font", "(", "filename", ")", ":", "if", "(", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", ".", "lower", "(", ")", "==", "u'.otf'", ")", ":", "result", "=", "_is_opentype_cff_font_cache", ".", "get", "...
returns true if the given font is a postscript compact font format font embedded in an opentype wrapper .
train
false
19,885
def get_distribution(dist): if isinstance(dist, basestring): dist = Requirement.parse(dist) if isinstance(dist, Requirement): dist = get_provider(dist) if (not isinstance(dist, Distribution)): raise TypeError('Expected string, Requirement, or Distribution', dist) return dist
[ "def", "get_distribution", "(", "dist", ")", ":", "if", "isinstance", "(", "dist", ",", "basestring", ")", ":", "dist", "=", "Requirement", ".", "parse", "(", "dist", ")", "if", "isinstance", "(", "dist", ",", "Requirement", ")", ":", "dist", "=", "get...
return a current distribution object for a requirement or string .
train
false
19,887
def get_git_name(repository_dir, git_dir): if git_dir.startswith(repository_dir): git_name = git_dir[len(repository_dir):] else: git_name = os.path.split(git_dir)[1] git_name = git_name.strip('\\/') if git_name.endswith('.git'): git_name = git_name[:(-4)] return git_name
[ "def", "get_git_name", "(", "repository_dir", ",", "git_dir", ")", ":", "if", "git_dir", ".", "startswith", "(", "repository_dir", ")", ":", "git_name", "=", "git_dir", "[", "len", "(", "repository_dir", ")", ":", "]", "else", ":", "git_name", "=", "os", ...
guess the name of the repository used in gitosis .
train
false
19,889
def _object_matcher(obj): if isinstance(obj, TreeElement): return _identity_matcher(obj) if isinstance(obj, type): return _class_matcher(obj) if isinstance(obj, basestring): return _string_matcher(obj) if isinstance(obj, dict): return _attribute_matcher(obj) if callable(obj): return _function_matcher(obj) raise ValueError(('%s (type %s) is not a valid type for comparison.' % (obj, type(obj))))
[ "def", "_object_matcher", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "TreeElement", ")", ":", "return", "_identity_matcher", "(", "obj", ")", "if", "isinstance", "(", "obj", ",", "type", ")", ":", "return", "_class_matcher", "(", "obj", "...
retrieve a matcher function by passing an arbitrary object .
train
false
19,892
def iter_default_settings(): for name in dir(default_settings): if name.isupper(): (yield (name, getattr(default_settings, name)))
[ "def", "iter_default_settings", "(", ")", ":", "for", "name", "in", "dir", "(", "default_settings", ")", ":", "if", "name", ".", "isupper", "(", ")", ":", "(", "yield", "(", "name", ",", "getattr", "(", "default_settings", ",", "name", ")", ")", ")" ]
return the default settings as an iterator of tuples .
train
false
19,894
def cast_bytes(s, encoding='utf8', errors='strict'): if isinstance(s, bytes): return s elif isinstance(s, unicode): return s.encode(encoding, errors) else: raise TypeError(('Expected unicode or bytes, got %r' % s))
[ "def", "cast_bytes", "(", "s", ",", "encoding", "=", "'utf8'", ",", "errors", "=", "'strict'", ")", ":", "if", "isinstance", "(", "s", ",", "bytes", ")", ":", "return", "s", "elif", "isinstance", "(", "s", ",", "unicode", ")", ":", "return", "s", "...
cast unicode or bytes to bytes .
train
true
19,895
def getVector3ByDictionaryListValue(value, vector3): if ((value.__class__ == Vector3) or (value.__class__.__name__ == 'Vector3Index')): return value if (value.__class__ == dict): return getVector3ByDictionary(value, vector3) if (value.__class__ == list): return getVector3ByFloatList(value, vector3) floatFromValue = euclidean.getFloatFromValue(value) if (floatFromValue == None): return vector3 vector3.setToXYZ(floatFromValue, floatFromValue, floatFromValue) return vector3
[ "def", "getVector3ByDictionaryListValue", "(", "value", ",", "vector3", ")", ":", "if", "(", "(", "value", ".", "__class__", "==", "Vector3", ")", "or", "(", "value", ".", "__class__", ".", "__name__", "==", "'Vector3Index'", ")", ")", ":", "return", "valu...
get vector3 by dictionary .
train
false
19,896
def test_batch_normalized_mlp_learn_scale_propagated_at_alloc(): mlp = BatchNormalizedMLP([Tanh(), Tanh()], [5, 7, 9], learn_scale=False) assert (not mlp.learn_scale) assert all((act.children[0].learn_scale for act in mlp.activations)) mlp.allocate() assert (not any((act.children[0].learn_scale for act in mlp.activations)))
[ "def", "test_batch_normalized_mlp_learn_scale_propagated_at_alloc", "(", ")", ":", "mlp", "=", "BatchNormalizedMLP", "(", "[", "Tanh", "(", ")", ",", "Tanh", "(", ")", "]", ",", "[", "5", ",", "7", ",", "9", "]", ",", "learn_scale", "=", "False", ")", "a...
test that setting learn_scale on a batchnormalizedmlp works .
train
false
19,897
def batchScoreIAT(path='.', write_file=False): files = glob.glob(os.path.join(path, '*.csv')) for f in files: scoreIAT(f, write_file=write_file)
[ "def", "batchScoreIAT", "(", "path", "=", "'.'", ",", "write_file", "=", "False", ")", ":", "files", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'*.csv'", ")", ")", "for", "f", "in", "files", ":", "scoreIAT", ...
call scoreiat() on all csv files in path .
train
false
19,898
def __grant_generate(grant, database, user, host='localhost', grant_option=False, escape=True, ssl_option=False): grant = re.sub('\\s*,\\s*', ', ', grant).upper() grant = __grant_normalize(grant) db_part = database.rpartition('.') dbc = db_part[0] table = db_part[2] if escape: if (dbc is not '*'): dbc = quote_identifier(dbc, for_grants=(table is '*')) if (table is not '*'): table = quote_identifier(table) qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table) args = {} args['user'] = user args['host'] = host if (isinstance(ssl_option, list) and len(ssl_option)): qry += __ssl_option_sanitize(ssl_option) if salt.utils.is_true(grant_option): qry += ' WITH GRANT OPTION' log.debug('Grant Query generated: {0} args {1}'.format(qry, repr(args))) return {'qry': qry, 'args': args}
[ "def", "__grant_generate", "(", "grant", ",", "database", ",", "user", ",", "host", "=", "'localhost'", ",", "grant_option", "=", "False", ",", "escape", "=", "True", ",", "ssl_option", "=", "False", ")", ":", "grant", "=", "re", ".", "sub", "(", "'\\\...
validate grants and build the query that could set the given grants note that this query contains arguments for user and host but not for grants or database .
train
true
19,899
def get_todays_events(as_list=False): from frappe.desk.doctype.event.event import get_events from frappe.utils import nowdate today = nowdate() events = get_events(today, today) return (events if as_list else len(events))
[ "def", "get_todays_events", "(", "as_list", "=", "False", ")", ":", "from", "frappe", ".", "desk", ".", "doctype", ".", "event", ".", "event", "import", "get_events", "from", "frappe", ".", "utils", "import", "nowdate", "today", "=", "nowdate", "(", ")", ...
returns a count of todays events in calendar .
train
false
19,900
def cmp_to_key(mycmp): class KeyClass(object, ): 'Key class' def __init__(self, obj, *args): self.obj = obj def __lt__(self, other): return (mycmp(self.obj, other.obj) < 0) def __gt__(self, other): return (mycmp(self.obj, other.obj) > 0) def __eq__(self, other): return (mycmp(self.obj, other.obj) == 0) def __le__(self, other): return (mycmp(self.obj, other.obj) <= 0) def __ge__(self, other): return (mycmp(self.obj, other.obj) >= 0) def __ne__(self, other): return (mycmp(self.obj, other.obj) != 0) return KeyClass
[ "def", "cmp_to_key", "(", "mycmp", ")", ":", "class", "KeyClass", "(", "object", ",", ")", ":", "def", "__init__", "(", "self", ",", "obj", ",", "*", "args", ")", ":", "self", ".", "obj", "=", "obj", "def", "__lt__", "(", "self", ",", "other", ")...
convert a cmp= function into a key= function .
train
false
19,901
def test_iforest_parallel_regression(): rng = check_random_state(0) (X_train, X_test, y_train, y_test) = train_test_split(boston.data, boston.target, random_state=rng) ensemble = IsolationForest(n_jobs=3, random_state=0).fit(X_train) ensemble.set_params(n_jobs=1) y1 = ensemble.predict(X_test) ensemble.set_params(n_jobs=2) y2 = ensemble.predict(X_test) assert_array_almost_equal(y1, y2) ensemble = IsolationForest(n_jobs=1, random_state=0).fit(X_train) y3 = ensemble.predict(X_test) assert_array_almost_equal(y1, y3)
[ "def", "test_iforest_parallel_regression", "(", ")", ":", "rng", "=", "check_random_state", "(", "0", ")", "(", "X_train", ",", "X_test", ",", "y_train", ",", "y_test", ")", "=", "train_test_split", "(", "boston", ".", "data", ",", "boston", ".", "target", ...
check parallel regression .
train
false
19,902
@testing.requires_testing_data def test_time_index(): raw_fname = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data', 'test_raw.fif') raw = read_raw_fif(raw_fname) orig_inds = raw.time_as_index(raw.times) assert (len(set(orig_inds)) != len(orig_inds)) new_inds = raw.time_as_index(raw.times, use_rounding=True) assert (len(set(new_inds)) == len(new_inds))
[ "@", "testing", ".", "requires_testing_data", "def", "test_time_index", "(", ")", ":", "raw_fname", "=", "op", ".", "join", "(", "op", ".", "dirname", "(", "__file__", ")", ",", "'..'", ",", "'..'", ",", "'io'", ",", "'tests'", ",", "'data'", ",", "'te...
test indexing of raw times .
train
false
19,906
def reverse_readline(fh, start_byte=0, buf_size=8192): segment = None offset = 0 if start_byte: fh.seek(start_byte) else: fh.seek(0, os.SEEK_END) total_size = remaining_size = fh.tell() while (remaining_size > 0): offset = min(total_size, (offset + buf_size)) fh.seek((- offset), os.SEEK_END) buf = fh.read(min(remaining_size, buf_size)) remaining_size -= buf_size lines = buf.decode(sys.getfilesystemencoding()).split(u'\n') if (segment is not None): if (buf[(-1)] is not u'\n'): lines[(-1)] += segment else: (yield segment) segment = lines[0] for index in range((len(lines) - 1), 0, (-1)): if len(lines[index]): (yield lines[index]) (yield segment)
[ "def", "reverse_readline", "(", "fh", ",", "start_byte", "=", "0", ",", "buf_size", "=", "8192", ")", ":", "segment", "=", "None", "offset", "=", "0", "if", "start_byte", ":", "fh", ".", "seek", "(", "start_byte", ")", "else", ":", "fh", ".", "seek",...
a generator that returns the lines of a file in reverse order .
train
false
19,909
def expireat(key, timestamp, host=None, port=None, db=None, password=None): server = _connect(host, port, db, password) return server.expireat(key, timestamp)
[ "def", "expireat", "(", "key", ",", "timestamp", ",", "host", "=", "None", ",", "port", "=", "None", ",", "db", "=", "None", ",", "password", "=", "None", ")", ":", "server", "=", "_connect", "(", "host", ",", "port", ",", "db", ",", "password", ...
set a keys expire at given unix time cli example: .
train
true
19,910
def logparser(registry, xml_parent, data): clog = XML.SubElement(xml_parent, 'hudson.plugins.logparser.LogParserPublisher') clog.set('plugin', 'log-parser') mappings = [('unstable-on-warning', 'unstableOnWarning', False), ('fail-on-error', 'failBuildOnError', False), ('parse-rules', 'parsingRulesPath', '')] helpers.convert_mapping_to_xml(clog, data, mappings, fail_required=True)
[ "def", "logparser", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "clog", "=", "XML", ".", "SubElement", "(", "xml_parent", ",", "'hudson.plugins.logparser.LogParserPublisher'", ")", "clog", ".", "set", "(", "'plugin'", ",", "'log-parser'", ")", "...
yaml: logparser requires the jenkins :jenkins-wiki:log parser plugin <log+parser+plugin> .
train
false
19,914
def has_known_categories(x): x = getattr(x, '_meta', x) if isinstance(x, pd.Series): return (UNKNOWN_CATEGORIES not in x.cat.categories) elif isinstance(x, pd.CategoricalIndex): return (UNKNOWN_CATEGORIES not in x.categories) raise TypeError('Expected Series or CategoricalIndex')
[ "def", "has_known_categories", "(", "x", ")", ":", "x", "=", "getattr", "(", "x", ",", "'_meta'", ",", "x", ")", "if", "isinstance", "(", "x", ",", "pd", ".", "Series", ")", ":", "return", "(", "UNKNOWN_CATEGORIES", "not", "in", "x", ".", "cat", "....
returns whether the categories in x are known .
train
false
19,915
def getNewRepository(): return ExportRepository()
[ "def", "getNewRepository", "(", ")", ":", "return", "ExportRepository", "(", ")" ]
get new repository .
train
false
19,916
def is_gentoo(): return os.path.exists('/etc/gentoo-release')
[ "def", "is_gentoo", "(", ")", ":", "return", "os", ".", "path", ".", "exists", "(", "'/etc/gentoo-release'", ")" ]
checks if were running on gentoo .
train
false
19,918
def getInsetPoint(loop, tinyRadius): pointIndex = getWideAnglePointIndex(loop) point = loop[(pointIndex % len(loop))] afterPoint = loop[((pointIndex + 1) % len(loop))] beforePoint = loop[((pointIndex - 1) % len(loop))] afterSegmentNormalized = euclidean.getNormalized((afterPoint - point)) beforeSegmentNormalized = euclidean.getNormalized((beforePoint - point)) afterClockwise = complex(afterSegmentNormalized.imag, (- afterSegmentNormalized.real)) beforeWiddershins = complex((- beforeSegmentNormalized.imag), beforeSegmentNormalized.real) midpoint = (afterClockwise + beforeWiddershins) midpointNormalized = (midpoint / abs(midpoint)) return (point + (midpointNormalized * tinyRadius))
[ "def", "getInsetPoint", "(", "loop", ",", "tinyRadius", ")", ":", "pointIndex", "=", "getWideAnglePointIndex", "(", "loop", ")", "point", "=", "loop", "[", "(", "pointIndex", "%", "len", "(", "loop", ")", ")", "]", "afterPoint", "=", "loop", "[", "(", ...
get the inset vertex .
train
false
19,921
def add_html_link(app, pagename, templatename, context, doctree): base_url = app.config['html_theme_options'].get('base_url', '') if base_url: app.sitemap_links.append(((base_url + pagename) + '.html'))
[ "def", "add_html_link", "(", "app", ",", "pagename", ",", "templatename", ",", "context", ",", "doctree", ")", ":", "base_url", "=", "app", ".", "config", "[", "'html_theme_options'", "]", ".", "get", "(", "'base_url'", ",", "''", ")", "if", "base_url", ...
as each page is built .
train
true
19,922
def check_params(module): if ((module.params.get('name') is None) and (module.params.get('id') is None)): module.fail_json(msg='"name" or "id" is required')
[ "def", "check_params", "(", "module", ")", ":", "if", "(", "(", "module", ".", "params", ".", "get", "(", "'name'", ")", "is", "None", ")", "and", "(", "module", ".", "params", ".", "get", "(", "'id'", ")", "is", "None", ")", ")", ":", "module", ...
most modules must have either name or id specified .
train
false
19,923
def build_discarder(registry, xml_parent, data): base_sub = XML.SubElement(xml_parent, 'jenkins.model.BuildDiscarderProperty') strategy = XML.SubElement(base_sub, 'strategy') strategy.set('class', 'hudson.tasks.LogRotator') mappings = [('days-to-keep', 'daysToKeep', (-1)), ('num-to-keep', 'numToKeep', (-1)), ('artifact-days-to-keep', 'artifactDaysToKeep', (-1)), ('artifact-num-to-keep', 'artifactNumToKeep', (-1))] helpers.convert_mapping_to_xml(strategy, data, mappings, fail_required=True)
[ "def", "build_discarder", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "base_sub", "=", "XML", ".", "SubElement", "(", "xml_parent", ",", "'jenkins.model.BuildDiscarderProperty'", ")", "strategy", "=", "XML", ".", "SubElement", "(", "base_sub", ","...
yaml: build-discarder :arg int days-to-keep: number of days to keep builds for :arg int num-to-keep: number of builds to keep :arg int artifact-days-to-keep: number of days to keep builds with artifacts :arg int artifact-num-to-keep: number of builds with artifacts to keep example: .
train
false
19,924
def _renew_by(name, window=None): expiry = _expires(name) if (window is not None): expiry = (expiry - datetime.timedelta(days=window)) return expiry
[ "def", "_renew_by", "(", "name", ",", "window", "=", "None", ")", ":", "expiry", "=", "_expires", "(", "name", ")", "if", "(", "window", "is", "not", "None", ")", ":", "expiry", "=", "(", "expiry", "-", "datetime", ".", "timedelta", "(", "days", "=...
date before a certificate should be renewed .
train
true
19,925
def from_text(textring): keyring = {} for keytext in textring: keyname = dns.name.from_text(keytext) secret = base64.decodestring(textring[keytext]) keyring[keyname] = secret return keyring
[ "def", "from_text", "(", "textring", ")", ":", "keyring", "=", "{", "}", "for", "keytext", "in", "textring", ":", "keyname", "=", "dns", ".", "name", ".", "from_text", "(", "keytext", ")", "secret", "=", "base64", ".", "decodestring", "(", "textring", ...
convert the text form of a ttl to an integer .
train
true
19,926
def _igam(a, x): ax = math.exp((((a * math.log(x)) - x) - math.lgamma(a))) r = a c = 1.0 ans = 1.0 while True: r += 1.0 c *= (x / r) ans += c if ((c / ans) <= MACHEP): return ((ans * ax) / a)
[ "def", "_igam", "(", "a", ",", "x", ")", ":", "ax", "=", "math", ".", "exp", "(", "(", "(", "(", "a", "*", "math", ".", "log", "(", "x", ")", ")", "-", "x", ")", "-", "math", ".", "lgamma", "(", "a", ")", ")", ")", "r", "=", "a", "c",...
left tail of incomplete gamma function .
train
true
19,927
def get_components(principal): if (not principal): return None return re.split('[\\/@]', str(principal))
[ "def", "get_components", "(", "principal", ")", ":", "if", "(", "not", "principal", ")", ":", "return", "None", "return", "re", ".", "split", "(", "'[\\\\/@]'", ",", "str", "(", "principal", ")", ")" ]
get_components -> (short name .
train
false
19,928
def stat(pid): with open(('/proc/%d/stat' % pid)) as fd: s = fd.read() i = s.find('(') j = s.rfind(')') name = s[(i + 1):j] return ((s[:i].split() + [name]) + s[(j + 1):].split())
[ "def", "stat", "(", "pid", ")", ":", "with", "open", "(", "(", "'/proc/%d/stat'", "%", "pid", ")", ")", "as", "fd", ":", "s", "=", "fd", ".", "read", "(", ")", "i", "=", "s", ".", "find", "(", "'('", ")", "j", "=", "s", ".", "rfind", "(", ...
get status of a finalized file given its full path filename .
train
false
19,929
def getNetworkOperatorName(): try: mContext = autoclass('android.content.Context') pythonActivity = autoclass('org.renpy.android.PythonService') telephonyManager = cast('android.telephony.TelephonyManager', pythonActivity.mService.getSystemService(mContext.TELEPHONY_SERVICE)) networkOperatorName = telephonyManager.getNetworkOperatorName() return networkOperatorName except Exception as e: return None
[ "def", "getNetworkOperatorName", "(", ")", ":", "try", ":", "mContext", "=", "autoclass", "(", "'android.content.Context'", ")", "pythonActivity", "=", "autoclass", "(", "'org.renpy.android.PythonService'", ")", "telephonyManager", "=", "cast", "(", "'android.telephony....
returns the alphabetic name of current registered operator returns none if an error .
train
false
19,930
def color_range(startcolor, goalcolor, steps): start_tuple = make_color_tuple(startcolor) goal_tuple = make_color_tuple(goalcolor) return interpolate_tuple(start_tuple, goal_tuple, steps)
[ "def", "color_range", "(", "startcolor", ",", "goalcolor", ",", "steps", ")", ":", "start_tuple", "=", "make_color_tuple", "(", "startcolor", ")", "goal_tuple", "=", "make_color_tuple", "(", "goalcolor", ")", "return", "interpolate_tuple", "(", "start_tuple", ",",...
wrapper for interpolate_tuple that accepts colors as html .
train
true
19,932
@public def assemble_partfrac_list(partial_list): common = partial_list[0] polypart = partial_list[1] pfd = polypart.as_expr() for (r, nf, df, ex) in partial_list[2]: if isinstance(r, Poly): (an, nu) = (nf.variables, nf.expr) (ad, de) = (df.variables, df.expr) de = de.subs(ad[0], an[0]) func = Lambda(an, (nu / (de ** ex))) pfd += RootSum(r, func, auto=False, quadratic=False) else: for root in r: pfd += (nf(root) / (df(root) ** ex)) return (common * pfd)
[ "@", "public", "def", "assemble_partfrac_list", "(", "partial_list", ")", ":", "common", "=", "partial_list", "[", "0", "]", "polypart", "=", "partial_list", "[", "1", "]", "pfd", "=", "polypart", ".", "as_expr", "(", ")", "for", "(", "r", ",", "nf", "...
reassemble a full partial fraction decomposition from a structured result obtained by the function apart_list .
train
false
19,933
@pytest.fixture(scope='module', params=['gpu', 'cpu']) def backend_default(request): be = get_backend(request) def cleanup(): be = request.getfuncargvalue('backend_default') del be request.addfinalizer(cleanup) return be
[ "@", "pytest", ".", "fixture", "(", "scope", "=", "'module'", ",", "params", "=", "[", "'gpu'", ",", "'cpu'", "]", ")", "def", "backend_default", "(", "request", ")", ":", "be", "=", "get_backend", "(", "request", ")", "def", "cleanup", "(", ")", ":"...
fixture to setup the backend before running a test .
train
false
19,936
def _safe_isinstance(obj, module, class_name): return ((module in sys.modules) and isinstance(obj, getattr(import_module(module), class_name)))
[ "def", "_safe_isinstance", "(", "obj", ",", "module", ",", "class_name", ")", ":", "return", "(", "(", "module", "in", "sys", ".", "modules", ")", "and", "isinstance", "(", "obj", ",", "getattr", "(", "import_module", "(", "module", ")", ",", "class_name...
checks if obj is an instance of module .
train
false
19,938
def islink(p): return _false
[ "def", "islink", "(", "p", ")", ":", "return", "_false" ]
test whether a path is a symbolic link .
train
false
19,939
def to_set(obj, encoder): return set(obj)
[ "def", "to_set", "(", "obj", ",", "encoder", ")", ":", "return", "set", "(", "obj", ")" ]
converts an arbitrary object c{obj} to a c{set} .
train
false
19,940
def is_valid_short_number_for_region(short_number, region_dialing_from): if isinstance(short_number, PhoneNumber): short_number = national_significant_number(short_number) metadata = PhoneMetadata.short_metadata_for_region(region_dialing_from) if (metadata is None): return False general_desc = metadata.general_desc if ((general_desc.national_number_pattern is None) or (not _is_number_matching_desc(short_number, general_desc))): return False short_number_desc = metadata.short_code if (short_number_desc.national_number_pattern is None): return False return _is_number_matching_desc(short_number, short_number_desc)
[ "def", "is_valid_short_number_for_region", "(", "short_number", ",", "region_dialing_from", ")", ":", "if", "isinstance", "(", "short_number", ",", "PhoneNumber", ")", ":", "short_number", "=", "national_significant_number", "(", "short_number", ")", "metadata", "=", ...
tests whether a short number matches a valid pattern in a region .
train
false
19,941
def paypaltime2datetime(s): return datetime.datetime(*time.strptime(s, PayPalNVP.TIMESTAMP_FORMAT)[:6])
[ "def", "paypaltime2datetime", "(", "s", ")", ":", "return", "datetime", ".", "datetime", "(", "*", "time", ".", "strptime", "(", "s", ",", "PayPalNVP", ".", "TIMESTAMP_FORMAT", ")", "[", ":", "6", "]", ")" ]
convert a paypal time string to a datetime .
train
false
19,942
def _correct_trans(t): t = np.array(t, np.float64) t[:3, :3] *= t[3, :3][:, np.newaxis] t[3, :3] = 0.0 assert (t[(3, 3)] == 1.0) return t
[ "def", "_correct_trans", "(", "t", ")", ":", "t", "=", "np", ".", "array", "(", "t", ",", "np", ".", "float64", ")", "t", "[", ":", "3", ",", ":", "3", "]", "*=", "t", "[", "3", ",", ":", "3", "]", "[", ":", ",", "np", ".", "newaxis", "...
convert to a transformation matrix .
train
false
19,943
def _check_frame(d, frame_str): if (d['coord_frame'] != _str_to_frame[frame_str]): raise RuntimeError(('dig point must be in %s coordinate frame, got %s' % (frame_str, _frame_to_str[d['coord_frame']])))
[ "def", "_check_frame", "(", "d", ",", "frame_str", ")", ":", "if", "(", "d", "[", "'coord_frame'", "]", "!=", "_str_to_frame", "[", "frame_str", "]", ")", ":", "raise", "RuntimeError", "(", "(", "'dig point must be in %s coordinate frame, got %s'", "%", "(", "...
helper to check coordinate frames .
train
false
19,944
def getFontReader(fontFamily): fontLower = fontFamily.lower().replace(' ', '_') global globalFontReaderDictionary if (fontLower in globalFontReaderDictionary): return globalFontReaderDictionary[fontLower] global globalFontFileNames if (globalFontFileNames == None): globalFontFileNames = archive.getPluginFileNamesFromDirectoryPath(getFontsDirectoryPath()) if (fontLower not in globalFontFileNames): print ('Warning, the %s font was not found in the fonts folder, so Gentium Basic Regular will be substituted.' % fontFamily) fontLower = 'gentium_basic_regular' fontReader = FontReader(fontLower) globalFontReaderDictionary[fontLower] = fontReader return fontReader
[ "def", "getFontReader", "(", "fontFamily", ")", ":", "fontLower", "=", "fontFamily", ".", "lower", "(", ")", ".", "replace", "(", "' '", ",", "'_'", ")", "global", "globalFontReaderDictionary", "if", "(", "fontLower", "in", "globalFontReaderDictionary", ")", "...
get the font reader for the fontfamily .
train
false
19,946
def _pivot_col(T, tol=1e-12, bland=False): ma = np.ma.masked_where((T[(-1), :(-1)] >= (- tol)), T[(-1), :(-1)], copy=False) if (ma.count() == 0): return (False, np.nan) if bland: return (True, np.where((ma.mask == False))[0][0]) return (True, np.ma.where((ma == ma.min()))[0][0])
[ "def", "_pivot_col", "(", "T", ",", "tol", "=", "1e-12", ",", "bland", "=", "False", ")", ":", "ma", "=", "np", ".", "ma", ".", "masked_where", "(", "(", "T", "[", "(", "-", "1", ")", ",", ":", "(", "-", "1", ")", "]", ">=", "(", "-", "to...
given a linear programming simplex tableau .
train
false
19,947
def encompasses_broadcastable(b1, b2): if (len(b1) < len(b2)): return False b1 = b1[(- len(b2)):] return (not any(((v1 and (not v2)) for (v1, v2) in zip(b1, b2))))
[ "def", "encompasses_broadcastable", "(", "b1", ",", "b2", ")", ":", "if", "(", "len", "(", "b1", ")", "<", "len", "(", "b2", ")", ")", ":", "return", "False", "b1", "=", "b1", "[", "(", "-", "len", "(", "b2", ")", ")", ":", "]", "return", "("...
parameters b1 the broadcastable attribute of a tensor type .
train
false
19,948
def user_input(prompt=''): if (PY_MAJOR_VERSION > 2): return input(prompt) else: return raw_input(prompt)
[ "def", "user_input", "(", "prompt", "=", "''", ")", ":", "if", "(", "PY_MAJOR_VERSION", ">", "2", ")", ":", "return", "input", "(", "prompt", ")", "else", ":", "return", "raw_input", "(", "prompt", ")" ]
for getting raw user input in python 2 and 3 .
train
false
19,950
@yield_fixture def no_patience(app): with mock.patch.dict(app.tornado_application.settings, {'slow_spawn_timeout': 0, 'slow_stop_timeout': 0}): (yield)
[ "@", "yield_fixture", "def", "no_patience", "(", "app", ")", ":", "with", "mock", ".", "patch", ".", "dict", "(", "app", ".", "tornado_application", ".", "settings", ",", "{", "'slow_spawn_timeout'", ":", "0", ",", "'slow_stop_timeout'", ":", "0", "}", ")"...
set slow-spawning timeouts to zero .
train
false
19,952
@frappe.whitelist() def make_mapped_doc(method, source_name, selected_children=None): method = frappe.get_attr(method) if (method not in frappe.whitelisted): raise frappe.PermissionError if selected_children: selected_children = json.loads(selected_children) frappe.flags.selected_children = (selected_children or None) return method(source_name)
[ "@", "frappe", ".", "whitelist", "(", ")", "def", "make_mapped_doc", "(", "method", ",", "source_name", ",", "selected_children", "=", "None", ")", ":", "method", "=", "frappe", ".", "get_attr", "(", "method", ")", "if", "(", "method", "not", "in", "frap...
returns the mapped document calling the given mapper method .
train
false
19,953
def rename_renewal_config(prev_name, new_name, cli_config): prev_filename = renewal_filename_for_lineagename(cli_config, prev_name) new_filename = renewal_filename_for_lineagename(cli_config, new_name) if os.path.exists(new_filename): raise errors.ConfigurationError('The new certificate name is already in use.') try: os.rename(prev_filename, new_filename) except OSError: raise errors.ConfigurationError('Please specify a valid filename for the new certificate name.')
[ "def", "rename_renewal_config", "(", "prev_name", ",", "new_name", ",", "cli_config", ")", ":", "prev_filename", "=", "renewal_filename_for_lineagename", "(", "cli_config", ",", "prev_name", ")", "new_filename", "=", "renewal_filename_for_lineagename", "(", "cli_config", ...
renames cli_config .
train
false
19,954
def test_user_statement_on_import(): s = u('from datetime import (\n time)') for pos in [(2, 1), (2, 4)]: p = ParserWithRecovery(load_grammar(), s) stmt = p.module.get_statement_for_position(pos) assert isinstance(stmt, pt.Import) assert ([str(n) for n in stmt.get_defined_names()] == ['time'])
[ "def", "test_user_statement_on_import", "(", ")", ":", "s", "=", "u", "(", "'from datetime import (\\n time)'", ")", "for", "pos", "in", "[", "(", "2", ",", "1", ")", ",", "(", "2", ",", "4", ")", "]", ":", "p", "=", "ParserWithRecovery", "(", "load...
github #285 .
train
false
19,955
def plot_epochs(epochs, picks=None, scalings=None, n_epochs=20, n_channels=20, title=None, events=None, event_colors=None, show=True, block=False): epochs.drop_bad() scalings = _compute_scalings(scalings, epochs) scalings = _handle_default('scalings_plot_raw', scalings) projs = epochs.info['projs'] params = {'epochs': epochs, 'info': copy.deepcopy(epochs.info), 'bad_color': (0.8, 0.8, 0.8), 't_start': 0, 'histogram': None} params['label_click_fun'] = partial(_pick_bad_channels, params=params) _prepare_mne_browse_epochs(params, projs, n_channels, n_epochs, scalings, title, picks, events=events, event_colors=event_colors) _prepare_projectors(params) _layout_figure(params) callback_close = partial(_close_event, params=params) params['fig'].canvas.mpl_connect('close_event', callback_close) try: plt_show(show, block=block) except TypeError: plt_show(show) return params['fig']
[ "def", "plot_epochs", "(", "epochs", ",", "picks", "=", "None", ",", "scalings", "=", "None", ",", "n_epochs", "=", "20", ",", "n_channels", "=", "20", ",", "title", "=", "None", ",", "events", "=", "None", ",", "event_colors", "=", "None", ",", "sho...
visualize epochs .
train
false
19,956
@intercept_errors(UserAPIInternalError, ignore_errors=[UserAPIRequestError]) def activate_account(activation_key): try: registration = Registration.objects.get(activation_key=activation_key) except Registration.DoesNotExist: raise UserNotAuthorized else: registration.activate()
[ "@", "intercept_errors", "(", "UserAPIInternalError", ",", "ignore_errors", "=", "[", "UserAPIRequestError", "]", ")", "def", "activate_account", "(", "activation_key", ")", ":", "try", ":", "registration", "=", "Registration", ".", "objects", ".", "get", "(", "...
when link in activation e-mail is clicked .
train
false
19,957
@gof.local_optimizer([SparseBlockOuter], inplace=True) def local_inplace_sparse_block_outer(node): if (isinstance(node.op, SparseBlockOuter) and (not node.op.inplace)): new_node = sparse_block_outer_inplace(*node.inputs) copy_stack_trace(node.outputs[0], new_node) return [new_node] return False
[ "@", "gof", ".", "local_optimizer", "(", "[", "SparseBlockOuter", "]", ",", "inplace", "=", "True", ")", "def", "local_inplace_sparse_block_outer", "(", "node", ")", ":", "if", "(", "isinstance", "(", "node", ".", "op", ",", "SparseBlockOuter", ")", "and", ...
sparseblockouter -> sparseblockouter .
train
false
19,959
def get_metrics_instance(): from stream_framework import settings metric_cls = get_class_from_string(settings.STREAM_METRIC_CLASS) return metric_cls(**settings.STREAM_METRICS_OPTIONS)
[ "def", "get_metrics_instance", "(", ")", ":", "from", "stream_framework", "import", "settings", "metric_cls", "=", "get_class_from_string", "(", "settings", ".", "STREAM_METRIC_CLASS", ")", "return", "metric_cls", "(", "**", "settings", ".", "STREAM_METRICS_OPTIONS", ...
returns an instance of the metric class as defined in stream_framework settings .
train
false
19,961
def get_travis_directories(package_list): if in_travis_pr(): pr_against_branch = travis_branch() return get_changed_packages('HEAD', pr_against_branch, package_list) else: return package_list
[ "def", "get_travis_directories", "(", "package_list", ")", ":", "if", "in_travis_pr", "(", ")", ":", "pr_against_branch", "=", "travis_branch", "(", ")", "return", "get_changed_packages", "(", "'HEAD'", ",", "pr_against_branch", ",", "package_list", ")", "else", "...
get list of packages that need to be tested on travis ci .
train
false
19,962
def test_append_private_mode(hist, config_stub): hist.handle_private_mode = True config_stub.data = CONFIG_PRIVATE hist.append('new item') assert (hist.history == HISTORY)
[ "def", "test_append_private_mode", "(", "hist", ",", "config_stub", ")", ":", "hist", ".", "handle_private_mode", "=", "True", "config_stub", ".", "data", "=", "CONFIG_PRIVATE", "hist", ".", "append", "(", "'new item'", ")", "assert", "(", "hist", ".", "histor...
test append in private mode .
train
false
19,963
def test_hierarchical(): (raw, events, picks) = _get_data() event_id = {'a/1': 1, 'a/2': 2, 'b/1': 3, 'b/2': 4} epochs = Epochs(raw, events, event_id, preload=True) epochs_a1 = epochs['a/1'] epochs_a2 = epochs['a/2'] epochs_b1 = epochs['b/1'] epochs_b2 = epochs['b/2'] epochs_a = epochs['a'] assert_equal(len(epochs_a), (len(epochs_a1) + len(epochs_a2))) epochs_b = epochs['b'] assert_equal(len(epochs_b), (len(epochs_b1) + len(epochs_b2))) epochs_1 = epochs['1'] assert_equal(len(epochs_1), (len(epochs_a1) + len(epochs_b1))) epochs_2 = epochs['2'] assert_equal(len(epochs_2), (len(epochs_a2) + len(epochs_b2))) epochs_all = epochs[('1', '2')] assert_equal(len(epochs), len(epochs_all)) assert_array_equal(epochs.get_data(), epochs_all.get_data())
[ "def", "test_hierarchical", "(", ")", ":", "(", "raw", ",", "events", ",", "picks", ")", "=", "_get_data", "(", ")", "event_id", "=", "{", "'a/1'", ":", "1", ",", "'a/2'", ":", "2", ",", "'b/1'", ":", "3", ",", "'b/2'", ":", "4", "}", "epochs", ...
test hierarchical access .
train
false
19,964
def hmean(a, axis=0, dtype=None): if (not isinstance(a, np.ndarray)): a = np.array(a, dtype=dtype) if np.all((a > 0)): if isinstance(a, np.ma.MaskedArray): size = a.count(axis) elif (axis is None): a = a.ravel() size = a.shape[0] else: size = a.shape[axis] return (size / np.sum((1.0 / a), axis=axis, dtype=dtype)) else: raise ValueError('Harmonic mean only defined if all elements greater than zero')
[ "def", "hmean", "(", "a", ",", "axis", "=", "0", ",", "dtype", "=", "None", ")", ":", "if", "(", "not", "isinstance", "(", "a", ",", "np", ".", "ndarray", ")", ")", ":", "a", "=", "np", ".", "array", "(", "a", ",", "dtype", "=", "dtype", ")...
returns the harmonic mean of the given list of values .
train
false
19,965
def _fetch_latest_from_datastore(app_version): rpc = db.create_rpc(deadline=DATASTORE_DEADLINE, read_policy=db.EVENTUAL_CONSISTENCY) key = _get_active_config_key(app_version) config = None try: config = Config.get(key, rpc=rpc) logging.debug('Loaded most recent conf data from datastore.') except: logging.warning('Tried but failed to fetch latest conf data from the datastore.') if config: memcache.set(app_version, db.model_to_protobuf(config).Encode(), namespace=NAMESPACE) logging.debug('Wrote most recent conf data into memcache.') return config
[ "def", "_fetch_latest_from_datastore", "(", "app_version", ")", ":", "rpc", "=", "db", ".", "create_rpc", "(", "deadline", "=", "DATASTORE_DEADLINE", ",", "read_policy", "=", "db", ".", "EVENTUAL_CONSISTENCY", ")", "key", "=", "_get_active_config_key", "(", "app_v...
get the latest configuration data for this app-version from the datastore .
train
false
19,966
def GroupEnum(): nmembers = 0 resume = 0 while 1: (data, total, resume) = win32net.NetGroupEnum(server, 1, resume) for group in data: verbose(('Found group %(name)s:%(comment)s ' % group)) memberresume = 0 while 1: (memberdata, total, memberresume) = win32net.NetGroupGetUsers(server, group['name'], 0, resume) for member in memberdata: verbose((' Member %(name)s' % member)) nmembers = (nmembers + 1) if (memberresume == 0): break if (not resume): break assert nmembers, 'Couldnt find a single member in a single group!' print 'Enumerated all the groups'
[ "def", "GroupEnum", "(", ")", ":", "nmembers", "=", "0", "resume", "=", "0", "while", "1", ":", "(", "data", ",", "total", ",", "resume", ")", "=", "win32net", ".", "NetGroupEnum", "(", "server", ",", "1", ",", "resume", ")", "for", "group", "in", ...
enumerates all the domain groups .
train
false
19,967
def safe_lower(txt): if txt: return txt.lower() else: return ''
[ "def", "safe_lower", "(", "txt", ")", ":", "if", "txt", ":", "return", "txt", ".", "lower", "(", ")", "else", ":", "return", "''" ]
return lowercased string .
train
false
19,968
def certificate_get_all_by_user(context, user_id): return IMPL.certificate_get_all_by_user(context, user_id)
[ "def", "certificate_get_all_by_user", "(", "context", ",", "user_id", ")", ":", "return", "IMPL", ".", "certificate_get_all_by_user", "(", "context", ",", "user_id", ")" ]
get all certificates for a user .
train
false