id_within_dataset int64 1 55.5k | snippet stringlengths 19 14.2k | tokens listlengths 6 1.63k | nl stringlengths 6 352 | split_within_dataset stringclasses 1
value | is_duplicated bool 2
classes |
|---|---|---|---|---|---|
34,438 | def _create_widget_object(request, module_name, widget_name):
user = request.user.profile
perspective = user.get_perspective()
modules = perspective.get_modules()
obj = None
current_module = modules.filter(name=module_name)
widget = None
if current_module:
current_module = current_module[0]
widget = _get_wid... | [
"def",
"_create_widget_object",
"(",
"request",
",",
"module_name",
",",
"widget_name",
")",
":",
"user",
"=",
"request",
".",
"user",
".",
"profile",
"perspective",
"=",
"user",
".",
"get_perspective",
"(",
")",
"modules",
"=",
"perspective",
".",
"get_module... | create a widget object if one is available for the current user perspective . | train | false |
34,439 | @pytest.mark.skipif(u'not HAS_PATHLIB')
def test_validate_path_object():
test_validate(test_path_object=True)
| [
"@",
"pytest",
".",
"mark",
".",
"skipif",
"(",
"u'not HAS_PATHLIB'",
")",
"def",
"test_validate_path_object",
"(",
")",
":",
"test_validate",
"(",
"test_path_object",
"=",
"True",
")"
] | validating when source is passed as path object . | train | false |
34,442 | def cluster_data(data, cluster_cnt, iter=20, thresh=1e-05):
wh_data = vq.whiten(data)
(code_book, dist) = vq.kmeans(wh_data, cluster_cnt, iter, thresh)
(code_ids, distortion) = vq.vq(wh_data, code_book)
clusters = []
for i in range(len(code_book)):
cluster = np.compress((code_ids == i), data, 0)
clusters.appen... | [
"def",
"cluster_data",
"(",
"data",
",",
"cluster_cnt",
",",
"iter",
"=",
"20",
",",
"thresh",
"=",
"1e-05",
")",
":",
"wh_data",
"=",
"vq",
".",
"whiten",
"(",
"data",
")",
"(",
"code_book",
",",
"dist",
")",
"=",
"vq",
".",
"kmeans",
"(",
"wh_dat... | group data into a number of common clusters data -- 2d array of data points . | train | false |
34,443 | def subnets6():
return _subnets('inet6')
| [
"def",
"subnets6",
"(",
")",
":",
"return",
"_subnets",
"(",
"'inet6'",
")"
] | returns a list of ipv6 subnets to which the host belongs . | train | false |
34,444 | @with_session
def get_cached(style=None, title=None, year=None, trakt_id=None, trakt_slug=None, tmdb_id=None, imdb_id=None, tvdb_id=None, tvrage_id=None, session=None):
ids = {u'id': trakt_id, u'slug': trakt_slug, u'tmdb_id': tmdb_id, u'imdb_id': imdb_id}
if (style == u'show'):
ids[u'tvdb_id'] = tvdb_id
ids[u'tvr... | [
"@",
"with_session",
"def",
"get_cached",
"(",
"style",
"=",
"None",
",",
"title",
"=",
"None",
",",
"year",
"=",
"None",
",",
"trakt_id",
"=",
"None",
",",
"trakt_slug",
"=",
"None",
",",
"tmdb_id",
"=",
"None",
",",
"imdb_id",
"=",
"None",
",",
"tv... | get the cached info for a given show/movie from the database . | train | false |
34,445 | @pytest.mark.django_db
def test_tp_empty_stats(project0_nongnu, project0, templates):
language = LanguageDBFactory()
tp = TranslationProject.objects.create(language=language, project=project0)
tp.init_from_templates()
assert (list(tp.stores.all()) == [])
stats = tp.data_tool.get_stats()
assert (stats['total'] == ... | [
"@",
"pytest",
".",
"mark",
".",
"django_db",
"def",
"test_tp_empty_stats",
"(",
"project0_nongnu",
",",
"project0",
",",
"templates",
")",
":",
"language",
"=",
"LanguageDBFactory",
"(",
")",
"tp",
"=",
"TranslationProject",
".",
"objects",
".",
"create",
"("... | tests if empty stats is initialized when translation project is added for a project with existing but empty template translation project . | train | false |
34,446 | def run_scenario(scenario):
seed = scenario['random_seed']
rb = builder.RingBuilder(scenario['part_power'], scenario['replicas'], 1)
rb.set_overload(scenario['overload'])
command_map = {'add': rb.add_dev, 'remove': rb.remove_dev, 'set_weight': rb.set_dev_weight, 'save': rb.save}
for (round_index, commands) in enum... | [
"def",
"run_scenario",
"(",
"scenario",
")",
":",
"seed",
"=",
"scenario",
"[",
"'random_seed'",
"]",
"rb",
"=",
"builder",
".",
"RingBuilder",
"(",
"scenario",
"[",
"'part_power'",
"]",
",",
"scenario",
"[",
"'replicas'",
"]",
",",
"1",
")",
"rb",
".",
... | runs a django scenario and returns its output vars . | train | false |
34,447 | def all_files(*args):
ls_files = git.ls_files(u'--', z=True, cached=True, others=True, exclude_standard=True, *args)[STDOUT]
return sorted([f for f in ls_files.split(u'\x00') if f])
| [
"def",
"all_files",
"(",
"*",
"args",
")",
":",
"ls_files",
"=",
"git",
".",
"ls_files",
"(",
"u'--'",
",",
"z",
"=",
"True",
",",
"cached",
"=",
"True",
",",
"others",
"=",
"True",
",",
"exclude_standard",
"=",
"True",
",",
"*",
"args",
")",
"[",
... | returns a sorted list of all files . | train | false |
34,450 | def key_kind_n(index):
@empty_if_none
def transform_function(key):
path = key.to_path()
path_index = (index * 2)
return unicode(path[path_index])
return transform_function
| [
"def",
"key_kind_n",
"(",
"index",
")",
":",
"@",
"empty_if_none",
"def",
"transform_function",
"(",
"key",
")",
":",
"path",
"=",
"key",
".",
"to_path",
"(",
")",
"path_index",
"=",
"(",
"index",
"*",
"2",
")",
"return",
"unicode",
"(",
"path",
"[",
... | pull out the nth key kind from a key which has parents . | train | false |
34,451 | def read_raw_artemis123(input_fname, preload=False, verbose=None):
return RawArtemis123(input_fname, preload=preload, verbose=verbose)
| [
"def",
"read_raw_artemis123",
"(",
"input_fname",
",",
"preload",
"=",
"False",
",",
"verbose",
"=",
"None",
")",
":",
"return",
"RawArtemis123",
"(",
"input_fname",
",",
"preload",
"=",
"preload",
",",
"verbose",
"=",
"verbose",
")"
] | read artemis123 data as raw object . | train | false |
34,452 | def getXYComplexFromVector3(vector3):
if (vector3 == None):
return None
return vector3.dropAxis()
| [
"def",
"getXYComplexFromVector3",
"(",
"vector3",
")",
":",
"if",
"(",
"vector3",
"==",
"None",
")",
":",
"return",
"None",
"return",
"vector3",
".",
"dropAxis",
"(",
")"
] | get an xy complex from a vector3 if it exists . | train | false |
34,453 | def block_average_above(x, y, new_x):
bad_index = None
x = atleast_1d_and_contiguous(x, np.float64)
y = atleast_1d_and_contiguous(y, np.float64)
new_x = atleast_1d_and_contiguous(new_x, np.float64)
if (y.ndim > 2):
raise ValueError('`linear` only works with 1-D or 2-D arrays.')
if (len(y.shape) == 2):
new_y =... | [
"def",
"block_average_above",
"(",
"x",
",",
"y",
",",
"new_x",
")",
":",
"bad_index",
"=",
"None",
"x",
"=",
"atleast_1d_and_contiguous",
"(",
"x",
",",
"np",
".",
"float64",
")",
"y",
"=",
"atleast_1d_and_contiguous",
"(",
"y",
",",
"np",
".",
"float64... | linearly interpolates values in new_x based on the values in x and y . | train | false |
34,457 | def send_monthly():
for report in frappe.get_all(u'Auto Email Report', {u'enabled': 1, u'frequency': u'Monthly'}):
frappe.get_doc(u'Auto Email Report', report.name).send()
| [
"def",
"send_monthly",
"(",
")",
":",
"for",
"report",
"in",
"frappe",
".",
"get_all",
"(",
"u'Auto Email Report'",
",",
"{",
"u'enabled'",
":",
"1",
",",
"u'frequency'",
":",
"u'Monthly'",
"}",
")",
":",
"frappe",
".",
"get_doc",
"(",
"u'Auto Email Report'"... | check reports to be sent monthly . | train | false |
34,458 | def draw_lines(start, total_duration, minute_scale, scale):
result = u''
next_line = 220
next_time = start
num_lines = (((total_duration // 60) // minute_scale) + 2)
for line in range(num_lines):
new_line = (u"<hr class='line' width='98%%' style='top:%dpx;'>" % next_line)
result += new_line
time = (u"<p clas... | [
"def",
"draw_lines",
"(",
"start",
",",
"total_duration",
",",
"minute_scale",
",",
"scale",
")",
":",
"result",
"=",
"u''",
"next_line",
"=",
"220",
"next_time",
"=",
"start",
"num_lines",
"=",
"(",
"(",
"(",
"total_duration",
"//",
"60",
")",
"//",
"mi... | function to draw the minute line markers and timestamps parameters start : datetime . | train | false |
34,459 | def tensorinv(a, ind=2):
return TensorInv(ind)(a)
| [
"def",
"tensorinv",
"(",
"a",
",",
"ind",
"=",
"2",
")",
":",
"return",
"TensorInv",
"(",
"ind",
")",
"(",
"a",
")"
] | does not run on gpu; theano utilization of numpy . | train | false |
34,460 | def get_valuation_method(item_code):
val_method = frappe.db.get_value(u'Item', item_code, u'valuation_method')
if (not val_method):
val_method = (frappe.db.get_value(u'Stock Settings', None, u'valuation_method') or u'FIFO')
return val_method
| [
"def",
"get_valuation_method",
"(",
"item_code",
")",
":",
"val_method",
"=",
"frappe",
".",
"db",
".",
"get_value",
"(",
"u'Item'",
",",
"item_code",
",",
"u'valuation_method'",
")",
"if",
"(",
"not",
"val_method",
")",
":",
"val_method",
"=",
"(",
"frappe"... | get valuation method from item or default . | train | false |
34,461 | def LocateWebServerPath(description):
assert (len(description) >= 1), 'Server name or comment is required'
iis = GetObject(_IIS_OBJECT)
description = description.lower().strip()
for site in iis:
site_attributes = [getattr(site, attr, '').lower().strip() for attr in ('Name', 'ServerComment')]
if (description in ... | [
"def",
"LocateWebServerPath",
"(",
"description",
")",
":",
"assert",
"(",
"len",
"(",
"description",
")",
">=",
"1",
")",
",",
"'Server name or comment is required'",
"iis",
"=",
"GetObject",
"(",
"_IIS_OBJECT",
")",
"description",
"=",
"description",
".",
"low... | find an iis web server whose name or comment matches the provided description . | train | false |
34,462 | def write_array(f, grp, array, name):
atom = tables.Atom.from_dtype(array.dtype)
ds = f.createCArray(grp, name, atom, array.shape)
ds[:] = array
| [
"def",
"write_array",
"(",
"f",
",",
"grp",
",",
"array",
",",
"name",
")",
":",
"atom",
"=",
"tables",
".",
"Atom",
".",
"from_dtype",
"(",
"array",
".",
"dtype",
")",
"ds",
"=",
"f",
".",
"createCArray",
"(",
"grp",
",",
"name",
",",
"atom",
",... | stores array in into group grp of h5 file f under name name . | train | false |
34,463 | def _make_multiples(b):
(c, k) = (b.c, b.k)
t1 = b.t.copy()
t1[17:19] = t1[17]
t1[22] = t1[21]
(yield BSpline(t1, c, k))
t1 = b.t.copy()
t1[:(k + 1)] = t1[0]
(yield BSpline(t1, c, k))
t1 = b.t.copy()
t1[((- k) - 1):] = t1[(-1)]
(yield BSpline(t1, c, k))
| [
"def",
"_make_multiples",
"(",
"b",
")",
":",
"(",
"c",
",",
"k",
")",
"=",
"(",
"b",
".",
"c",
",",
"b",
".",
"k",
")",
"t1",
"=",
"b",
".",
"t",
".",
"copy",
"(",
")",
"t1",
"[",
"17",
":",
"19",
"]",
"=",
"t1",
"[",
"17",
"]",
"t1"... | increase knot multiplicity . | train | false |
34,464 | def check_keystore_json(jsondata):
if (('crypto' not in jsondata) and ('Crypto' not in jsondata)):
return False
if ('version' not in jsondata):
return False
if (jsondata['version'] != 3):
return False
crypto = jsondata.get('crypto', jsondata.get('Crypto'))
if ('cipher' not in crypto):
return False
if ('ci... | [
"def",
"check_keystore_json",
"(",
"jsondata",
")",
":",
"if",
"(",
"(",
"'crypto'",
"not",
"in",
"jsondata",
")",
"and",
"(",
"'Crypto'",
"not",
"in",
"jsondata",
")",
")",
":",
"return",
"False",
"if",
"(",
"'version'",
"not",
"in",
"jsondata",
")",
... | check if jsondata has the structure of a keystore file version 3 . | train | true |
34,466 | def _get_children_as(parent, tag, construct):
return [construct(child) for child in parent.findall(_ns(tag))]
| [
"def",
"_get_children_as",
"(",
"parent",
",",
"tag",
",",
"construct",
")",
":",
"return",
"[",
"construct",
"(",
"child",
")",
"for",
"child",
"in",
"parent",
".",
"findall",
"(",
"_ns",
"(",
"tag",
")",
")",
"]"
] | find child nodes by tag; pass each through a constructor . | train | false |
34,468 | def test_defined_step_represent_string():
feature_file = ojoin('runner_features', 'first.feature')
feature_dir = ojoin('runner_features')
loader = FeatureLoader(feature_dir)
world._output = StringIO()
world._is_colored = False
loader.find_and_load_step_definitions()
feature = Feature.from_file(feature_file)
ste... | [
"def",
"test_defined_step_represent_string",
"(",
")",
":",
"feature_file",
"=",
"ojoin",
"(",
"'runner_features'",
",",
"'first.feature'",
")",
"feature_dir",
"=",
"ojoin",
"(",
"'runner_features'",
")",
"loader",
"=",
"FeatureLoader",
"(",
"feature_dir",
")",
"wor... | defined step represented without colors . | train | false |
34,469 | def test_periodic_command_delay():
with pytest.raises(ValueError) as exc_info:
schedule.PeriodicCommand.after(0, None)
assert (str(exc_info.value) == test_periodic_command_delay.__doc__)
| [
"def",
"test_periodic_command_delay",
"(",
")",
":",
"with",
"pytest",
".",
"raises",
"(",
"ValueError",
")",
"as",
"exc_info",
":",
"schedule",
".",
"PeriodicCommand",
".",
"after",
"(",
"0",
",",
"None",
")",
"assert",
"(",
"str",
"(",
"exc_info",
".",
... | a periodiccommand must have a positive . | train | false |
34,472 | def merge_identical_selectors(sheet):
selector_map = defaultdict(list)
for rule in sheet.cssRules.rulesOfType(CSSRule.STYLE_RULE):
selector_map[rule.selectorText].append(rule)
remove = []
for rule_group in selector_map.itervalues():
if (len(rule_group) > 1):
for i in range(1, len(rule_group)):
merge_decl... | [
"def",
"merge_identical_selectors",
"(",
"sheet",
")",
":",
"selector_map",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"rule",
"in",
"sheet",
".",
"cssRules",
".",
"rulesOfType",
"(",
"CSSRule",
".",
"STYLE_RULE",
")",
":",
"selector_map",
"[",
"rule",
"."... | merge rules that have identical selectors . | train | false |
34,473 | def patch_mako_templates():
orig_render = Template.render_unicode
def wrapped_render(*args, **kwargs):
' Render the template and send the context info to any listeners that want it '
django.test.signals.template_rendered.send(sender=None, template=None, context=kwargs)
return orig_render(*args, **kwargs)
retur... | [
"def",
"patch_mako_templates",
"(",
")",
":",
"orig_render",
"=",
"Template",
".",
"render_unicode",
"def",
"wrapped_render",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"django",
".",
"test",
".",
"signals",
".",
"template_rendered",
".",
"send",
"(",
... | patch mako so the django test client can access template context . | train | false |
34,475 | def get_xattr(path, key, **kwargs):
namespaced_key = _make_namespaced_xattr_key(key)
try:
return xattr.getxattr(path, namespaced_key)
except IOError:
if ('default' in kwargs):
return kwargs['default']
else:
raise
| [
"def",
"get_xattr",
"(",
"path",
",",
"key",
",",
"**",
"kwargs",
")",
":",
"namespaced_key",
"=",
"_make_namespaced_xattr_key",
"(",
"key",
")",
"try",
":",
"return",
"xattr",
".",
"getxattr",
"(",
"path",
",",
"namespaced_key",
")",
"except",
"IOError",
... | return the value for a particular xattr if the key doesnt not exist . | train | false |
34,476 | def getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0):
return get_hub().resolver.getaddrinfo(host, port, family, socktype, proto, flags)
| [
"def",
"getaddrinfo",
"(",
"host",
",",
"port",
",",
"family",
"=",
"0",
",",
"socktype",
"=",
"0",
",",
"proto",
"=",
"0",
",",
"flags",
"=",
"0",
")",
":",
"return",
"get_hub",
"(",
")",
".",
"resolver",
".",
"getaddrinfo",
"(",
"host",
",",
"p... | resolve host and port into list of address info entries . | train | false |
34,478 | def connect_sqs(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
from .sqs.connection import AsyncSQSConnection
return AsyncSQSConnection(aws_access_key_id, aws_secret_access_key, **kwargs)
| [
"def",
"connect_sqs",
"(",
"aws_access_key_id",
"=",
"None",
",",
"aws_secret_access_key",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"from",
".",
"sqs",
".",
"connection",
"import",
"AsyncSQSConnection",
"return",
"AsyncSQSConnection",
"(",
"aws_access_key_id",
... | return async connection to amazon sqs . | train | true |
34,480 | def p_expression_opt_2(t):
pass
| [
"def",
"p_expression_opt_2",
"(",
"t",
")",
":",
"pass"
] | expression_opt : expression . | train | false |
34,482 | def squared_error_ridge(x_i, y_i, beta, alpha):
return ((error(x_i, y_i, beta) ** 2) + ridge_penalty(beta, alpha))
| [
"def",
"squared_error_ridge",
"(",
"x_i",
",",
"y_i",
",",
"beta",
",",
"alpha",
")",
":",
"return",
"(",
"(",
"error",
"(",
"x_i",
",",
"y_i",
",",
"beta",
")",
"**",
"2",
")",
"+",
"ridge_penalty",
"(",
"beta",
",",
"alpha",
")",
")"
] | estimate error plus ridge penalty on beta . | train | false |
34,483 | @add_handler('log')
def qute_log(url):
if (log.ram_handler is None):
html_log = None
else:
try:
level = urllib.parse.parse_qs(url.query())['level'][0]
except KeyError:
level = 'vdebug'
html_log = log.ram_handler.dump_log(html=True, level=level)
html = jinja.render('log.html', title='log', content=html_... | [
"@",
"add_handler",
"(",
"'log'",
")",
"def",
"qute_log",
"(",
"url",
")",
":",
"if",
"(",
"log",
".",
"ram_handler",
"is",
"None",
")",
":",
"html_log",
"=",
"None",
"else",
":",
"try",
":",
"level",
"=",
"urllib",
".",
"parse",
".",
"parse_qs",
"... | handler for qute:log . | train | false |
34,484 | def test(HandlerClass=BaseHTTPRequestHandler, ServerClass=HTTPServer, protocol='HTTP/1.0', port=8000, bind=''):
server_address = (bind, port)
HandlerClass.protocol_version = protocol
httpd = ServerClass(server_address, HandlerClass)
sa = httpd.socket.getsockname()
print ('Serving HTTP on', sa[0], 'port', sa[1], '.... | [
"def",
"test",
"(",
"HandlerClass",
"=",
"BaseHTTPRequestHandler",
",",
"ServerClass",
"=",
"HTTPServer",
",",
"protocol",
"=",
"'HTTP/1.0'",
",",
"port",
"=",
"8000",
",",
"bind",
"=",
"''",
")",
":",
"server_address",
"=",
"(",
"bind",
",",
"port",
")",
... | rank-1 nex easily solves high-dimensional rosenbrock functions . | train | true |
34,485 | def _getDeprecationWarningString(fqpn, version, format=None, replacement=None):
if (format is None):
format = DEPRECATION_WARNING_FORMAT
warningString = (format % {'fqpn': fqpn, 'version': getVersionString(version)})
if replacement:
warningString = ('%s; %s' % (warningString, _getReplacementString(replacement)))... | [
"def",
"_getDeprecationWarningString",
"(",
"fqpn",
",",
"version",
",",
"format",
"=",
"None",
",",
"replacement",
"=",
"None",
")",
":",
"if",
"(",
"format",
"is",
"None",
")",
":",
"format",
"=",
"DEPRECATION_WARNING_FORMAT",
"warningString",
"=",
"(",
"f... | return a string indicating that the python name was deprecated in the given version . | train | false |
34,486 | def get_backend_instance(name):
LOG.debug(('Retrieving backend instance for backend "%s"' % name))
try:
manager = DriverManager(namespace=BACKENDS_NAMESPACE, name=name, invoke_on_load=False)
except RuntimeError:
message = ('Invalid authentication backend specified: %s' % name)
LOG.exception(message)
raise Va... | [
"def",
"get_backend_instance",
"(",
"name",
")",
":",
"LOG",
".",
"debug",
"(",
"(",
"'Retrieving backend instance for backend \"%s\"'",
"%",
"name",
")",
")",
"try",
":",
"manager",
"=",
"DriverManager",
"(",
"namespace",
"=",
"BACKENDS_NAMESPACE",
",",
"name",
... | retrieve a class instance for the provided auth backend . | train | false |
34,487 | def iso8601interval(value, argument='argument'):
try:
(start, end) = _parse_interval(value)
if (end is None):
end = _expand_datetime(start, value)
(start, end) = _normalize_interval(start, end, value)
except ValueError:
raise ValueError('Invalid {arg}: {value}. {arg} must be a valid ISO8601 date/time inter... | [
"def",
"iso8601interval",
"(",
"value",
",",
"argument",
"=",
"'argument'",
")",
":",
"try",
":",
"(",
"start",
",",
"end",
")",
"=",
"_parse_interval",
"(",
"value",
")",
"if",
"(",
"end",
"is",
"None",
")",
":",
"end",
"=",
"_expand_datetime",
"(",
... | parses iso 8601-formatted datetime intervals into tuples of datetimes . | train | true |
34,488 | def string_repr(text, show_quotes=True):
if (six.PY3 and isinstance(text, six.binary_type)):
output = repr(text)[1:]
else:
output = repr(text)
if show_quotes:
return output
else:
return output[1:(-1)]
| [
"def",
"string_repr",
"(",
"text",
",",
"show_quotes",
"=",
"True",
")",
":",
"if",
"(",
"six",
".",
"PY3",
"and",
"isinstance",
"(",
"text",
",",
"six",
".",
"binary_type",
")",
")",
":",
"output",
"=",
"repr",
"(",
"text",
")",
"[",
"1",
":",
"... | prints the repr of a string . | train | false |
34,489 | def shutdown_abort():
try:
win32api.AbortSystemShutdown('127.0.0.1')
return True
except pywintypes.error as exc:
(number, context, message) = exc
log.error('Failed to abort system shutdown')
log.error('nbr: {0}'.format(number))
log.error('ctx: {0}'.format(context))
log.error('msg: {0}'.format(message))
... | [
"def",
"shutdown_abort",
"(",
")",
":",
"try",
":",
"win32api",
".",
"AbortSystemShutdown",
"(",
"'127.0.0.1'",
")",
"return",
"True",
"except",
"pywintypes",
".",
"error",
"as",
"exc",
":",
"(",
"number",
",",
"context",
",",
"message",
")",
"=",
"exc",
... | abort a shutdown . | train | true |
34,490 | def _all_wants_satisfied(store, haves, wants):
haves = set(haves)
if haves:
earliest = min([store[h].commit_time for h in haves])
else:
earliest = 0
for want in wants:
if (not _want_satisfied(store, haves, want, earliest)):
return False
return True
| [
"def",
"_all_wants_satisfied",
"(",
"store",
",",
"haves",
",",
"wants",
")",
":",
"haves",
"=",
"set",
"(",
"haves",
")",
"if",
"haves",
":",
"earliest",
"=",
"min",
"(",
"[",
"store",
"[",
"h",
"]",
".",
"commit_time",
"for",
"h",
"in",
"haves",
... | check whether all the current wants are satisfied by a set of haves . | train | false |
34,491 | def get_instance_el(evaluator, instance, var, is_class_var=False):
if isinstance(var, tree.Name):
parent = get_instance_el(evaluator, instance, var.parent, is_class_var)
return InstanceName(var, parent)
elif ((var.type != 'funcdef') and isinstance(var, (Instance, compiled.CompiledObject, tree.Leaf, tree.Module, F... | [
"def",
"get_instance_el",
"(",
"evaluator",
",",
"instance",
",",
"var",
",",
"is_class_var",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"var",
",",
"tree",
".",
"Name",
")",
":",
"parent",
"=",
"get_instance_el",
"(",
"evaluator",
",",
"instance",
... | returns an instanceelement if it makes sense . | train | false |
34,492 | def _args_for_opt_dest_subset(option_parser, args, dests=None):
values = deepcopy(option_parser.get_default_values())
rargs = [x for x in args]
option_parser.rargs = rargs
while rargs:
arg = rargs[0]
if (arg == '--'):
del rargs[0]
return
elif (arg[0:2] == '--'):
for item in _process_long_opt(option_p... | [
"def",
"_args_for_opt_dest_subset",
"(",
"option_parser",
",",
"args",
",",
"dests",
"=",
"None",
")",
":",
"values",
"=",
"deepcopy",
"(",
"option_parser",
".",
"get_default_values",
"(",
")",
")",
"rargs",
"=",
"[",
"x",
"for",
"x",
"in",
"args",
"]",
... | see docs for :py:func:args_for_opt_dest_subset() . | train | false |
34,493 | def convert_to_lower(data):
results = dict()
if isinstance(data, dict):
for (key, val) in data.items():
key = re.sub('(([A-Z]{1,3}){1})', '_\\1', key).lower()
if (key[0] == '_'):
key = key[1:]
if isinstance(val, datetime.datetime):
results[key] = val.isoformat()
elif isinstance(val, dict):
r... | [
"def",
"convert_to_lower",
"(",
"data",
")",
":",
"results",
"=",
"dict",
"(",
")",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"for",
"(",
"key",
",",
"val",
")",
"in",
"data",
".",
"items",
"(",
")",
":",
"key",
"=",
"re",
".",
"s... | convert all uppercase keys in dict with lowercase_ args: data : dictionary with keys that have upper cases in them example . | train | false |
34,496 | def ignore_notfound(func, *args, **kwargs):
try:
return func(*args, **kwargs)
except n_exc.NotFound:
pass
| [
"def",
"ignore_notfound",
"(",
"func",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"except",
"n_exc",
".",
"NotFound",
":",
"pass"
] | call the given function and pass if a notfound exception is raised . | train | false |
34,498 | def browse_to(browser, dest_url, wait_time=0.1, max_retries=50):
if (dest_url == browser.current_url):
return True
browser.get(dest_url)
return True
| [
"def",
"browse_to",
"(",
"browser",
",",
"dest_url",
",",
"wait_time",
"=",
"0.1",
",",
"max_retries",
"=",
"50",
")",
":",
"if",
"(",
"dest_url",
"==",
"browser",
".",
"current_url",
")",
":",
"return",
"True",
"browser",
".",
"get",
"(",
"dest_url",
... | browse to the given url . | train | false |
34,499 | def _transform_selected(X, transform, selected='all', copy=True):
X = check_array(X, accept_sparse='csc', copy=copy, dtype=FLOAT_DTYPES)
if (isinstance(selected, six.string_types) and (selected == 'all')):
return transform(X)
if (len(selected) == 0):
return X
n_features = X.shape[1]
ind = np.arange(n_features)... | [
"def",
"_transform_selected",
"(",
"X",
",",
"transform",
",",
"selected",
"=",
"'all'",
",",
"copy",
"=",
"True",
")",
":",
"X",
"=",
"check_array",
"(",
"X",
",",
"accept_sparse",
"=",
"'csc'",
",",
"copy",
"=",
"copy",
",",
"dtype",
"=",
"FLOAT_DTYP... | apply a transform function to portion of selected features parameters x : {array-like . | train | false |
34,500 | def dup_gegenbauer(n, a, K):
seq = [[K.one], [(K(2) * a), K.zero]]
for i in range(2, (n + 1)):
f1 = ((K(2) * ((i + a) - K.one)) / i)
f2 = (((i + (K(2) * a)) - K(2)) / i)
p1 = dup_mul_ground(dup_lshift(seq[(-1)], 1, K), f1, K)
p2 = dup_mul_ground(seq[(-2)], f2, K)
seq.append(dup_sub(p1, p2, K))
return seq[n... | [
"def",
"dup_gegenbauer",
"(",
"n",
",",
"a",
",",
"K",
")",
":",
"seq",
"=",
"[",
"[",
"K",
".",
"one",
"]",
",",
"[",
"(",
"K",
"(",
"2",
")",
"*",
"a",
")",
",",
"K",
".",
"zero",
"]",
"]",
"for",
"i",
"in",
"range",
"(",
"2",
",",
... | low-level implementation of gegenbauer polynomials . | train | false |
34,501 | def tokens_equal(x, y):
xtup = ensure_tuple(x)
ytup = ensure_tuple(y)
return (xtup == ytup)
| [
"def",
"tokens_equal",
"(",
"x",
",",
"y",
")",
":",
"xtup",
"=",
"ensure_tuple",
"(",
"x",
")",
"ytup",
"=",
"ensure_tuple",
"(",
"y",
")",
"return",
"(",
"xtup",
"==",
"ytup",
")"
] | tests whether two token are equal . | train | false |
34,503 | def generate_tool_shed_repository_install_dir(repository_clone_url, changeset_revision):
tmp_url = common_util.remove_protocol_and_user_from_clone_url(repository_clone_url)
items = tmp_url.split('/repos/')
tool_shed_url = items[0]
repo_path = items[1]
tool_shed_url = common_util.remove_port_from_tool_shed_url(tool... | [
"def",
"generate_tool_shed_repository_install_dir",
"(",
"repository_clone_url",
",",
"changeset_revision",
")",
":",
"tmp_url",
"=",
"common_util",
".",
"remove_protocol_and_user_from_clone_url",
"(",
"repository_clone_url",
")",
"items",
"=",
"tmp_url",
".",
"split",
"(",... | generate a repository installation directory that guarantees repositories with the same name will always be installed in different directories . | train | false |
34,504 | def not_the_same(user, other_user):
return (user['id'] != other_user['id'])
| [
"def",
"not_the_same",
"(",
"user",
",",
"other_user",
")",
":",
"return",
"(",
"user",
"[",
"'id'",
"]",
"!=",
"other_user",
"[",
"'id'",
"]",
")"
] | two users are not the same if they have different ids . | train | false |
34,505 | def _RegEnumerator(key, func):
index = 0
try:
while 1:
(yield func(key, index))
index += 1
except WindowsError:
pass
| [
"def",
"_RegEnumerator",
"(",
"key",
",",
"func",
")",
":",
"index",
"=",
"0",
"try",
":",
"while",
"1",
":",
"(",
"yield",
"func",
"(",
"key",
",",
"index",
")",
")",
"index",
"+=",
"1",
"except",
"WindowsError",
":",
"pass"
] | enumerates an open registry key as an iterable generator . | train | false |
34,506 | def hashes():
t = []
if ('md5' in dir(hashlib)):
t = ['MD5']
if ('md2' in dir(hashlib)):
t += ['MD2']
hashes = [('SHA-' + h[3:]) for h in dir(hashlib) if h.startswith('sha')]
return (t + hashes)
| [
"def",
"hashes",
"(",
")",
":",
"t",
"=",
"[",
"]",
"if",
"(",
"'md5'",
"in",
"dir",
"(",
"hashlib",
")",
")",
":",
"t",
"=",
"[",
"'MD5'",
"]",
"if",
"(",
"'md2'",
"in",
"dir",
"(",
"hashlib",
")",
")",
":",
"t",
"+=",
"[",
"'MD2'",
"]",
... | return a list of available hashing algorithms . | train | false |
34,507 | def authenticationAndCipheringReject():
a = TpPd(pd=3)
b = MessageType(mesType=20)
packet = (a / b)
return packet
| [
"def",
"authenticationAndCipheringReject",
"(",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"3",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"20",
")",
"packet",
"=",
"(",
"a",
"/",
"b",
")",
"return",
"packet"
] | authentication and ciphering reject section 9 . | train | true |
34,509 | def lookup_vm_vdis(session, vm_ref):
vbd_refs = session.call_xenapi('VM.get_VBDs', vm_ref)
vdi_refs = []
if vbd_refs:
for vbd_ref in vbd_refs:
try:
vdi_ref = session.call_xenapi('VBD.get_VDI', vbd_ref)
vdi_uuid = session.call_xenapi('VDI.get_uuid', vdi_ref)
LOG.debug('VDI %s is still available', vdi... | [
"def",
"lookup_vm_vdis",
"(",
"session",
",",
"vm_ref",
")",
":",
"vbd_refs",
"=",
"session",
".",
"call_xenapi",
"(",
"'VM.get_VBDs'",
",",
"vm_ref",
")",
"vdi_refs",
"=",
"[",
"]",
"if",
"vbd_refs",
":",
"for",
"vbd_ref",
"in",
"vbd_refs",
":",
"try",
... | look for the vdis that are attached to the vm . | train | false |
34,510 | def find_interfaces(*args):
brs = _os_dispatch('brshow')
if (not brs):
return None
iflist = {}
for iface in args:
for br in brs:
try:
if (iface in brs[br]['interfaces']):
iflist[iface] = br
except Exception:
pass
return iflist
| [
"def",
"find_interfaces",
"(",
"*",
"args",
")",
":",
"brs",
"=",
"_os_dispatch",
"(",
"'brshow'",
")",
"if",
"(",
"not",
"brs",
")",
":",
"return",
"None",
"iflist",
"=",
"{",
"}",
"for",
"iface",
"in",
"args",
":",
"for",
"br",
"in",
"brs",
":",
... | returns the bridge to which the interfaces are bond to cli example: . | train | true |
34,512 | def forward_mercator(lonlat):
x = ((lonlat[0] * 20037508.34) / 180)
try:
n = math.tan((((90 + lonlat[1]) * math.pi) / 360))
except ValueError:
n = 0
if (n <= 0):
y = float('-inf')
else:
y = ((math.log(n) / math.pi) * 20037508.34)
return (x, y)
| [
"def",
"forward_mercator",
"(",
"lonlat",
")",
":",
"x",
"=",
"(",
"(",
"lonlat",
"[",
"0",
"]",
"*",
"20037508.34",
")",
"/",
"180",
")",
"try",
":",
"n",
"=",
"math",
".",
"tan",
"(",
"(",
"(",
"(",
"90",
"+",
"lonlat",
"[",
"1",
"]",
")",
... | given geographic coordinates . | train | true |
34,513 | def url_argument_spec():
return dict(url=dict(), force=dict(default='no', aliases=['thirsty'], type='bool'), http_agent=dict(default='ansible-httpget'), use_proxy=dict(default='yes', type='bool'), validate_certs=dict(default='yes', type='bool'), url_username=dict(required=False), url_password=dict(required=False), for... | [
"def",
"url_argument_spec",
"(",
")",
":",
"return",
"dict",
"(",
"url",
"=",
"dict",
"(",
")",
",",
"force",
"=",
"dict",
"(",
"default",
"=",
"'no'",
",",
"aliases",
"=",
"[",
"'thirsty'",
"]",
",",
"type",
"=",
"'bool'",
")",
",",
"http_agent",
... | creates an argument spec that can be used with any module that will be requesting content via urllib/urllib2 . | train | false |
34,514 | def getXMLLines(text):
accumulatedOutput = None
textLines = archive.getTextLines(text)
combinedLines = []
lastWord = '>'
for textLine in textLines:
strippedLine = textLine.strip()
firstCharacter = None
lastCharacter = None
if (len(strippedLine) > 1):
firstCharacter = strippedLine[0]
lastCharacter = s... | [
"def",
"getXMLLines",
"(",
"text",
")",
":",
"accumulatedOutput",
"=",
"None",
"textLines",
"=",
"archive",
".",
"getTextLines",
"(",
"text",
")",
"combinedLines",
"=",
"[",
"]",
"lastWord",
"=",
"'>'",
"for",
"textLine",
"in",
"textLines",
":",
"strippedLin... | get the all the xml lines of a text . | train | false |
34,515 | def testfunction(self):
return self
| [
"def",
"testfunction",
"(",
"self",
")",
":",
"return",
"self"
] | some doc . | train | false |
34,516 | def deduplicate_regions(region, dup_region):
cities = dup_region.city_set.all()
if cities.exists():
cities.update(region=region)
users = dup_region.userprofile_set.all()
if users.exists():
users.update(geo_region=region)
dup_region.delete()
| [
"def",
"deduplicate_regions",
"(",
"region",
",",
"dup_region",
")",
":",
"cities",
"=",
"dup_region",
".",
"city_set",
".",
"all",
"(",
")",
"if",
"cities",
".",
"exists",
"(",
")",
":",
"cities",
".",
"update",
"(",
"region",
"=",
"region",
")",
"use... | given 2 country instances . | train | false |
34,517 | def _xmlcharref_encode(unicode_data, encoding):
chars = []
for char in unicode_data:
try:
chars.append(char.encode(encoding, u'strict'))
except UnicodeError:
chars.append((u'&#%i;' % ord(char)))
return u''.join(chars)
| [
"def",
"_xmlcharref_encode",
"(",
"unicode_data",
",",
"encoding",
")",
":",
"chars",
"=",
"[",
"]",
"for",
"char",
"in",
"unicode_data",
":",
"try",
":",
"chars",
".",
"append",
"(",
"char",
".",
"encode",
"(",
"encoding",
",",
"u'strict'",
")",
")",
... | emulate python 2 . | train | false |
34,518 | @profiler.trace
def can_set_mount_point():
hypervisor_features = getattr(settings, 'OPENSTACK_HYPERVISOR_FEATURES', {})
return hypervisor_features.get('can_set_mount_point', False)
| [
"@",
"profiler",
".",
"trace",
"def",
"can_set_mount_point",
"(",
")",
":",
"hypervisor_features",
"=",
"getattr",
"(",
"settings",
",",
"'OPENSTACK_HYPERVISOR_FEATURES'",
",",
"{",
"}",
")",
"return",
"hypervisor_features",
".",
"get",
"(",
"'can_set_mount_point'",... | return the hypervisors capability of setting mount points . | train | false |
34,519 | @receiver(post_save, sender=Source)
def update_source(sender, instance, **kwargs):
related_units = Unit.objects.filter(checksum=instance.checksum, translation__subproject=instance.subproject)
if instance.priority_modified:
units = related_units.exclude(priority=instance.priority)
units.update(priority=instance.pr... | [
"@",
"receiver",
"(",
"post_save",
",",
"sender",
"=",
"Source",
")",
"def",
"update_source",
"(",
"sender",
",",
"instance",
",",
"**",
"kwargs",
")",
":",
"related_units",
"=",
"Unit",
".",
"objects",
".",
"filter",
"(",
"checksum",
"=",
"instance",
".... | updates unit priority or checks based on source change . | train | false |
34,521 | def GetObject(Pathname=None, Class=None, clsctx=None):
if (clsctx is None):
clsctx = pythoncom.CLSCTX_ALL
if (((Pathname is None) and (Class is None)) or ((Pathname is not None) and (Class is not None))):
raise ValueError('You must specify a value for Pathname or Class, but not both.')
if (Class is not None):
... | [
"def",
"GetObject",
"(",
"Pathname",
"=",
"None",
",",
"Class",
"=",
"None",
",",
"clsctx",
"=",
"None",
")",
":",
"if",
"(",
"clsctx",
"is",
"None",
")",
":",
"clsctx",
"=",
"pythoncom",
".",
"CLSCTX_ALL",
"if",
"(",
"(",
"(",
"Pathname",
"is",
"N... | mimic vbs getobject() function . | train | false |
34,522 | def testng(registry, xml_parent, data):
reporter = XML.SubElement(xml_parent, 'hudson.plugins.testng.Publisher')
reporter.set('plugin', 'testng-plugin')
threshold_modes = {'number': 1, 'percentage': 2}
mappings = [('pattern', 'reportFilenamePattern', None), ('escape-test-description', 'escapeTestDescp', True), ('es... | [
"def",
"testng",
"(",
"registry",
",",
"xml_parent",
",",
"data",
")",
":",
"reporter",
"=",
"XML",
".",
"SubElement",
"(",
"xml_parent",
",",
"'hudson.plugins.testng.Publisher'",
")",
"reporter",
".",
"set",
"(",
"'plugin'",
",",
"'testng-plugin'",
")",
"thre... | yaml: testng this plugin publishes testng test reports . | train | false |
34,523 | def expand_level_metadata(metadata):
if isinstance(metadata, compat.string_type):
metadata = {'name': metadata, 'attributes': [metadata]}
else:
metadata = dict(metadata)
try:
name = metadata['name']
except KeyError:
raise ModelError('Level has no name')
attributes = metadata.get('attributes')
if (not attr... | [
"def",
"expand_level_metadata",
"(",
"metadata",
")",
":",
"if",
"isinstance",
"(",
"metadata",
",",
"compat",
".",
"string_type",
")",
":",
"metadata",
"=",
"{",
"'name'",
":",
"metadata",
",",
"'attributes'",
":",
"[",
"metadata",
"]",
"}",
"else",
":",
... | returns a level description as a dictionary . | train | false |
34,524 | def best_match_language(req):
if (not req.accept_language):
return None
return req.accept_language.best_match(oslo_i18n.get_available_languages('keystone'))
| [
"def",
"best_match_language",
"(",
"req",
")",
":",
"if",
"(",
"not",
"req",
".",
"accept_language",
")",
":",
"return",
"None",
"return",
"req",
".",
"accept_language",
".",
"best_match",
"(",
"oslo_i18n",
".",
"get_available_languages",
"(",
"'keystone'",
")... | determine the best available locale . | train | false |
34,525 | def mangle_args_c(argtys):
return ''.join([mangle_type_c(t) for t in argtys])
| [
"def",
"mangle_args_c",
"(",
"argtys",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"mangle_type_c",
"(",
"t",
")",
"for",
"t",
"in",
"argtys",
"]",
")"
] | mangle sequence of c type names . | train | false |
34,526 | def _get_queue_arguments(conf):
return ({'x-ha-policy': 'all'} if conf.rabbit_ha_queues else {})
| [
"def",
"_get_queue_arguments",
"(",
"conf",
")",
":",
"return",
"(",
"{",
"'x-ha-policy'",
":",
"'all'",
"}",
"if",
"conf",
".",
"rabbit_ha_queues",
"else",
"{",
"}",
")"
] | construct the arguments for declaring a queue . | train | false |
34,527 | def default_selem(func):
@functools.wraps(func)
def func_out(image, selem=None, *args, **kwargs):
if (selem is None):
selem = _default_selem(image.ndim)
return func(image, selem=selem, *args, **kwargs)
return func_out
| [
"def",
"default_selem",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"func_out",
"(",
"image",
",",
"selem",
"=",
"None",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"selem",
"is",
"None",
")",
"... | decorator to add a default structuring element to morphology functions . | train | false |
34,528 | def test_sensitivity_specificity_f_binary_single_class():
assert_equal(1.0, sensitivity_score([1, 1], [1, 1]))
assert_equal(0.0, specificity_score([1, 1], [1, 1]))
assert_equal(0.0, sensitivity_score([(-1), (-1)], [(-1), (-1)]))
assert_equal(0.0, specificity_score([(-1), (-1)], [(-1), (-1)]))
| [
"def",
"test_sensitivity_specificity_f_binary_single_class",
"(",
")",
":",
"assert_equal",
"(",
"1.0",
",",
"sensitivity_score",
"(",
"[",
"1",
",",
"1",
"]",
",",
"[",
"1",
",",
"1",
"]",
")",
")",
"assert_equal",
"(",
"0.0",
",",
"specificity_score",
"(",... | test sensitivity and specificity behave with a single positive or negative class . | train | false |
34,531 | def _cygcheck(args, cyg_arch='x86_64'):
cmd = ' '.join([os.sep.join(['c:', _get_cyg_dir(cyg_arch), 'bin', 'cygcheck']), '-c', args])
ret = __salt__['cmd.run_all'](cmd)
if (ret['retcode'] == 0):
return ret['stdout']
else:
return False
| [
"def",
"_cygcheck",
"(",
"args",
",",
"cyg_arch",
"=",
"'x86_64'",
")",
":",
"cmd",
"=",
"' '",
".",
"join",
"(",
"[",
"os",
".",
"sep",
".",
"join",
"(",
"[",
"'c:'",
",",
"_get_cyg_dir",
"(",
"cyg_arch",
")",
",",
"'bin'",
",",
"'cygcheck'",
"]",... | run the cygcheck executable . | train | true |
34,534 | def test_install_exit_status_code_when_no_requirements(script):
result = script.pip('install', expect_error=True)
assert ('You must give at least one requirement to install' in result.stderr)
assert (result.returncode == ERROR)
| [
"def",
"test_install_exit_status_code_when_no_requirements",
"(",
"script",
")",
":",
"result",
"=",
"script",
".",
"pip",
"(",
"'install'",
",",
"expect_error",
"=",
"True",
")",
"assert",
"(",
"'You must give at least one requirement to install'",
"in",
"result",
".",... | test install exit status code when no requirements specified . | train | false |
34,535 | def write_pot_file(potfile, msgs):
pot_lines = msgs.splitlines()
if os.path.exists(potfile):
lines = dropwhile(len, pot_lines)
else:
lines = []
(found, header_read) = (False, False)
for line in pot_lines:
if ((not found) and (not header_read)):
found = True
line = line.replace('charset=CHARSET', '... | [
"def",
"write_pot_file",
"(",
"potfile",
",",
"msgs",
")",
":",
"pot_lines",
"=",
"msgs",
".",
"splitlines",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"potfile",
")",
":",
"lines",
"=",
"dropwhile",
"(",
"len",
",",
"pot_lines",
")",
"el... | write the . | train | false |
34,536 | def skype(msg):
cmd = (('tell app "Skype" to send command "' + msg) + '" script name "Alfred"')
p = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
(stdout, stderr) = p.communicate(cmd)
return stdout
| [
"def",
"skype",
"(",
"msg",
")",
":",
"cmd",
"=",
"(",
"(",
"'tell app \"Skype\" to send command \"'",
"+",
"msg",
")",
"+",
"'\" script name \"Alfred\"'",
")",
"p",
"=",
"Popen",
"(",
"[",
"'osascript'",
",",
"'-'",
"]",
",",
"stdin",
"=",
"PIPE",
",",
... | sends message to skype . | train | false |
34,537 | def smithbr():
try:
show_list = requests.get('https://raw.github.com/svendahlstrand/couchpotato/master/shows.json').json()
random_show = random.randint(0, len(show_list))
print ('Do you have %s of free time today? Check out an episode of %s!' % (show_list[random_show]['run time'], show_list[random_show]['title']... | [
"def",
"smithbr",
"(",
")",
":",
"try",
":",
"show_list",
"=",
"requests",
".",
"get",
"(",
"'https://raw.github.com/svendahlstrand/couchpotato/master/shows.json'",
")",
".",
"json",
"(",
")",
"random_show",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"len",
... | suggests a new tv show to watch . | train | false |
34,538 | def search_player_tag(key=None, category=None):
return PlayerDB.objects.get_by_tag(key=key, category=category)
| [
"def",
"search_player_tag",
"(",
"key",
"=",
"None",
",",
"category",
"=",
"None",
")",
":",
"return",
"PlayerDB",
".",
"objects",
".",
"get_by_tag",
"(",
"key",
"=",
"key",
",",
"category",
"=",
"category",
")"
] | find player based on tag or category . | train | false |
34,539 | def _ScrubItem(dict, item_name):
if (item_name in dict):
dict[item_name] = ('...scrubbed %s bytes...' % len(dict[item_name]))
| [
"def",
"_ScrubItem",
"(",
"dict",
",",
"item_name",
")",
":",
"if",
"(",
"item_name",
"in",
"dict",
")",
":",
"dict",
"[",
"item_name",
"]",
"=",
"(",
"'...scrubbed %s bytes...'",
"%",
"len",
"(",
"dict",
"[",
"item_name",
"]",
")",
")"
] | replace value of dict[item_name] with scrubbed text . | train | false |
34,541 | def mattrgetter(*attrs):
return (lambda obj: dict(((attr, getattr(obj, attr, None)) for attr in attrs)))
| [
"def",
"mattrgetter",
"(",
"*",
"attrs",
")",
":",
"return",
"(",
"lambda",
"obj",
":",
"dict",
"(",
"(",
"(",
"attr",
",",
"getattr",
"(",
"obj",
",",
"attr",
",",
"None",
")",
")",
"for",
"attr",
"in",
"attrs",
")",
")",
")"
] | get attributes . | train | false |
34,542 | def generate_youtube_embed(video_id):
return render_to_string('wikiparser/hook_youtube_embed.html', {'video_id': video_id})
| [
"def",
"generate_youtube_embed",
"(",
"video_id",
")",
":",
"return",
"render_to_string",
"(",
"'wikiparser/hook_youtube_embed.html'",
",",
"{",
"'video_id'",
":",
"video_id",
"}",
")"
] | takes a youtube video id and returns the embed markup . | train | false |
34,543 | def populate_uuids(apps, schema_editor):
Document = apps.get_model(u'wiki', u'Document')
docs = Document.objects.filter(uuid__isnull=True)
for document_id in docs.values_list(u'id', flat=True).iterator():
Document.objects.filter(id=document_id).update(uuid=uuid4())
| [
"def",
"populate_uuids",
"(",
"apps",
",",
"schema_editor",
")",
":",
"Document",
"=",
"apps",
".",
"get_model",
"(",
"u'wiki'",
",",
"u'Document'",
")",
"docs",
"=",
"Document",
".",
"objects",
".",
"filter",
"(",
"uuid__isnull",
"=",
"True",
")",
"for",
... | populate document . | train | false |
34,544 | def excluded(self, filename):
basename = os.path.basename(filename)
return any((pep8.filename_match(filename, self.options.exclude, default=False), pep8.filename_match(basename, self.options.exclude, default=False)))
| [
"def",
"excluded",
"(",
"self",
",",
"filename",
")",
":",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"return",
"any",
"(",
"(",
"pep8",
".",
"filename_match",
"(",
"filename",
",",
"self",
".",
"options",
".",
"exclude"... | check if options . | train | false |
34,545 | def ntToPosixSlashes(filepath):
return filepath.replace('\\', '/')
| [
"def",
"ntToPosixSlashes",
"(",
"filepath",
")",
":",
"return",
"filepath",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")"
] | replaces all occurances of nt slashes () in provided filepath with posix ones (/) . | train | false |
34,546 | def set_next_date(doc, posting_date):
if (not doc.repeat_on_day_of_month):
msgprint(_(u"Please enter 'Repeat on Day of Month' field value"), raise_exception=1)
next_date = get_next_date(posting_date, month_map[doc.recurring_type], cint(doc.repeat_on_day_of_month))
doc.db_set(u'next_date', next_date)
msgprint(_(u'... | [
"def",
"set_next_date",
"(",
"doc",
",",
"posting_date",
")",
":",
"if",
"(",
"not",
"doc",
".",
"repeat_on_day_of_month",
")",
":",
"msgprint",
"(",
"_",
"(",
"u\"Please enter 'Repeat on Day of Month' field value\"",
")",
",",
"raise_exception",
"=",
"1",
")",
... | set next date on which recurring document will be created . | train | false |
34,547 | def dcross(**keywords):
keys = keywords.keys()
sequences = [keywords[key] for key in keys]
wheels = map(iter, sequences)
digits = [it.next() for it in wheels]
while True:
(yield dict(zip(keys, digits)))
for i in range((len(digits) - 1), (-1), (-1)):
try:
digits[i] = wheels[i].next()
break
except ... | [
"def",
"dcross",
"(",
"**",
"keywords",
")",
":",
"keys",
"=",
"keywords",
".",
"keys",
"(",
")",
"sequences",
"=",
"[",
"keywords",
"[",
"key",
"]",
"for",
"key",
"in",
"keys",
"]",
"wheels",
"=",
"map",
"(",
"iter",
",",
"sequences",
")",
"digits... | similar to cross() . | train | true |
34,548 | def urlsafe_base64_decode(s):
s = s.encode(u'utf-8')
try:
return base64.urlsafe_b64decode(s.ljust((len(s) + (len(s) % 4)), '='))
except (LookupError, BinasciiError) as e:
raise ValueError(e)
| [
"def",
"urlsafe_base64_decode",
"(",
"s",
")",
":",
"s",
"=",
"s",
".",
"encode",
"(",
"u'utf-8'",
")",
"try",
":",
"return",
"base64",
".",
"urlsafe_b64decode",
"(",
"s",
".",
"ljust",
"(",
"(",
"len",
"(",
"s",
")",
"+",
"(",
"len",
"(",
"s",
"... | decodes a base64 encoded string . | train | false |
34,550 | def _activate_env_from_path(env_path):
prev_sys_path = list(sys.path)
if (sys.platform == 'win32'):
site_packages_paths = [os.path.join(env_path, 'Lib', 'site-packages')]
else:
lib_path = os.path.join(env_path, 'lib')
site_packages_paths = [os.path.join(lib_path, lib, 'site-packages') for lib in os.listdir(lib... | [
"def",
"_activate_env_from_path",
"(",
"env_path",
")",
":",
"prev_sys_path",
"=",
"list",
"(",
"sys",
".",
"path",
")",
"if",
"(",
"sys",
".",
"platform",
"==",
"'win32'",
")",
":",
"site_packages_paths",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
... | fix when activate_this . | train | false |
34,551 | def case_type():
return s3_rest_controller()
| [
"def",
"case_type",
"(",
")",
":",
"return",
"s3_rest_controller",
"(",
")"
] | case types: restful crud controller . | train | false |
34,552 | def _add_candidate(items, results, info):
log.debug(u'Candidate: {0} - {1}'.format(info.artist, info.album))
if (not info.tracks):
log.debug('No tracks.')
return
if (info.album_id in results):
log.debug(u'Duplicate.')
return
for req_tag in config['match']['required'].as_str_seq():
if (getattr(info, req_ta... | [
"def",
"_add_candidate",
"(",
"items",
",",
"results",
",",
"info",
")",
":",
"log",
".",
"debug",
"(",
"u'Candidate: {0} - {1}'",
".",
"format",
"(",
"info",
".",
"artist",
",",
"info",
".",
"album",
")",
")",
"if",
"(",
"not",
"info",
".",
"tracks",
... | given a candidate albuminfo object . | train | false |
34,553 | def init_leases(network_id):
ctxt = context.get_admin_context()
network = objects.Network.get_by_id(ctxt, network_id)
network_manager = importutils.import_object(CONF.network_manager)
return network_manager.get_dhcp_leases(ctxt, network)
| [
"def",
"init_leases",
"(",
"network_id",
")",
":",
"ctxt",
"=",
"context",
".",
"get_admin_context",
"(",
")",
"network",
"=",
"objects",
".",
"Network",
".",
"get_by_id",
"(",
"ctxt",
",",
"network_id",
")",
"network_manager",
"=",
"importutils",
".",
"impo... | get the list of hosts for a network . | train | false |
34,554 | def seek_end_of_dict(module_data, start_line, start_col, next_node_line, next_node_col):
if (next_node_line == None):
snippet = module_data.splitlines()[start_line:]
next_node_col = 0
last_line_offset = 0
else:
snippet = module_data.splitlines()[start_line:next_node_line]
last_line_offset = 1
if (next_node... | [
"def",
"seek_end_of_dict",
"(",
"module_data",
",",
"start_line",
",",
"start_col",
",",
"next_node_line",
",",
"next_node_col",
")",
":",
"if",
"(",
"next_node_line",
"==",
"None",
")",
":",
"snippet",
"=",
"module_data",
".",
"splitlines",
"(",
")",
"[",
"... | look for the end of a dict in a set of lines we know the starting position of the dict and we know the start of the next code node but in between there may be multiple newlines and comments . | train | false |
34,555 | def monitor_del_global(sock, name):
return communicate(sock, ('__del_global__("%s")' % name))
| [
"def",
"monitor_del_global",
"(",
"sock",
",",
"name",
")",
":",
"return",
"communicate",
"(",
"sock",
",",
"(",
"'__del_global__(\"%s\")'",
"%",
"name",
")",
")"
] | del global variable *name* . | train | false |
34,557 | def assert_mode_755(mode):
assert ((mode & stat.S_IROTH) and (mode & stat.S_IRGRP) and (mode & stat.S_IXOTH) and (mode & stat.S_IXGRP))
assert ((mode & stat.S_IWUSR) and (mode & stat.S_IRUSR) and (mode & stat.S_IXUSR))
| [
"def",
"assert_mode_755",
"(",
"mode",
")",
":",
"assert",
"(",
"(",
"mode",
"&",
"stat",
".",
"S_IROTH",
")",
"and",
"(",
"mode",
"&",
"stat",
".",
"S_IRGRP",
")",
"and",
"(",
"mode",
"&",
"stat",
".",
"S_IXOTH",
")",
"and",
"(",
"mode",
"&",
"s... | verify given mode is 755 . | train | false |
34,558 | def rand_text_alpha_lower(length, bad=''):
return rand_base(length, bad, set(lowerAlpha))
| [
"def",
"rand_text_alpha_lower",
"(",
"length",
",",
"bad",
"=",
"''",
")",
":",
"return",
"rand_base",
"(",
"length",
",",
"bad",
",",
"set",
"(",
"lowerAlpha",
")",
")"
] | generate a random lower string with alpha chars . | train | false |
34,559 | def get_keys(keynames=None, filters=None, region=None, key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
keys = conn.get_all_key_pairs(keynames, filters)
log.debug('the key to return is : {0}'.format(keys))
key_values = []
if keys:
for key in k... | [
"def",
"get_keys",
"(",
"keynames",
"=",
"None",
",",
"filters",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"regi... | for cross compatibility between python 2 and python 3 dictionaries . | train | true |
34,560 | def partition_is(dev):
return ceph_cfg.partition_is(dev)
| [
"def",
"partition_is",
"(",
"dev",
")",
":",
"return",
"ceph_cfg",
".",
"partition_is",
"(",
"dev",
")"
] | check whether a given device path is a partition or a full disk . | train | false |
34,561 | def do_exit(actions):
for action_group in actions:
if (len(action_group.destroy) > 0):
raise SystemExit(1)
| [
"def",
"do_exit",
"(",
"actions",
")",
":",
"for",
"action_group",
"in",
"actions",
":",
"if",
"(",
"len",
"(",
"action_group",
".",
"destroy",
")",
">",
"0",
")",
":",
"raise",
"SystemExit",
"(",
"1",
")"
] | if resources are destroyed . | train | false |
34,563 | def get_locale_identifier(tup, sep='_'):
tup = tuple(tup[:4])
(lang, territory, script, variant) = (tup + ((None,) * (4 - len(tup))))
return sep.join(filter(None, (lang, script, territory, variant)))
| [
"def",
"get_locale_identifier",
"(",
"tup",
",",
"sep",
"=",
"'_'",
")",
":",
"tup",
"=",
"tuple",
"(",
"tup",
"[",
":",
"4",
"]",
")",
"(",
"lang",
",",
"territory",
",",
"script",
",",
"variant",
")",
"=",
"(",
"tup",
"+",
"(",
"(",
"None",
"... | the reverse of :func:parse_locale . | train | false |
34,564 | def check_error(when='periodic check'):
errors = []
while True:
err = glGetError()
if ((err == GL_NO_ERROR) or (errors and (err == errors[(-1)]))):
break
errors.append(err)
if errors:
msg = ', '.join([repr(ENUM_MAP.get(e, e)) for e in errors])
err = RuntimeError(('OpenGL got errors (%s): %s' % (when, ms... | [
"def",
"check_error",
"(",
"when",
"=",
"'periodic check'",
")",
":",
"errors",
"=",
"[",
"]",
"while",
"True",
":",
"err",
"=",
"glGetError",
"(",
")",
"if",
"(",
"(",
"err",
"==",
"GL_NO_ERROR",
")",
"or",
"(",
"errors",
"and",
"(",
"err",
"==",
... | check this from time to time to detect gl errors . | train | true |
34,566 | def get_load_per_cpu(_stats=None):
stats = []
f_stat = open('/proc/stat', 'r')
if _stats:
for i in range(len(_stats)):
stats.append((int(f_stat.readline().split()[1]) - _stats[i]))
else:
line = f_stat.readline()
while line:
if line.startswith('cpu'):
stats.append(int(line.split()[1]))
else:
b... | [
"def",
"get_load_per_cpu",
"(",
"_stats",
"=",
"None",
")",
":",
"stats",
"=",
"[",
"]",
"f_stat",
"=",
"open",
"(",
"'/proc/stat'",
",",
"'r'",
")",
"if",
"_stats",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"_stats",
")",
")",
":",
"stats",... | gather load per cpu from /proc/stat . | train | false |
34,567 | def parse_private_key(s):
if pemSniff(s, 'PRIVATE KEY'):
bytes = dePem(s, 'PRIVATE KEY')
return _parsePKCS8(bytes)
elif pemSniff(s, 'RSA PRIVATE KEY'):
bytes = dePem(s, 'RSA PRIVATE KEY')
return _parseSSLeay(bytes)
else:
raise SyntaxError('Not a PEM private key file')
| [
"def",
"parse_private_key",
"(",
"s",
")",
":",
"if",
"pemSniff",
"(",
"s",
",",
"'PRIVATE KEY'",
")",
":",
"bytes",
"=",
"dePem",
"(",
"s",
",",
"'PRIVATE KEY'",
")",
"return",
"_parsePKCS8",
"(",
"bytes",
")",
"elif",
"pemSniff",
"(",
"s",
",",
"'RSA... | parse a string containing a pem-encoded <privatekey> . | train | false |
34,569 | def check_interaction(fn):
def check_fn(self, *args, **kwargs):
interact_lock.acquire()
try:
if self.filename:
self.clear_interaction()
return fn(self, *args, **kwargs)
finally:
interact_lock.release()
return check_fn
| [
"def",
"check_interaction",
"(",
"fn",
")",
":",
"def",
"check_fn",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"interact_lock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"self",
".",
"filename",
":",
"self",
".",
"clear_interaction... | decorator to clean and prevent interaction when not available . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.