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 |
|---|---|---|---|---|---|
43,077 | def check_ddir(d):
expanded = os.path.expanduser(d)
if os.path.isdir(expanded):
message = ((('Downloads will be saved to ' + c.y) + d) + c.w)
return dict(valid=True, message=message, value=expanded)
else:
message = ((('Not a valid directory: ' + c.r) + d) + c.w)
return dict(valid=False, message=message)
| [
"def",
"check_ddir",
"(",
"d",
")",
":",
"expanded",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"d",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"expanded",
")",
":",
"message",
"=",
"(",
"(",
"(",
"'Downloads will be saved to '",
"+",
"c",
".",
"y",
")",
"+",
"d",
")",
"+",
"c",
".",
"w",
")",
"return",
"dict",
"(",
"valid",
"=",
"True",
",",
"message",
"=",
"message",
",",
"value",
"=",
"expanded",
")",
"else",
":",
"message",
"=",
"(",
"(",
"(",
"'Not a valid directory: '",
"+",
"c",
".",
"r",
")",
"+",
"d",
")",
"+",
"c",
".",
"w",
")",
"return",
"dict",
"(",
"valid",
"=",
"False",
",",
"message",
"=",
"message",
")"
] | check whether dir is a valid directory . | train | false |
43,078 | def johnson_lindenstrauss_min_dim(n_samples, eps=0.1):
eps = np.asarray(eps)
n_samples = np.asarray(n_samples)
if (np.any((eps <= 0.0)) or np.any((eps >= 1))):
raise ValueError(('The JL bound is defined for eps in ]0, 1[, got %r' % eps))
if (np.any(n_samples) <= 0):
raise ValueError(('The JL bound is defined for n_samples greater than zero, got %r' % n_samples))
denominator = (((eps ** 2) / 2) - ((eps ** 3) / 3))
return ((4 * np.log(n_samples)) / denominator).astype(np.int)
| [
"def",
"johnson_lindenstrauss_min_dim",
"(",
"n_samples",
",",
"eps",
"=",
"0.1",
")",
":",
"eps",
"=",
"np",
".",
"asarray",
"(",
"eps",
")",
"n_samples",
"=",
"np",
".",
"asarray",
"(",
"n_samples",
")",
"if",
"(",
"np",
".",
"any",
"(",
"(",
"eps",
"<=",
"0.0",
")",
")",
"or",
"np",
".",
"any",
"(",
"(",
"eps",
">=",
"1",
")",
")",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'The JL bound is defined for eps in ]0, 1[, got %r'",
"%",
"eps",
")",
")",
"if",
"(",
"np",
".",
"any",
"(",
"n_samples",
")",
"<=",
"0",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'The JL bound is defined for n_samples greater than zero, got %r'",
"%",
"n_samples",
")",
")",
"denominator",
"=",
"(",
"(",
"(",
"eps",
"**",
"2",
")",
"/",
"2",
")",
"-",
"(",
"(",
"eps",
"**",
"3",
")",
"/",
"3",
")",
")",
"return",
"(",
"(",
"4",
"*",
"np",
".",
"log",
"(",
"n_samples",
")",
")",
"/",
"denominator",
")",
".",
"astype",
"(",
"np",
".",
"int",
")"
] | find a safe number of components to randomly project to the distortion introduced by a random projection p only changes the distance between two points by a factor in an euclidean space with good probability . | train | false |
43,081 | def sum_percentile(image, selem, out=None, mask=None, shift_x=False, shift_y=False, p0=0, p1=1):
return _apply(percentile_cy._sum, image, selem, out=out, mask=mask, shift_x=shift_x, shift_y=shift_y, p0=p0, p1=p1)
| [
"def",
"sum_percentile",
"(",
"image",
",",
"selem",
",",
"out",
"=",
"None",
",",
"mask",
"=",
"None",
",",
"shift_x",
"=",
"False",
",",
"shift_y",
"=",
"False",
",",
"p0",
"=",
"0",
",",
"p1",
"=",
"1",
")",
":",
"return",
"_apply",
"(",
"percentile_cy",
".",
"_sum",
",",
"image",
",",
"selem",
",",
"out",
"=",
"out",
",",
"mask",
"=",
"mask",
",",
"shift_x",
"=",
"shift_x",
",",
"shift_y",
"=",
"shift_y",
",",
"p0",
"=",
"p0",
",",
"p1",
"=",
"p1",
")"
] | return the local sum of pixels . | train | false |
43,083 | def get_ccx_by_ccx_id(course, coach, ccx_id):
try:
ccx = CustomCourseForEdX.objects.get(id=ccx_id, course_id=course.id, coach=coach)
except CustomCourseForEdX.DoesNotExist:
return None
return ccx
| [
"def",
"get_ccx_by_ccx_id",
"(",
"course",
",",
"coach",
",",
"ccx_id",
")",
":",
"try",
":",
"ccx",
"=",
"CustomCourseForEdX",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"ccx_id",
",",
"course_id",
"=",
"course",
".",
"id",
",",
"coach",
"=",
"coach",
")",
"except",
"CustomCourseForEdX",
".",
"DoesNotExist",
":",
"return",
"None",
"return",
"ccx"
] | finds a ccx of given coach on given master course . | train | false |
43,084 | @require_POST
@login_required
def unwatch_locale(request, product=None):
kwargs = {'locale': request.LANGUAGE_CODE}
if (product is not None):
kwargs['product'] = product
ReviewableRevisionInLocaleEvent.stop_notifying(request.user, **kwargs)
return HttpResponse()
| [
"@",
"require_POST",
"@",
"login_required",
"def",
"unwatch_locale",
"(",
"request",
",",
"product",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"'locale'",
":",
"request",
".",
"LANGUAGE_CODE",
"}",
"if",
"(",
"product",
"is",
"not",
"None",
")",
":",
"kwargs",
"[",
"'product'",
"]",
"=",
"product",
"ReviewableRevisionInLocaleEvent",
".",
"stop_notifying",
"(",
"request",
".",
"user",
",",
"**",
"kwargs",
")",
"return",
"HttpResponse",
"(",
")"
] | stop watching a locale for revisions ready for review . | train | false |
43,085 | def binom_test_reject_interval(value, nobs, alpha=0.05, alternative='two-sided'):
if (alternative in ['2s', 'two-sided']):
alternative = '2s'
alpha = (alpha / 2)
if (alternative in ['2s', 'smaller']):
x_low = (stats.binom.ppf(alpha, nobs, value) - 1)
else:
x_low = 0
if (alternative in ['2s', 'larger']):
x_upp = (stats.binom.isf(alpha, nobs, value) + 1)
else:
x_upp = nobs
return (x_low, x_upp)
| [
"def",
"binom_test_reject_interval",
"(",
"value",
",",
"nobs",
",",
"alpha",
"=",
"0.05",
",",
"alternative",
"=",
"'two-sided'",
")",
":",
"if",
"(",
"alternative",
"in",
"[",
"'2s'",
",",
"'two-sided'",
"]",
")",
":",
"alternative",
"=",
"'2s'",
"alpha",
"=",
"(",
"alpha",
"/",
"2",
")",
"if",
"(",
"alternative",
"in",
"[",
"'2s'",
",",
"'smaller'",
"]",
")",
":",
"x_low",
"=",
"(",
"stats",
".",
"binom",
".",
"ppf",
"(",
"alpha",
",",
"nobs",
",",
"value",
")",
"-",
"1",
")",
"else",
":",
"x_low",
"=",
"0",
"if",
"(",
"alternative",
"in",
"[",
"'2s'",
",",
"'larger'",
"]",
")",
":",
"x_upp",
"=",
"(",
"stats",
".",
"binom",
".",
"isf",
"(",
"alpha",
",",
"nobs",
",",
"value",
")",
"+",
"1",
")",
"else",
":",
"x_upp",
"=",
"nobs",
"return",
"(",
"x_low",
",",
"x_upp",
")"
] | rejection region for binomial test for one sample proportion the interval includes the end points of the rejection region . | train | false |
43,086 | @register.inclusion_tag('inclusion.html')
def inclusion_one_param(arg):
return {'result': ('inclusion_one_param - Expected result: %s' % arg)}
| [
"@",
"register",
".",
"inclusion_tag",
"(",
"'inclusion.html'",
")",
"def",
"inclusion_one_param",
"(",
"arg",
")",
":",
"return",
"{",
"'result'",
":",
"(",
"'inclusion_one_param - Expected result: %s'",
"%",
"arg",
")",
"}"
] | expected inclusion_one_param __doc__ . | train | false |
43,090 | def fadein(clip, duration, initial_color=None):
if (initial_color is None):
initial_color = (0 if clip.ismask else [0, 0, 0])
initial_color = np.array(initial_color)
def fl(gf, t):
if (t >= duration):
return gf(t)
else:
fading = ((1.0 * t) / duration)
return ((fading * gf(t)) + ((1 - fading) * initial_color))
return clip.fl(fl)
| [
"def",
"fadein",
"(",
"clip",
",",
"duration",
",",
"initial_color",
"=",
"None",
")",
":",
"if",
"(",
"initial_color",
"is",
"None",
")",
":",
"initial_color",
"=",
"(",
"0",
"if",
"clip",
".",
"ismask",
"else",
"[",
"0",
",",
"0",
",",
"0",
"]",
")",
"initial_color",
"=",
"np",
".",
"array",
"(",
"initial_color",
")",
"def",
"fl",
"(",
"gf",
",",
"t",
")",
":",
"if",
"(",
"t",
">=",
"duration",
")",
":",
"return",
"gf",
"(",
"t",
")",
"else",
":",
"fading",
"=",
"(",
"(",
"1.0",
"*",
"t",
")",
"/",
"duration",
")",
"return",
"(",
"(",
"fading",
"*",
"gf",
"(",
"t",
")",
")",
"+",
"(",
"(",
"1",
"-",
"fading",
")",
"*",
"initial_color",
")",
")",
"return",
"clip",
".",
"fl",
"(",
"fl",
")"
] | makes the clip progressively appear from some color . | train | false |
43,091 | def is_finite(builder, val):
val_minus_val = builder.fsub(val, val)
return builder.fcmp_ordered('ord', val_minus_val, val_minus_val)
| [
"def",
"is_finite",
"(",
"builder",
",",
"val",
")",
":",
"val_minus_val",
"=",
"builder",
".",
"fsub",
"(",
"val",
",",
"val",
")",
"return",
"builder",
".",
"fcmp_ordered",
"(",
"'ord'",
",",
"val_minus_val",
",",
"val_minus_val",
")"
] | return a condition testing whether *val* is a finite . | train | false |
43,092 | def _unit_quat_constraint(x):
return (1 - (x * x).sum())
| [
"def",
"_unit_quat_constraint",
"(",
"x",
")",
":",
"return",
"(",
"1",
"-",
"(",
"x",
"*",
"x",
")",
".",
"sum",
"(",
")",
")"
] | constrain our 3 quaternion rot params to have norm <= 1 . | train | false |
43,093 | def get_num_jobs(not_yet_run=False, running=False, finished=False, **filter_data):
filter_data['extra_args'] = rpc_utils.extra_job_filters(not_yet_run, running, finished)
return models.Job.query_count(filter_data)
| [
"def",
"get_num_jobs",
"(",
"not_yet_run",
"=",
"False",
",",
"running",
"=",
"False",
",",
"finished",
"=",
"False",
",",
"**",
"filter_data",
")",
":",
"filter_data",
"[",
"'extra_args'",
"]",
"=",
"rpc_utils",
".",
"extra_job_filters",
"(",
"not_yet_run",
",",
"running",
",",
"finished",
")",
"return",
"models",
".",
"Job",
".",
"query_count",
"(",
"filter_data",
")"
] | see get_jobs() for documentation of extra filter parameters . | train | false |
43,094 | def bench_R11():
a = [(random() + (random() * I)) for w in range(1000)]
| [
"def",
"bench_R11",
"(",
")",
":",
"a",
"=",
"[",
"(",
"random",
"(",
")",
"+",
"(",
"random",
"(",
")",
"*",
"I",
")",
")",
"for",
"w",
"in",
"range",
"(",
"1000",
")",
"]"
] | a = [random() + random()*i for w in [0 . | train | false |
43,095 | def _norm(x):
return np.sqrt(squared_norm(x))
| [
"def",
"_norm",
"(",
"x",
")",
":",
"return",
"np",
".",
"sqrt",
"(",
"squared_norm",
"(",
"x",
")",
")"
] | return sqrt . | train | false |
43,096 | def __get_ssh_interface(vm_):
return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)
| [
"def",
"__get_ssh_interface",
"(",
"vm_",
")",
":",
"return",
"config",
".",
"get_cloud_config_value",
"(",
"'ssh_interface'",
",",
"vm_",
",",
"__opts__",
",",
"default",
"=",
"'public_ips'",
",",
"search_global",
"=",
"False",
")"
] | return the ssh_interface type to connect to . | train | false |
43,099 | def test_function_execution():
s = '\n def x():\n return str()\n x'
(func, evaluator) = get_definition_and_evaluator(s)
assert (len(evaluator.execute(func)) == 1)
assert (len(evaluator.execute(func)) == 1)
| [
"def",
"test_function_execution",
"(",
")",
":",
"s",
"=",
"'\\n def x():\\n return str()\\n x'",
"(",
"func",
",",
"evaluator",
")",
"=",
"get_definition_and_evaluator",
"(",
"s",
")",
"assert",
"(",
"len",
"(",
"evaluator",
".",
"execute",
"(",
"func",
")",
")",
"==",
"1",
")",
"assert",
"(",
"len",
"(",
"evaluator",
".",
"execute",
"(",
"func",
")",
")",
"==",
"1",
")"
] | weve been having an issue of a mutable list that was changed inside the function execution . | train | false |
43,100 | def _get_connect_string(backend, user='openstack_citest', passwd='openstack_citest', database='openstack_citest'):
if (backend == 'mysql'):
backend = 'mysql+mysqldb'
elif (backend == 'postgres'):
backend = 'postgresql+psycopg2'
return ('%(backend)s://%(user)s:%(passwd)s@localhost/%(database)s' % locals())
| [
"def",
"_get_connect_string",
"(",
"backend",
",",
"user",
"=",
"'openstack_citest'",
",",
"passwd",
"=",
"'openstack_citest'",
",",
"database",
"=",
"'openstack_citest'",
")",
":",
"if",
"(",
"backend",
"==",
"'mysql'",
")",
":",
"backend",
"=",
"'mysql+mysqldb'",
"elif",
"(",
"backend",
"==",
"'postgres'",
")",
":",
"backend",
"=",
"'postgresql+psycopg2'",
"return",
"(",
"'%(backend)s://%(user)s:%(passwd)s@localhost/%(database)s'",
"%",
"locals",
"(",
")",
")"
] | try to get a connection with a very specific set of values . | train | false |
43,101 | @pytest.mark.cmd
@pytest.mark.django_db
def test_export_language(capfd, export_dir, cd_export_dir):
call_command('export', '--language=language0')
(out, err) = capfd.readouterr()
assert ('language0.zip' in out)
assert ('language1.zip' not in out)
| [
"@",
"pytest",
".",
"mark",
".",
"cmd",
"@",
"pytest",
".",
"mark",
".",
"django_db",
"def",
"test_export_language",
"(",
"capfd",
",",
"export_dir",
",",
"cd_export_dir",
")",
":",
"call_command",
"(",
"'export'",
",",
"'--language=language0'",
")",
"(",
"out",
",",
"err",
")",
"=",
"capfd",
".",
"readouterr",
"(",
")",
"assert",
"(",
"'language0.zip'",
"in",
"out",
")",
"assert",
"(",
"'language1.zip'",
"not",
"in",
"out",
")"
] | export a language . | train | false |
43,102 | def thrift_library(name, srcs=[], deps=[], optimize=[], deprecated=False, **kwargs):
thrift_library_target = ThriftLibrary(name, srcs, deps, optimize, deprecated, blade.blade, kwargs)
blade.blade.register_target(thrift_library_target)
| [
"def",
"thrift_library",
"(",
"name",
",",
"srcs",
"=",
"[",
"]",
",",
"deps",
"=",
"[",
"]",
",",
"optimize",
"=",
"[",
"]",
",",
"deprecated",
"=",
"False",
",",
"**",
"kwargs",
")",
":",
"thrift_library_target",
"=",
"ThriftLibrary",
"(",
"name",
",",
"srcs",
",",
"deps",
",",
"optimize",
",",
"deprecated",
",",
"blade",
".",
"blade",
",",
"kwargs",
")",
"blade",
".",
"blade",
".",
"register_target",
"(",
"thrift_library_target",
")"
] | thrift_library target . | train | false |
43,103 | def validate_is_instance(instance, classes):
if (not isinstance(classes, tuple)):
classes = (classes,)
correct_instance = isinstance(instance, classes)
if (not correct_instance):
raise ValueError(('Expected instance type %s found %s' % (classes, type(instance))))
| [
"def",
"validate_is_instance",
"(",
"instance",
",",
"classes",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"classes",
",",
"tuple",
")",
")",
":",
"classes",
"=",
"(",
"classes",
",",
")",
"correct_instance",
"=",
"isinstance",
"(",
"instance",
",",
"classes",
")",
"if",
"(",
"not",
"correct_instance",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'Expected instance type %s found %s'",
"%",
"(",
"classes",
",",
"type",
"(",
"instance",
")",
")",
")",
")"
] | usage validate_is_instance validate_is_instance(a . | train | false |
43,104 | def persist_clipboard():
clipboard = QtWidgets.QApplication.clipboard()
event = QtCore.QEvent(QtCore.QEvent.Clipboard)
QtWidgets.QApplication.sendEvent(clipboard, event)
| [
"def",
"persist_clipboard",
"(",
")",
":",
"clipboard",
"=",
"QtWidgets",
".",
"QApplication",
".",
"clipboard",
"(",
")",
"event",
"=",
"QtCore",
".",
"QEvent",
"(",
"QtCore",
".",
"QEvent",
".",
"Clipboard",
")",
"QtWidgets",
".",
"QApplication",
".",
"sendEvent",
"(",
"clipboard",
",",
"event",
")"
] | persist the clipboard x11 stores only a reference to the clipboard data . | train | false |
43,106 | def _SinglePropertyIndex(prop_name, direction):
index = entity_pb.Index()
prop = index.add_property()
prop.set_name(prop_name)
prop.set_direction(direction)
return index
| [
"def",
"_SinglePropertyIndex",
"(",
"prop_name",
",",
"direction",
")",
":",
"index",
"=",
"entity_pb",
".",
"Index",
"(",
")",
"prop",
"=",
"index",
".",
"add_property",
"(",
")",
"prop",
".",
"set_name",
"(",
"prop_name",
")",
"prop",
".",
"set_direction",
"(",
"direction",
")",
"return",
"index"
] | creates a single property index for the given name and direction . | train | false |
43,108 | def ipStr(ip):
w = ((ip >> 24) & 255)
x = ((ip >> 16) & 255)
y = ((ip >> 8) & 255)
z = (ip & 255)
return ('%i.%i.%i.%i' % (w, x, y, z))
| [
"def",
"ipStr",
"(",
"ip",
")",
":",
"w",
"=",
"(",
"(",
"ip",
">>",
"24",
")",
"&",
"255",
")",
"x",
"=",
"(",
"(",
"ip",
">>",
"16",
")",
"&",
"255",
")",
"y",
"=",
"(",
"(",
"ip",
">>",
"8",
")",
"&",
"255",
")",
"z",
"=",
"(",
"ip",
"&",
"255",
")",
"return",
"(",
"'%i.%i.%i.%i'",
"%",
"(",
"w",
",",
"x",
",",
"y",
",",
"z",
")",
")"
] | generate ip address string from an unsigned int . | train | false |
43,109 | def getOverhangSpan(elementNode):
return getCascadeFloatWithoutSelf((2.0 * getLayerHeight(elementNode)), elementNode, 'overhangSpan')
| [
"def",
"getOverhangSpan",
"(",
"elementNode",
")",
":",
"return",
"getCascadeFloatWithoutSelf",
"(",
"(",
"2.0",
"*",
"getLayerHeight",
"(",
"elementNode",
")",
")",
",",
"elementNode",
",",
"'overhangSpan'",
")"
] | get the overhang span . | train | false |
43,110 | def col_delete(cols_selected):
if (len(cols_selected) < 1):
flash('No collections selected to delete!', 'error')
else:
for source_id in cols_selected:
delete_collection(source_id)
flash(('%s %s deleted' % (len(cols_selected), ('collection' if (len(cols_selected) == 1) else 'collections'))), 'notification')
return redirect(url_for('index'))
| [
"def",
"col_delete",
"(",
"cols_selected",
")",
":",
"if",
"(",
"len",
"(",
"cols_selected",
")",
"<",
"1",
")",
":",
"flash",
"(",
"'No collections selected to delete!'",
",",
"'error'",
")",
"else",
":",
"for",
"source_id",
"in",
"cols_selected",
":",
"delete_collection",
"(",
"source_id",
")",
"flash",
"(",
"(",
"'%s %s deleted'",
"%",
"(",
"len",
"(",
"cols_selected",
")",
",",
"(",
"'collection'",
"if",
"(",
"len",
"(",
"cols_selected",
")",
"==",
"1",
")",
"else",
"'collections'",
")",
")",
")",
",",
"'notification'",
")",
"return",
"redirect",
"(",
"url_for",
"(",
"'index'",
")",
")"
] | deleting multiple collections from the index . | train | false |
43,111 | def partition_by_cut(cut, rag):
nodes1 = [n for (i, n) in enumerate(rag.nodes()) if cut[i]]
nodes2 = [n for (i, n) in enumerate(rag.nodes()) if (not cut[i])]
sub1 = rag.subgraph(nodes1)
sub2 = rag.subgraph(nodes2)
return (sub1, sub2)
| [
"def",
"partition_by_cut",
"(",
"cut",
",",
"rag",
")",
":",
"nodes1",
"=",
"[",
"n",
"for",
"(",
"i",
",",
"n",
")",
"in",
"enumerate",
"(",
"rag",
".",
"nodes",
"(",
")",
")",
"if",
"cut",
"[",
"i",
"]",
"]",
"nodes2",
"=",
"[",
"n",
"for",
"(",
"i",
",",
"n",
")",
"in",
"enumerate",
"(",
"rag",
".",
"nodes",
"(",
")",
")",
"if",
"(",
"not",
"cut",
"[",
"i",
"]",
")",
"]",
"sub1",
"=",
"rag",
".",
"subgraph",
"(",
"nodes1",
")",
"sub2",
"=",
"rag",
".",
"subgraph",
"(",
"nodes2",
")",
"return",
"(",
"sub1",
",",
"sub2",
")"
] | compute resulting subgraphs from given bi-parition . | train | false |
43,113 | def is_running(proxyname):
return {'result': _is_proxy_running(proxyname)}
| [
"def",
"is_running",
"(",
"proxyname",
")",
":",
"return",
"{",
"'result'",
":",
"_is_proxy_running",
"(",
"proxyname",
")",
"}"
] | checks for if a process with a given name is running or not . | train | false |
43,115 | def get_length_audio(audiopath, extension):
try:
audio = AudioSegment.from_file(audiopath, extension.replace('.', ''))
except:
print ('Error in get_length_audio(): %s' % traceback.format_exc())
return None
return int((len(audio) / 1000.0))
| [
"def",
"get_length_audio",
"(",
"audiopath",
",",
"extension",
")",
":",
"try",
":",
"audio",
"=",
"AudioSegment",
".",
"from_file",
"(",
"audiopath",
",",
"extension",
".",
"replace",
"(",
"'.'",
",",
"''",
")",
")",
"except",
":",
"print",
"(",
"'Error in get_length_audio(): %s'",
"%",
"traceback",
".",
"format_exc",
"(",
")",
")",
"return",
"None",
"return",
"int",
"(",
"(",
"len",
"(",
"audio",
")",
"/",
"1000.0",
")",
")"
] | returns length of audio in seconds . | train | false |
43,116 | def update_many(path, points):
if (not points):
return
points = [(int(t), float(v)) for (t, v) in points]
points.sort(key=(lambda p: p[0]), reverse=True)
with open(path, 'r+b', BUFFERING) as fh:
if (CAN_FADVISE and FADVISE_RANDOM):
posix_fadvise(fh.fileno(), 0, 0, POSIX_FADV_RANDOM)
return file_update_many(fh, points)
| [
"def",
"update_many",
"(",
"path",
",",
"points",
")",
":",
"if",
"(",
"not",
"points",
")",
":",
"return",
"points",
"=",
"[",
"(",
"int",
"(",
"t",
")",
",",
"float",
"(",
"v",
")",
")",
"for",
"(",
"t",
",",
"v",
")",
"in",
"points",
"]",
"points",
".",
"sort",
"(",
"key",
"=",
"(",
"lambda",
"p",
":",
"p",
"[",
"0",
"]",
")",
",",
"reverse",
"=",
"True",
")",
"with",
"open",
"(",
"path",
",",
"'r+b'",
",",
"BUFFERING",
")",
"as",
"fh",
":",
"if",
"(",
"CAN_FADVISE",
"and",
"FADVISE_RANDOM",
")",
":",
"posix_fadvise",
"(",
"fh",
".",
"fileno",
"(",
")",
",",
"0",
",",
"0",
",",
"POSIX_FADV_RANDOM",
")",
"return",
"file_update_many",
"(",
"fh",
",",
"points",
")"
] | update_many path is a string points is a list of points . | train | false |
43,118 | def decode_base64_and_inflate(string):
return zlib.decompress(base64.b64decode(string), (-15))
| [
"def",
"decode_base64_and_inflate",
"(",
"string",
")",
":",
"return",
"zlib",
".",
"decompress",
"(",
"base64",
".",
"b64decode",
"(",
"string",
")",
",",
"(",
"-",
"15",
")",
")"
] | base64 decodes and then inflates according to rfc1951 . | train | false |
43,120 | def write_gif_with_image_io(clip, filename, fps=None, opt='wu', loop=0, colors=None, verbose=True):
if (colors is None):
colors = 256
if (not IMAGEIO_FOUND):
raise ImportError("Writing a gif with imageio requires ImageIO installed, with e.g. 'pip install imageio'")
if (fps is None):
fps = clip.fps
quantizer = ('wu' if (opt != 'nq') else 'nq')
writer = imageio.save(filename, duration=(1.0 / fps), quantizer=quantizer, palettesize=colors)
verbose_print(verbose, ('\n[MoviePy] Building file %s with imageio\n' % filename))
for frame in clip.iter_frames(fps=fps, progress_bar=True, dtype='uint8'):
writer.append_data(frame)
| [
"def",
"write_gif_with_image_io",
"(",
"clip",
",",
"filename",
",",
"fps",
"=",
"None",
",",
"opt",
"=",
"'wu'",
",",
"loop",
"=",
"0",
",",
"colors",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"(",
"colors",
"is",
"None",
")",
":",
"colors",
"=",
"256",
"if",
"(",
"not",
"IMAGEIO_FOUND",
")",
":",
"raise",
"ImportError",
"(",
"\"Writing a gif with imageio requires ImageIO installed, with e.g. 'pip install imageio'\"",
")",
"if",
"(",
"fps",
"is",
"None",
")",
":",
"fps",
"=",
"clip",
".",
"fps",
"quantizer",
"=",
"(",
"'wu'",
"if",
"(",
"opt",
"!=",
"'nq'",
")",
"else",
"'nq'",
")",
"writer",
"=",
"imageio",
".",
"save",
"(",
"filename",
",",
"duration",
"=",
"(",
"1.0",
"/",
"fps",
")",
",",
"quantizer",
"=",
"quantizer",
",",
"palettesize",
"=",
"colors",
")",
"verbose_print",
"(",
"verbose",
",",
"(",
"'\\n[MoviePy] Building file %s with imageio\\n'",
"%",
"filename",
")",
")",
"for",
"frame",
"in",
"clip",
".",
"iter_frames",
"(",
"fps",
"=",
"fps",
",",
"progress_bar",
"=",
"True",
",",
"dtype",
"=",
"'uint8'",
")",
":",
"writer",
".",
"append_data",
"(",
"frame",
")"
] | writes the gif with the python library imageio . | train | false |
43,121 | def betweenness_centrality_parallel(G, processes=None):
p = Pool(processes=processes)
node_divisor = (len(p._pool) * 4)
node_chunks = list(chunks(G.nodes(), int((G.order() / node_divisor))))
num_chunks = len(node_chunks)
bt_sc = p.map(_betmap, zip(([G] * num_chunks), ([True] * num_chunks), ([None] * num_chunks), node_chunks))
bt_c = bt_sc[0]
for bt in bt_sc[1:]:
for n in bt:
bt_c[n] += bt[n]
return bt_c
| [
"def",
"betweenness_centrality_parallel",
"(",
"G",
",",
"processes",
"=",
"None",
")",
":",
"p",
"=",
"Pool",
"(",
"processes",
"=",
"processes",
")",
"node_divisor",
"=",
"(",
"len",
"(",
"p",
".",
"_pool",
")",
"*",
"4",
")",
"node_chunks",
"=",
"list",
"(",
"chunks",
"(",
"G",
".",
"nodes",
"(",
")",
",",
"int",
"(",
"(",
"G",
".",
"order",
"(",
")",
"/",
"node_divisor",
")",
")",
")",
")",
"num_chunks",
"=",
"len",
"(",
"node_chunks",
")",
"bt_sc",
"=",
"p",
".",
"map",
"(",
"_betmap",
",",
"zip",
"(",
"(",
"[",
"G",
"]",
"*",
"num_chunks",
")",
",",
"(",
"[",
"True",
"]",
"*",
"num_chunks",
")",
",",
"(",
"[",
"None",
"]",
"*",
"num_chunks",
")",
",",
"node_chunks",
")",
")",
"bt_c",
"=",
"bt_sc",
"[",
"0",
"]",
"for",
"bt",
"in",
"bt_sc",
"[",
"1",
":",
"]",
":",
"for",
"n",
"in",
"bt",
":",
"bt_c",
"[",
"n",
"]",
"+=",
"bt",
"[",
"n",
"]",
"return",
"bt_c"
] | parallel betweenness centrality function . | train | false |
43,122 | def test_world_should_be_able_to_absorb_classs():
assert (not hasattr(world, 'MyClass'))
if (sys.version_info < (2, 6)):
return
class MyClass:
pass
world.absorb(MyClass)
assert hasattr(world, 'MyClass')
assert_equals(world.MyClass, MyClass)
assert isinstance(world.MyClass(), MyClass)
world.spew('MyClass')
assert (not hasattr(world, 'MyClass'))
| [
"def",
"test_world_should_be_able_to_absorb_classs",
"(",
")",
":",
"assert",
"(",
"not",
"hasattr",
"(",
"world",
",",
"'MyClass'",
")",
")",
"if",
"(",
"sys",
".",
"version_info",
"<",
"(",
"2",
",",
"6",
")",
")",
":",
"return",
"class",
"MyClass",
":",
"pass",
"world",
".",
"absorb",
"(",
"MyClass",
")",
"assert",
"hasattr",
"(",
"world",
",",
"'MyClass'",
")",
"assert_equals",
"(",
"world",
".",
"MyClass",
",",
"MyClass",
")",
"assert",
"isinstance",
"(",
"world",
".",
"MyClass",
"(",
")",
",",
"MyClass",
")",
"world",
".",
"spew",
"(",
"'MyClass'",
")",
"assert",
"(",
"not",
"hasattr",
"(",
"world",
",",
"'MyClass'",
")",
")"
] | world should be able to absorb class . | train | false |
43,123 | def export_patchset(start, end, output=u'patches', **kwargs):
return git.format_patch(u'-o', output, ((start + u'^..') + end), **kwargs)
| [
"def",
"export_patchset",
"(",
"start",
",",
"end",
",",
"output",
"=",
"u'patches'",
",",
"**",
"kwargs",
")",
":",
"return",
"git",
".",
"format_patch",
"(",
"u'-o'",
",",
"output",
",",
"(",
"(",
"start",
"+",
"u'^..'",
")",
"+",
"end",
")",
",",
"**",
"kwargs",
")"
] | export patches from start^ to end . | train | false |
43,124 | @contextlib.contextmanager
def try_target_cell(context, cell):
if cell:
with nova_context.target_cell(context, cell) as cell_context:
(yield cell_context)
else:
(yield context)
| [
"@",
"contextlib",
".",
"contextmanager",
"def",
"try_target_cell",
"(",
"context",
",",
"cell",
")",
":",
"if",
"cell",
":",
"with",
"nova_context",
".",
"target_cell",
"(",
"context",
",",
"cell",
")",
"as",
"cell_context",
":",
"(",
"yield",
"cell_context",
")",
"else",
":",
"(",
"yield",
"context",
")"
] | if cell is not none call func with context . | train | false |
43,125 | def _future_completed(future):
exc = future.exception()
if exc:
log.debug('Failed to run task on executor', exc_info=exc)
| [
"def",
"_future_completed",
"(",
"future",
")",
":",
"exc",
"=",
"future",
".",
"exception",
"(",
")",
"if",
"exc",
":",
"log",
".",
"debug",
"(",
"'Failed to run task on executor'",
",",
"exc_info",
"=",
"exc",
")"
] | helper for run_in_executor() . | train | true |
43,126 | def connect_to_zookeeper(hostlist, credentials):
client = KazooClient(hostlist, timeout=5, max_retries=3, auth_data=[('digest', ':'.join(credentials))])
client.make_acl = functools.partial(make_digest_acl, *credentials)
client.start()
return client
| [
"def",
"connect_to_zookeeper",
"(",
"hostlist",
",",
"credentials",
")",
":",
"client",
"=",
"KazooClient",
"(",
"hostlist",
",",
"timeout",
"=",
"5",
",",
"max_retries",
"=",
"3",
",",
"auth_data",
"=",
"[",
"(",
"'digest'",
",",
"':'",
".",
"join",
"(",
"credentials",
")",
")",
"]",
")",
"client",
".",
"make_acl",
"=",
"functools",
".",
"partial",
"(",
"make_digest_acl",
",",
"*",
"credentials",
")",
"client",
".",
"start",
"(",
")",
"return",
"client"
] | create a connection to the zookeeper ensemble . | train | false |
43,127 | def assert_cloudtrail_arn_is_valid(trail_arn):
pattern = re.compile('arn:.+:cloudtrail:.+:\\d{12}:trail/.+')
if (not pattern.match(trail_arn)):
raise ValueError(('Invalid trail ARN provided: %s' % trail_arn))
| [
"def",
"assert_cloudtrail_arn_is_valid",
"(",
"trail_arn",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"'arn:.+:cloudtrail:.+:\\\\d{12}:trail/.+'",
")",
"if",
"(",
"not",
"pattern",
".",
"match",
"(",
"trail_arn",
")",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'Invalid trail ARN provided: %s'",
"%",
"trail_arn",
")",
")"
] | ensures that the arn looks correct . | train | false |
43,128 | def polar_to_cartesian(r, start_angles, end_angles):
cartesian = (lambda r, alpha: ((r * cos(alpha)), (r * sin(alpha))))
points = []
for (r, start, end) in zip(r, start_angles, end_angles):
points.append(cartesian(r, ((end + start) / 2)))
return zip(*points)
| [
"def",
"polar_to_cartesian",
"(",
"r",
",",
"start_angles",
",",
"end_angles",
")",
":",
"cartesian",
"=",
"(",
"lambda",
"r",
",",
"alpha",
":",
"(",
"(",
"r",
"*",
"cos",
"(",
"alpha",
")",
")",
",",
"(",
"r",
"*",
"sin",
"(",
"alpha",
")",
")",
")",
")",
"points",
"=",
"[",
"]",
"for",
"(",
"r",
",",
"start",
",",
"end",
")",
"in",
"zip",
"(",
"r",
",",
"start_angles",
",",
"end_angles",
")",
":",
"points",
".",
"append",
"(",
"cartesian",
"(",
"r",
",",
"(",
"(",
"end",
"+",
"start",
")",
"/",
"2",
")",
")",
")",
"return",
"zip",
"(",
"*",
"points",
")"
] | translate polar coordinates to cartesian . | train | true |
43,129 | def print_items(items):
for item in items:
print_item(item)
| [
"def",
"print_items",
"(",
"items",
")",
":",
"for",
"item",
"in",
"items",
":",
"print_item",
"(",
"item",
")"
] | displays a number of items . | train | false |
43,133 | def crc(data):
return crc_finalize(crc_update(CRC_INIT, data))
| [
"def",
"crc",
"(",
"data",
")",
":",
"return",
"crc_finalize",
"(",
"crc_update",
"(",
"CRC_INIT",
",",
"data",
")",
")"
] | compute crc-32c checksum of the data . | train | false |
43,135 | def safe_sparse_dot(a, b, dense_output=False):
if (issparse(a) or issparse(b)):
ret = (a * b)
if (dense_output and hasattr(ret, 'toarray')):
ret = ret.toarray()
return ret
else:
return fast_dot(a, b)
| [
"def",
"safe_sparse_dot",
"(",
"a",
",",
"b",
",",
"dense_output",
"=",
"False",
")",
":",
"if",
"(",
"issparse",
"(",
"a",
")",
"or",
"issparse",
"(",
"b",
")",
")",
":",
"ret",
"=",
"(",
"a",
"*",
"b",
")",
"if",
"(",
"dense_output",
"and",
"hasattr",
"(",
"ret",
",",
"'toarray'",
")",
")",
":",
"ret",
"=",
"ret",
".",
"toarray",
"(",
")",
"return",
"ret",
"else",
":",
"return",
"fast_dot",
"(",
"a",
",",
"b",
")"
] | dot product that handle the sparse matrix case correctly uses blas gemm as replacement for numpy . | train | false |
43,136 | def volume_get_all_by_instance_uuid(context, instance_uuid):
return IMPL.volume_get_all_by_instance_uuid(context, instance_uuid)
| [
"def",
"volume_get_all_by_instance_uuid",
"(",
"context",
",",
"instance_uuid",
")",
":",
"return",
"IMPL",
".",
"volume_get_all_by_instance_uuid",
"(",
"context",
",",
"instance_uuid",
")"
] | get all volumes belonging to a instance . | train | false |
43,137 | def _stateMeetsRule(state, rule):
if rule.HasField('phase'):
if (rule.phase != state.phase):
return False
if rule.HasField('min_level'):
if (state.level < rule.min_level):
return False
if rule.HasField('max_level'):
if (state.level > rule.max_level):
return False
for stage in rule.stage:
if (stage not in state.stage):
return False
for stage in rule.not_stage:
if (stage in state.stage):
return False
return True
| [
"def",
"_stateMeetsRule",
"(",
"state",
",",
"rule",
")",
":",
"if",
"rule",
".",
"HasField",
"(",
"'phase'",
")",
":",
"if",
"(",
"rule",
".",
"phase",
"!=",
"state",
".",
"phase",
")",
":",
"return",
"False",
"if",
"rule",
".",
"HasField",
"(",
"'min_level'",
")",
":",
"if",
"(",
"state",
".",
"level",
"<",
"rule",
".",
"min_level",
")",
":",
"return",
"False",
"if",
"rule",
".",
"HasField",
"(",
"'max_level'",
")",
":",
"if",
"(",
"state",
".",
"level",
">",
"rule",
".",
"max_level",
")",
":",
"return",
"False",
"for",
"stage",
"in",
"rule",
".",
"stage",
":",
"if",
"(",
"stage",
"not",
"in",
"state",
".",
"stage",
")",
":",
"return",
"False",
"for",
"stage",
"in",
"rule",
".",
"not_stage",
":",
"if",
"(",
"stage",
"in",
"state",
".",
"stage",
")",
":",
"return",
"False",
"return",
"True"
] | returns true if the given state meets the given rule logic copied from caffes net::statemeetsrule() . | train | false |
43,138 | def make_gax_sinks_api(client):
channel = make_secure_channel(client._connection.credentials, DEFAULT_USER_AGENT, ConfigServiceV2Client.SERVICE_ADDRESS)
generated = ConfigServiceV2Client(channel=channel)
return _SinksAPI(generated, client)
| [
"def",
"make_gax_sinks_api",
"(",
"client",
")",
":",
"channel",
"=",
"make_secure_channel",
"(",
"client",
".",
"_connection",
".",
"credentials",
",",
"DEFAULT_USER_AGENT",
",",
"ConfigServiceV2Client",
".",
"SERVICE_ADDRESS",
")",
"generated",
"=",
"ConfigServiceV2Client",
"(",
"channel",
"=",
"channel",
")",
"return",
"_SinksAPI",
"(",
"generated",
",",
"client",
")"
] | create an instance of the gax sinks api . | train | false |
43,139 | def _log_compute_error(instance_uuid, retry):
exc = retry.get('exc')
if (not exc):
return
hosts = retry.get('hosts', None)
if (not hosts):
return
(last_host, last_node) = hosts[(-1)]
LOG.error(_LE('Error from last host: %(last_host)s (node %(last_node)s): %(exc)s'), {'last_host': last_host, 'last_node': last_node, 'exc': exc}, instance_uuid=instance_uuid)
| [
"def",
"_log_compute_error",
"(",
"instance_uuid",
",",
"retry",
")",
":",
"exc",
"=",
"retry",
".",
"get",
"(",
"'exc'",
")",
"if",
"(",
"not",
"exc",
")",
":",
"return",
"hosts",
"=",
"retry",
".",
"get",
"(",
"'hosts'",
",",
"None",
")",
"if",
"(",
"not",
"hosts",
")",
":",
"return",
"(",
"last_host",
",",
"last_node",
")",
"=",
"hosts",
"[",
"(",
"-",
"1",
")",
"]",
"LOG",
".",
"error",
"(",
"_LE",
"(",
"'Error from last host: %(last_host)s (node %(last_node)s): %(exc)s'",
")",
",",
"{",
"'last_host'",
":",
"last_host",
",",
"'last_node'",
":",
"last_node",
",",
"'exc'",
":",
"exc",
"}",
",",
"instance_uuid",
"=",
"instance_uuid",
")"
] | if the request contained an exception from a previous compute build/resize operation . | train | false |
43,140 | def get_documented_in_docstring(name, module=None, filename=None):
try:
(obj, real_name) = import_by_name(name)
lines = pydoc.getdoc(obj).splitlines()
return get_documented_in_lines(lines, module=name, filename=filename)
except AttributeError:
pass
except ImportError as e:
print((u"Failed to import '%s': %s" % (name, e)))
return {}
| [
"def",
"get_documented_in_docstring",
"(",
"name",
",",
"module",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"try",
":",
"(",
"obj",
",",
"real_name",
")",
"=",
"import_by_name",
"(",
"name",
")",
"lines",
"=",
"pydoc",
".",
"getdoc",
"(",
"obj",
")",
".",
"splitlines",
"(",
")",
"return",
"get_documented_in_lines",
"(",
"lines",
",",
"module",
"=",
"name",
",",
"filename",
"=",
"filename",
")",
"except",
"AttributeError",
":",
"pass",
"except",
"ImportError",
"as",
"e",
":",
"print",
"(",
"(",
"u\"Failed to import '%s': %s\"",
"%",
"(",
"name",
",",
"e",
")",
")",
")",
"return",
"{",
"}"
] | find out what items are documented in the given objects docstring . | train | false |
43,141 | def requires_confirmation(user):
return (_security.confirmable and (not _security.login_without_confirmation) and (user.confirmed_at is None))
| [
"def",
"requires_confirmation",
"(",
"user",
")",
":",
"return",
"(",
"_security",
".",
"confirmable",
"and",
"(",
"not",
"_security",
".",
"login_without_confirmation",
")",
"and",
"(",
"user",
".",
"confirmed_at",
"is",
"None",
")",
")"
] | returns true if the user requires confirmation . | train | false |
43,143 | def set_host_attribute(attribute, value, **host_filter_data):
assert host_filter_data
hosts = models.Host.query_objects(host_filter_data)
models.AclGroup.check_for_acl_violation_hosts(hosts)
for host in hosts:
host.set_or_delete_attribute(attribute, value)
| [
"def",
"set_host_attribute",
"(",
"attribute",
",",
"value",
",",
"**",
"host_filter_data",
")",
":",
"assert",
"host_filter_data",
"hosts",
"=",
"models",
".",
"Host",
".",
"query_objects",
"(",
"host_filter_data",
")",
"models",
".",
"AclGroup",
".",
"check_for_acl_violation_hosts",
"(",
"hosts",
")",
"for",
"host",
"in",
"hosts",
":",
"host",
".",
"set_or_delete_attribute",
"(",
"attribute",
",",
"value",
")"
] | set host attribute . | train | false |
43,144 | def write_conf(conf_file, conf):
if (not isinstance(conf, list)):
raise SaltInvocationError('Configuration must be passed as a list')
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(line[key], (six.text_type, six.string_types, six.integer_types, float)):
out_line = ' = '.join((key, '{0}'.format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if ('comment' in line[key]):
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.fopen(conf_file, 'w') as fp_:
fp_.write(content)
return {}
| [
"def",
"write_conf",
"(",
"conf_file",
",",
"conf",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"conf",
",",
"list",
")",
")",
":",
"raise",
"SaltInvocationError",
"(",
"'Configuration must be passed as a list'",
")",
"content",
"=",
"''",
"for",
"line",
"in",
"conf",
":",
"if",
"isinstance",
"(",
"line",
",",
"(",
"six",
".",
"text_type",
",",
"six",
".",
"string_types",
")",
")",
":",
"content",
"+=",
"line",
"elif",
"isinstance",
"(",
"line",
",",
"dict",
")",
":",
"for",
"key",
"in",
"list",
"(",
"line",
".",
"keys",
"(",
")",
")",
":",
"out_line",
"=",
"None",
"if",
"isinstance",
"(",
"line",
"[",
"key",
"]",
",",
"(",
"six",
".",
"text_type",
",",
"six",
".",
"string_types",
",",
"six",
".",
"integer_types",
",",
"float",
")",
")",
":",
"out_line",
"=",
"' = '",
".",
"join",
"(",
"(",
"key",
",",
"'{0}'",
".",
"format",
"(",
"line",
"[",
"key",
"]",
")",
")",
")",
"elif",
"isinstance",
"(",
"line",
"[",
"key",
"]",
",",
"dict",
")",
":",
"out_line",
"=",
"' = '",
".",
"join",
"(",
"(",
"key",
",",
"line",
"[",
"key",
"]",
"[",
"'value'",
"]",
")",
")",
"if",
"(",
"'comment'",
"in",
"line",
"[",
"key",
"]",
")",
":",
"out_line",
"=",
"' # '",
".",
"join",
"(",
"(",
"out_line",
",",
"line",
"[",
"key",
"]",
"[",
"'comment'",
"]",
")",
")",
"if",
"out_line",
":",
"content",
"+=",
"out_line",
"content",
"+=",
"'\\n'",
"with",
"salt",
".",
"utils",
".",
"fopen",
"(",
"conf_file",
",",
"'w'",
")",
"as",
"fp_",
":",
"fp_",
".",
"write",
"(",
"content",
")",
"return",
"{",
"}"
] | write out an lxc configuration file this is normally only used internally . | train | true |
43,146 | def _thread_done(gt, *args, **kwargs):
kwargs['group'].thread_done(kwargs['thread'])
| [
"def",
"_thread_done",
"(",
"gt",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"kwargs",
"[",
"'group'",
"]",
".",
"thread_done",
"(",
"kwargs",
"[",
"'thread'",
"]",
")"
] | callback function to be passed to greenthread . | train | false |
43,147 | def _get_user_project_membership(user, project, cache='user'):
if user.is_anonymous():
return None
if (cache == 'user'):
return user.cached_membership_for_project(project)
return project.cached_memberships_for_user(user)
| [
"def",
"_get_user_project_membership",
"(",
"user",
",",
"project",
",",
"cache",
"=",
"'user'",
")",
":",
"if",
"user",
".",
"is_anonymous",
"(",
")",
":",
"return",
"None",
"if",
"(",
"cache",
"==",
"'user'",
")",
":",
"return",
"user",
".",
"cached_membership_for_project",
"(",
"project",
")",
"return",
"project",
".",
"cached_memberships_for_user",
"(",
"user",
")"
] | cache param determines how memberships are calculated trying to reuse the existing data in cache . | train | false |
43,148 | def _syscmd_uname(option, default=''):
if (sys.platform in ('dos', 'win32', 'win16')):
return default
try:
f = os.popen(('uname %s 2> %s' % (option, DEV_NULL)))
except (AttributeError, OSError):
return default
output = f.read().strip()
rc = f.close()
if ((not output) or rc):
return default
else:
return output
| [
"def",
"_syscmd_uname",
"(",
"option",
",",
"default",
"=",
"''",
")",
":",
"if",
"(",
"sys",
".",
"platform",
"in",
"(",
"'dos'",
",",
"'win32'",
",",
"'win16'",
")",
")",
":",
"return",
"default",
"try",
":",
"f",
"=",
"os",
".",
"popen",
"(",
"(",
"'uname %s 2> %s'",
"%",
"(",
"option",
",",
"DEV_NULL",
")",
")",
")",
"except",
"(",
"AttributeError",
",",
"OSError",
")",
":",
"return",
"default",
"output",
"=",
"f",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
"rc",
"=",
"f",
".",
"close",
"(",
")",
"if",
"(",
"(",
"not",
"output",
")",
"or",
"rc",
")",
":",
"return",
"default",
"else",
":",
"return",
"output"
] | interface to the systems uname command . | train | false |
43,149 | def _update_ssl_config(opts):
if (opts['ssl'] is None):
return
import ssl
for (key, prefix) in (('cert_reqs', 'CERT_'), ('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if (val is None):
continue
if ((not isinstance(val, string_types)) or (not val.startswith(prefix)) or (not hasattr(ssl, val))):
message = "SSL option '{0}' must be set to one of the following values: '{1}'.".format(key, "', '".join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
| [
"def",
"_update_ssl_config",
"(",
"opts",
")",
":",
"if",
"(",
"opts",
"[",
"'ssl'",
"]",
"is",
"None",
")",
":",
"return",
"import",
"ssl",
"for",
"(",
"key",
",",
"prefix",
")",
"in",
"(",
"(",
"'cert_reqs'",
",",
"'CERT_'",
")",
",",
"(",
"'ssl_version'",
",",
"'PROTOCOL_'",
")",
")",
":",
"val",
"=",
"opts",
"[",
"'ssl'",
"]",
".",
"get",
"(",
"key",
")",
"if",
"(",
"val",
"is",
"None",
")",
":",
"continue",
"if",
"(",
"(",
"not",
"isinstance",
"(",
"val",
",",
"string_types",
")",
")",
"or",
"(",
"not",
"val",
".",
"startswith",
"(",
"prefix",
")",
")",
"or",
"(",
"not",
"hasattr",
"(",
"ssl",
",",
"val",
")",
")",
")",
":",
"message",
"=",
"\"SSL option '{0}' must be set to one of the following values: '{1}'.\"",
".",
"format",
"(",
"key",
",",
"\"', '\"",
".",
"join",
"(",
"[",
"val",
"for",
"val",
"in",
"dir",
"(",
"ssl",
")",
"if",
"val",
".",
"startswith",
"(",
"prefix",
")",
"]",
")",
")",
"log",
".",
"error",
"(",
"message",
")",
"raise",
"salt",
".",
"exceptions",
".",
"SaltConfigurationError",
"(",
"message",
")",
"opts",
"[",
"'ssl'",
"]",
"[",
"key",
"]",
"=",
"getattr",
"(",
"ssl",
",",
"val",
")"
] | resolves string names to integer constant in ssl configuration . | train | true |
43,150 | def random_degree_sequence_graph(sequence, seed=None, tries=10):
DSRG = DegreeSequenceRandomGraph(sequence, seed=seed)
for try_n in range(tries):
try:
return DSRG.generate()
except nx.NetworkXUnfeasible:
pass
raise nx.NetworkXError(('failed to generate graph in %d tries' % tries))
| [
"def",
"random_degree_sequence_graph",
"(",
"sequence",
",",
"seed",
"=",
"None",
",",
"tries",
"=",
"10",
")",
":",
"DSRG",
"=",
"DegreeSequenceRandomGraph",
"(",
"sequence",
",",
"seed",
"=",
"seed",
")",
"for",
"try_n",
"in",
"range",
"(",
"tries",
")",
":",
"try",
":",
"return",
"DSRG",
".",
"generate",
"(",
")",
"except",
"nx",
".",
"NetworkXUnfeasible",
":",
"pass",
"raise",
"nx",
".",
"NetworkXError",
"(",
"(",
"'failed to generate graph in %d tries'",
"%",
"tries",
")",
")"
] | return a simple random graph with the given degree sequence . | train | false |
43,151 | def assert_naming(warns, fname, n_warn):
from nose.tools import assert_true
assert_true((sum((('naming conventions' in str(ww.message)) for ww in warns)) == n_warn))
for ww in warns:
if ('naming conventions' in str(ww.message)):
assert_true((fname in ww.filename), msg=('"%s" not in "%s"' % (fname, ww.filename)))
| [
"def",
"assert_naming",
"(",
"warns",
",",
"fname",
",",
"n_warn",
")",
":",
"from",
"nose",
".",
"tools",
"import",
"assert_true",
"assert_true",
"(",
"(",
"sum",
"(",
"(",
"(",
"'naming conventions'",
"in",
"str",
"(",
"ww",
".",
"message",
")",
")",
"for",
"ww",
"in",
"warns",
")",
")",
"==",
"n_warn",
")",
")",
"for",
"ww",
"in",
"warns",
":",
"if",
"(",
"'naming conventions'",
"in",
"str",
"(",
"ww",
".",
"message",
")",
")",
":",
"assert_true",
"(",
"(",
"fname",
"in",
"ww",
".",
"filename",
")",
",",
"msg",
"=",
"(",
"'\"%s\" not in \"%s\"'",
"%",
"(",
"fname",
",",
"ww",
".",
"filename",
")",
")",
")"
] | assert a non-standard naming scheme was used while saving or loading parameters warns : list list of warnings from warnings . | train | false |
43,152 | def dlls_in_subdirs(directory):
filelist = []
for (root, dirs, files) in os.walk(directory):
filelist.extend(dlls_in_dir(root))
return filelist
| [
"def",
"dlls_in_subdirs",
"(",
"directory",
")",
":",
"filelist",
"=",
"[",
"]",
"for",
"(",
"root",
",",
"dirs",
",",
"files",
")",
"in",
"os",
".",
"walk",
"(",
"directory",
")",
":",
"filelist",
".",
"extend",
"(",
"dlls_in_dir",
"(",
"root",
")",
")",
"return",
"filelist"
] | returns a list * . | train | false |
43,153 | def test_skip_dt_decorator():
check = 'A function whose doctest we need to skip.\n\n >>> 1+1\n 3\n '
val = doctest_bad.__doc__
nt.assert_equal(check, val, "doctest_bad docstrings don't match")
| [
"def",
"test_skip_dt_decorator",
"(",
")",
":",
"check",
"=",
"'A function whose doctest we need to skip.\\n\\n >>> 1+1\\n 3\\n '",
"val",
"=",
"doctest_bad",
".",
"__doc__",
"nt",
".",
"assert_equal",
"(",
"check",
",",
"val",
",",
"\"doctest_bad docstrings don't match\"",
")"
] | doctest-skipping decorator should preserve the docstring . | train | false |
43,154 | def getThicknessMultipliedPath(path, thicknessMultiplier):
for (pointIndex, point) in enumerate(path):
path[pointIndex] = complex((point.real * thicknessMultiplier), point.imag)
return path
| [
"def",
"getThicknessMultipliedPath",
"(",
"path",
",",
"thicknessMultiplier",
")",
":",
"for",
"(",
"pointIndex",
",",
"point",
")",
"in",
"enumerate",
"(",
"path",
")",
":",
"path",
"[",
"pointIndex",
"]",
"=",
"complex",
"(",
"(",
"point",
".",
"real",
"*",
"thicknessMultiplier",
")",
",",
"point",
".",
"imag",
")",
"return",
"path"
] | get thickness multiplied path . | train | false |
43,155 | def filterPairValues(values):
retVal = []
if ((not isNoneValue(values)) and hasattr(values, '__iter__')):
retVal = filter((lambda x: (isinstance(x, (tuple, list, set)) and (len(x) == 2))), values)
return retVal
| [
"def",
"filterPairValues",
"(",
"values",
")",
":",
"retVal",
"=",
"[",
"]",
"if",
"(",
"(",
"not",
"isNoneValue",
"(",
"values",
")",
")",
"and",
"hasattr",
"(",
"values",
",",
"'__iter__'",
")",
")",
":",
"retVal",
"=",
"filter",
"(",
"(",
"lambda",
"x",
":",
"(",
"isinstance",
"(",
"x",
",",
"(",
"tuple",
",",
"list",
",",
"set",
")",
")",
"and",
"(",
"len",
"(",
"x",
")",
"==",
"2",
")",
")",
")",
",",
"values",
")",
"return",
"retVal"
] | returns only list-like values with length 2 . | train | false |
43,156 | def addToMenu(master, menu, repository, window):
metaFilePath = archive.getSkeinforgePluginsPath('meta.py')
settings.addPluginsParentToMenu(skeinforge_meta.getPluginsDirectoryPath(), menu, metaFilePath, skeinforge_meta.getPluginFileNames())
| [
"def",
"addToMenu",
"(",
"master",
",",
"menu",
",",
"repository",
",",
"window",
")",
":",
"metaFilePath",
"=",
"archive",
".",
"getSkeinforgePluginsPath",
"(",
"'meta.py'",
")",
"settings",
".",
"addPluginsParentToMenu",
"(",
"skeinforge_meta",
".",
"getPluginsDirectoryPath",
"(",
")",
",",
"menu",
",",
"metaFilePath",
",",
"skeinforge_meta",
".",
"getPluginFileNames",
"(",
")",
")"
] | add a tool plugin menu . | train | false |
43,160 | def latestClass(oldClass):
module = reflect.namedModule(oldClass.__module__)
newClass = getattr(module, oldClass.__name__)
newBases = [latestClass(base) for base in newClass.__bases__]
try:
newClass.__bases__ = tuple(newBases)
return newClass
except TypeError:
if (newClass.__module__ == '__builtin__'):
return newClass
ctor = getattr(newClass, '__metaclass__', type)
return ctor(newClass.__name__, tuple(newBases), dict(newClass.__dict__))
| [
"def",
"latestClass",
"(",
"oldClass",
")",
":",
"module",
"=",
"reflect",
".",
"namedModule",
"(",
"oldClass",
".",
"__module__",
")",
"newClass",
"=",
"getattr",
"(",
"module",
",",
"oldClass",
".",
"__name__",
")",
"newBases",
"=",
"[",
"latestClass",
"(",
"base",
")",
"for",
"base",
"in",
"newClass",
".",
"__bases__",
"]",
"try",
":",
"newClass",
".",
"__bases__",
"=",
"tuple",
"(",
"newBases",
")",
"return",
"newClass",
"except",
"TypeError",
":",
"if",
"(",
"newClass",
".",
"__module__",
"==",
"'__builtin__'",
")",
":",
"return",
"newClass",
"ctor",
"=",
"getattr",
"(",
"newClass",
",",
"'__metaclass__'",
",",
"type",
")",
"return",
"ctor",
"(",
"newClass",
".",
"__name__",
",",
"tuple",
"(",
"newBases",
")",
",",
"dict",
"(",
"newClass",
".",
"__dict__",
")",
")"
] | get the latest version of a class . | train | false |
43,162 | def find_common_elements(source_preferences, target_preferences):
src = dict(source_preferences)
tgt = dict(target_preferences)
inter = np.intersect1d(src.keys(), tgt.keys())
common_preferences = zip(*[(src[item], tgt[item]) for item in inter if ((not np.isnan(src[item])) and (not np.isnan(tgt[item])))])
if common_preferences:
return (np.asarray([common_preferences[0]]), np.asarray([common_preferences[1]]))
else:
return (np.asarray([[]]), np.asarray([[]]))
| [
"def",
"find_common_elements",
"(",
"source_preferences",
",",
"target_preferences",
")",
":",
"src",
"=",
"dict",
"(",
"source_preferences",
")",
"tgt",
"=",
"dict",
"(",
"target_preferences",
")",
"inter",
"=",
"np",
".",
"intersect1d",
"(",
"src",
".",
"keys",
"(",
")",
",",
"tgt",
".",
"keys",
"(",
")",
")",
"common_preferences",
"=",
"zip",
"(",
"*",
"[",
"(",
"src",
"[",
"item",
"]",
",",
"tgt",
"[",
"item",
"]",
")",
"for",
"item",
"in",
"inter",
"if",
"(",
"(",
"not",
"np",
".",
"isnan",
"(",
"src",
"[",
"item",
"]",
")",
")",
"and",
"(",
"not",
"np",
".",
"isnan",
"(",
"tgt",
"[",
"item",
"]",
")",
")",
")",
"]",
")",
"if",
"common_preferences",
":",
"return",
"(",
"np",
".",
"asarray",
"(",
"[",
"common_preferences",
"[",
"0",
"]",
"]",
")",
",",
"np",
".",
"asarray",
"(",
"[",
"common_preferences",
"[",
"1",
"]",
"]",
")",
")",
"else",
":",
"return",
"(",
"np",
".",
"asarray",
"(",
"[",
"[",
"]",
"]",
")",
",",
"np",
".",
"asarray",
"(",
"[",
"[",
"]",
"]",
")",
")"
] | returns the preferences from both vectors . | train | false |
43,163 | def test_slug():
schema = vol.Schema(cv.slug)
for value in (None, 'hello world'):
with pytest.raises(vol.MultipleInvalid):
schema(value)
for value in (12345, 'hello'):
schema(value)
| [
"def",
"test_slug",
"(",
")",
":",
"schema",
"=",
"vol",
".",
"Schema",
"(",
"cv",
".",
"slug",
")",
"for",
"value",
"in",
"(",
"None",
",",
"'hello world'",
")",
":",
"with",
"pytest",
".",
"raises",
"(",
"vol",
".",
"MultipleInvalid",
")",
":",
"schema",
"(",
"value",
")",
"for",
"value",
"in",
"(",
"12345",
",",
"'hello'",
")",
":",
"schema",
"(",
"value",
")"
] | test slug validation . | train | false |
43,164 | def get_qualified_path(name):
import sys
import os
path = sys.path
try:
path = ([os.path.dirname(__file__)] + path)
except NameError:
pass
for dir in path:
fullname = os.path.join(dir, name)
if os.path.exists(fullname):
return fullname
return name
| [
"def",
"get_qualified_path",
"(",
"name",
")",
":",
"import",
"sys",
"import",
"os",
"path",
"=",
"sys",
".",
"path",
"try",
":",
"path",
"=",
"(",
"[",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"]",
"+",
"path",
")",
"except",
"NameError",
":",
"pass",
"for",
"dir",
"in",
"path",
":",
"fullname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"name",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fullname",
")",
":",
"return",
"fullname",
"return",
"name"
] | return a more qualified path to name . | train | false |
43,165 | def _quotes_historical_yahoo(ticker, date1, date2, asobject=False, adjusted=True, cachename=None, ochl=True):
fh = fetch_historical_yahoo(ticker, date1, date2, cachename)
try:
ret = _parse_yahoo_historical(fh, asobject=asobject, adjusted=adjusted, ochl=ochl)
if (len(ret) == 0):
return None
except IOError as exc:
warnings.warn((u'fh failure\n%s' % exc.strerror[1]))
return None
return ret
| [
"def",
"_quotes_historical_yahoo",
"(",
"ticker",
",",
"date1",
",",
"date2",
",",
"asobject",
"=",
"False",
",",
"adjusted",
"=",
"True",
",",
"cachename",
"=",
"None",
",",
"ochl",
"=",
"True",
")",
":",
"fh",
"=",
"fetch_historical_yahoo",
"(",
"ticker",
",",
"date1",
",",
"date2",
",",
"cachename",
")",
"try",
":",
"ret",
"=",
"_parse_yahoo_historical",
"(",
"fh",
",",
"asobject",
"=",
"asobject",
",",
"adjusted",
"=",
"adjusted",
",",
"ochl",
"=",
"ochl",
")",
"if",
"(",
"len",
"(",
"ret",
")",
"==",
"0",
")",
":",
"return",
"None",
"except",
"IOError",
"as",
"exc",
":",
"warnings",
".",
"warn",
"(",
"(",
"u'fh failure\\n%s'",
"%",
"exc",
".",
"strerror",
"[",
"1",
"]",
")",
")",
"return",
"None",
"return",
"ret"
] | get historical data for ticker between date1 and date2 . | train | false |
43,166 | def get_marker_style(line):
style = {}
style['alpha'] = line.get_alpha()
if (style['alpha'] is None):
style['alpha'] = 1
style['facecolor'] = color_to_hex(line.get_markerfacecolor())
style['edgecolor'] = color_to_hex(line.get_markeredgecolor())
style['edgewidth'] = line.get_markeredgewidth()
style['marker'] = line.get_marker()
markerstyle = MarkerStyle(line.get_marker())
markersize = line.get_markersize()
markertransform = (markerstyle.get_transform() + Affine2D().scale(markersize, (- markersize)))
style['markerpath'] = SVG_path(markerstyle.get_path(), markertransform)
style['markersize'] = markersize
style['zorder'] = line.get_zorder()
return style
| [
"def",
"get_marker_style",
"(",
"line",
")",
":",
"style",
"=",
"{",
"}",
"style",
"[",
"'alpha'",
"]",
"=",
"line",
".",
"get_alpha",
"(",
")",
"if",
"(",
"style",
"[",
"'alpha'",
"]",
"is",
"None",
")",
":",
"style",
"[",
"'alpha'",
"]",
"=",
"1",
"style",
"[",
"'facecolor'",
"]",
"=",
"color_to_hex",
"(",
"line",
".",
"get_markerfacecolor",
"(",
")",
")",
"style",
"[",
"'edgecolor'",
"]",
"=",
"color_to_hex",
"(",
"line",
".",
"get_markeredgecolor",
"(",
")",
")",
"style",
"[",
"'edgewidth'",
"]",
"=",
"line",
".",
"get_markeredgewidth",
"(",
")",
"style",
"[",
"'marker'",
"]",
"=",
"line",
".",
"get_marker",
"(",
")",
"markerstyle",
"=",
"MarkerStyle",
"(",
"line",
".",
"get_marker",
"(",
")",
")",
"markersize",
"=",
"line",
".",
"get_markersize",
"(",
")",
"markertransform",
"=",
"(",
"markerstyle",
".",
"get_transform",
"(",
")",
"+",
"Affine2D",
"(",
")",
".",
"scale",
"(",
"markersize",
",",
"(",
"-",
"markersize",
")",
")",
")",
"style",
"[",
"'markerpath'",
"]",
"=",
"SVG_path",
"(",
"markerstyle",
".",
"get_path",
"(",
")",
",",
"markertransform",
")",
"style",
"[",
"'markersize'",
"]",
"=",
"markersize",
"style",
"[",
"'zorder'",
"]",
"=",
"line",
".",
"get_zorder",
"(",
")",
"return",
"style"
] | get the style dictionary for matplotlib marker objects . | train | true |
43,168 | def _reloader_child(server, app, interval):
lockfile = os.environ.get('BOTTLE_LOCKFILE')
bgcheck = FileCheckerThread(lockfile, interval)
try:
bgcheck.start()
server.run(app)
except KeyboardInterrupt:
pass
(bgcheck.status, status) = (5, bgcheck.status)
bgcheck.join()
if status:
sys.exit(status)
| [
"def",
"_reloader_child",
"(",
"server",
",",
"app",
",",
"interval",
")",
":",
"lockfile",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'BOTTLE_LOCKFILE'",
")",
"bgcheck",
"=",
"FileCheckerThread",
"(",
"lockfile",
",",
"interval",
")",
"try",
":",
"bgcheck",
".",
"start",
"(",
")",
"server",
".",
"run",
"(",
"app",
")",
"except",
"KeyboardInterrupt",
":",
"pass",
"(",
"bgcheck",
".",
"status",
",",
"status",
")",
"=",
"(",
"5",
",",
"bgcheck",
".",
"status",
")",
"bgcheck",
".",
"join",
"(",
")",
"if",
"status",
":",
"sys",
".",
"exit",
"(",
"status",
")"
] | start the server and check for modified files in a background thread . | train | true |
43,169 | def IsPythonFile(filename):
if (os.path.splitext(filename)[1] == '.py'):
return True
try:
with open(filename, 'rb') as fd:
encoding = tokenize.detect_encoding(fd.readline)[0]
with py3compat.open_with_encoding(filename, mode='r', encoding=encoding) as fd:
fd.read()
except UnicodeDecodeError:
encoding = 'latin-1'
except (IOError, SyntaxError):
return False
try:
with py3compat.open_with_encoding(filename, mode='r', encoding=encoding) as fd:
first_line = fd.readlines()[0]
except (IOError, IndexError):
return False
return re.match('^#!.*\\bpython[23]?\\b', first_line)
| [
"def",
"IsPythonFile",
"(",
"filename",
")",
":",
"if",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"1",
"]",
"==",
"'.py'",
")",
":",
"return",
"True",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"fd",
":",
"encoding",
"=",
"tokenize",
".",
"detect_encoding",
"(",
"fd",
".",
"readline",
")",
"[",
"0",
"]",
"with",
"py3compat",
".",
"open_with_encoding",
"(",
"filename",
",",
"mode",
"=",
"'r'",
",",
"encoding",
"=",
"encoding",
")",
"as",
"fd",
":",
"fd",
".",
"read",
"(",
")",
"except",
"UnicodeDecodeError",
":",
"encoding",
"=",
"'latin-1'",
"except",
"(",
"IOError",
",",
"SyntaxError",
")",
":",
"return",
"False",
"try",
":",
"with",
"py3compat",
".",
"open_with_encoding",
"(",
"filename",
",",
"mode",
"=",
"'r'",
",",
"encoding",
"=",
"encoding",
")",
"as",
"fd",
":",
"first_line",
"=",
"fd",
".",
"readlines",
"(",
")",
"[",
"0",
"]",
"except",
"(",
"IOError",
",",
"IndexError",
")",
":",
"return",
"False",
"return",
"re",
".",
"match",
"(",
"'^#!.*\\\\bpython[23]?\\\\b'",
",",
"first_line",
")"
] | return true if filename is a python file . | train | false |
43,170 | @raises(TypeError)
def test_extra_kwarg():
w = wcs.WCS()
with NumpyRNGContext(123456789):
data = np.random.rand(100, 2)
w.wcs_pix2world(data, origin=1)
| [
"@",
"raises",
"(",
"TypeError",
")",
"def",
"test_extra_kwarg",
"(",
")",
":",
"w",
"=",
"wcs",
".",
"WCS",
"(",
")",
"with",
"NumpyRNGContext",
"(",
"123456789",
")",
":",
"data",
"=",
"np",
".",
"random",
".",
"rand",
"(",
"100",
",",
"2",
")",
"w",
".",
"wcs_pix2world",
"(",
"data",
",",
"origin",
"=",
"1",
")"
] | issue #444 . | train | false |
43,172 | @decorators.which('arp')
def arp():
ret = {}
out = __salt__['cmd.run']('arp -an')
for line in out.splitlines():
comps = line.split()
if (len(comps) < 4):
continue
if (__grains__['kernel'] == 'SunOS'):
if (':' not in comps[(-1)]):
continue
ret[comps[(-1)]] = comps[1]
elif (__grains__['kernel'] == 'OpenBSD'):
if ((comps[0] == 'Host') or (comps[1] == '(incomplete)')):
continue
ret[comps[1]] = comps[0]
else:
ret[comps[3]] = comps[1].strip('(').strip(')')
return ret
| [
"@",
"decorators",
".",
"which",
"(",
"'arp'",
")",
"def",
"arp",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'arp -an'",
")",
"for",
"line",
"in",
"out",
".",
"splitlines",
"(",
")",
":",
"comps",
"=",
"line",
".",
"split",
"(",
")",
"if",
"(",
"len",
"(",
"comps",
")",
"<",
"4",
")",
":",
"continue",
"if",
"(",
"__grains__",
"[",
"'kernel'",
"]",
"==",
"'SunOS'",
")",
":",
"if",
"(",
"':'",
"not",
"in",
"comps",
"[",
"(",
"-",
"1",
")",
"]",
")",
":",
"continue",
"ret",
"[",
"comps",
"[",
"(",
"-",
"1",
")",
"]",
"]",
"=",
"comps",
"[",
"1",
"]",
"elif",
"(",
"__grains__",
"[",
"'kernel'",
"]",
"==",
"'OpenBSD'",
")",
":",
"if",
"(",
"(",
"comps",
"[",
"0",
"]",
"==",
"'Host'",
")",
"or",
"(",
"comps",
"[",
"1",
"]",
"==",
"'(incomplete)'",
")",
")",
":",
"continue",
"ret",
"[",
"comps",
"[",
"1",
"]",
"]",
"=",
"comps",
"[",
"0",
"]",
"else",
":",
"ret",
"[",
"comps",
"[",
"3",
"]",
"]",
"=",
"comps",
"[",
"1",
"]",
".",
"strip",
"(",
"'('",
")",
".",
"strip",
"(",
"')'",
")",
"return",
"ret"
] | return the arp table from the minion . | train | true |
43,174 | def test_hdf5_load_all():
skip_if_no_h5py()
import h5py
(handle, filename) = tempfile.mkstemp()
dataset = random_one_hot_dense_design_matrix(np.random.RandomState(1), num_examples=10, dim=5, num_classes=3)
with h5py.File(filename, 'w') as f:
f.create_dataset('X', data=dataset.get_design_matrix())
f.create_dataset('y', data=dataset.get_targets())
trainer = yaml_parse.load((load_all_yaml % {'filename': filename}))
trainer.main_loop()
os.remove(filename)
| [
"def",
"test_hdf5_load_all",
"(",
")",
":",
"skip_if_no_h5py",
"(",
")",
"import",
"h5py",
"(",
"handle",
",",
"filename",
")",
"=",
"tempfile",
".",
"mkstemp",
"(",
")",
"dataset",
"=",
"random_one_hot_dense_design_matrix",
"(",
"np",
".",
"random",
".",
"RandomState",
"(",
"1",
")",
",",
"num_examples",
"=",
"10",
",",
"dim",
"=",
"5",
",",
"num_classes",
"=",
"3",
")",
"with",
"h5py",
".",
"File",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"create_dataset",
"(",
"'X'",
",",
"data",
"=",
"dataset",
".",
"get_design_matrix",
"(",
")",
")",
"f",
".",
"create_dataset",
"(",
"'y'",
",",
"data",
"=",
"dataset",
".",
"get_targets",
"(",
")",
")",
"trainer",
"=",
"yaml_parse",
".",
"load",
"(",
"(",
"load_all_yaml",
"%",
"{",
"'filename'",
":",
"filename",
"}",
")",
")",
"trainer",
".",
"main_loop",
"(",
")",
"os",
".",
"remove",
"(",
"filename",
")"
] | train using an hdf5 dataset with all data loaded into memory . | train | false |
43,175 | def weighted_lottery(weights, _random=random.random):
total = sum(weights.itervalues())
if (total <= 0):
raise ValueError('total weight must be positive')
r = (_random() * total)
t = 0
for (key, weight) in weights.iteritems():
if (weight < 0):
raise ValueError(('weight for %r must be non-negative' % key))
t += weight
if (t > r):
return key
raise ValueError(('weighted_lottery messed up: r=%r, t=%r, total=%r' % (r, t, total)))
| [
"def",
"weighted_lottery",
"(",
"weights",
",",
"_random",
"=",
"random",
".",
"random",
")",
":",
"total",
"=",
"sum",
"(",
"weights",
".",
"itervalues",
"(",
")",
")",
"if",
"(",
"total",
"<=",
"0",
")",
":",
"raise",
"ValueError",
"(",
"'total weight must be positive'",
")",
"r",
"=",
"(",
"_random",
"(",
")",
"*",
"total",
")",
"t",
"=",
"0",
"for",
"(",
"key",
",",
"weight",
")",
"in",
"weights",
".",
"iteritems",
"(",
")",
":",
"if",
"(",
"weight",
"<",
"0",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'weight for %r must be non-negative'",
"%",
"key",
")",
")",
"t",
"+=",
"weight",
"if",
"(",
"t",
">",
"r",
")",
":",
"return",
"key",
"raise",
"ValueError",
"(",
"(",
"'weighted_lottery messed up: r=%r, t=%r, total=%r'",
"%",
"(",
"r",
",",
"t",
",",
"total",
")",
")",
")"
] | randomly choose a key from a dict where values are weights . | train | false |
43,176 | def item_method(fn):
fn._item_method = True
return fn
| [
"def",
"item_method",
"(",
"fn",
")",
":",
"fn",
".",
"_item_method",
"=",
"True",
"return",
"fn"
] | flag method as an item method . | train | false |
43,177 | def raw_incron(user):
if (__grains__['os_family'] == 'Solaris'):
cmd = 'incrontab -l {0}'.format(user)
else:
cmd = 'incrontab -l -u {0}'.format(user)
return __salt__['cmd.run_stdout'](cmd, rstrip=False, runas=user, python_shell=False)
| [
"def",
"raw_incron",
"(",
"user",
")",
":",
"if",
"(",
"__grains__",
"[",
"'os_family'",
"]",
"==",
"'Solaris'",
")",
":",
"cmd",
"=",
"'incrontab -l {0}'",
".",
"format",
"(",
"user",
")",
"else",
":",
"cmd",
"=",
"'incrontab -l -u {0}'",
".",
"format",
"(",
"user",
")",
"return",
"__salt__",
"[",
"'cmd.run_stdout'",
"]",
"(",
"cmd",
",",
"rstrip",
"=",
"False",
",",
"runas",
"=",
"user",
",",
"python_shell",
"=",
"False",
")"
] | return the contents of the users incrontab cli example: . | train | true |
43,179 | def _get_prerequisite_milestone(prereq_content_key):
milestones = milestones_api.get_milestones('{usage_key}{qualifier}'.format(usage_key=prereq_content_key, qualifier=GATING_NAMESPACE_QUALIFIER))
if (not milestones):
log.warning('Could not find gating milestone for prereq UsageKey %s', prereq_content_key)
return None
if (len(milestones) > 1):
log.warning('Multiple gating milestones found for prereq UsageKey %s', prereq_content_key)
return milestones[0]
| [
"def",
"_get_prerequisite_milestone",
"(",
"prereq_content_key",
")",
":",
"milestones",
"=",
"milestones_api",
".",
"get_milestones",
"(",
"'{usage_key}{qualifier}'",
".",
"format",
"(",
"usage_key",
"=",
"prereq_content_key",
",",
"qualifier",
"=",
"GATING_NAMESPACE_QUALIFIER",
")",
")",
"if",
"(",
"not",
"milestones",
")",
":",
"log",
".",
"warning",
"(",
"'Could not find gating milestone for prereq UsageKey %s'",
",",
"prereq_content_key",
")",
"return",
"None",
"if",
"(",
"len",
"(",
"milestones",
")",
">",
"1",
")",
":",
"log",
".",
"warning",
"(",
"'Multiple gating milestones found for prereq UsageKey %s'",
",",
"prereq_content_key",
")",
"return",
"milestones",
"[",
"0",
"]"
] | get gating milestone associated with the given content usage key . | train | false |
43,181 | def _generate_urls(mbid):
for level in LEVELS:
(yield ((ACOUSTIC_BASE + mbid) + level))
| [
"def",
"_generate_urls",
"(",
"mbid",
")",
":",
"for",
"level",
"in",
"LEVELS",
":",
"(",
"yield",
"(",
"(",
"ACOUSTIC_BASE",
"+",
"mbid",
")",
"+",
"level",
")",
")"
] | generates acousticbrainz end point urls for given mbid . | train | false |
43,182 | def monomial_count(V, N):
from sympy import factorial
return ((factorial((V + N)) / factorial(V)) / factorial(N))
| [
"def",
"monomial_count",
"(",
"V",
",",
"N",
")",
":",
"from",
"sympy",
"import",
"factorial",
"return",
"(",
"(",
"factorial",
"(",
"(",
"V",
"+",
"N",
")",
")",
"/",
"factorial",
"(",
"V",
")",
")",
"/",
"factorial",
"(",
"N",
")",
")"
] | computes the number of monomials . | train | false |
43,183 | def validate_trust_root(openid_request):
trusted_roots = getattr(settings, 'OPENID_PROVIDER_TRUSTED_ROOT', None)
if (not trusted_roots):
return True
if ((not hasattr(openid_request, 'trust_root')) or (not openid_request.trust_root)):
log.error('no trust_root')
return False
trust_root = TrustRoot.parse(openid_request.trust_root)
if (not trust_root):
log.error('invalid trust_root')
return False
if ((not hasattr(openid_request, 'return_to')) or (not openid_request.return_to)):
log.error('empty return_to')
return False
if (not trust_root.validateURL(openid_request.return_to)):
log.error('invalid return_to')
return False
if (not any((r for r in trusted_roots if fnmatch.fnmatch(trust_root, r)))):
log.error('non-trusted root')
return False
return True
| [
"def",
"validate_trust_root",
"(",
"openid_request",
")",
":",
"trusted_roots",
"=",
"getattr",
"(",
"settings",
",",
"'OPENID_PROVIDER_TRUSTED_ROOT'",
",",
"None",
")",
"if",
"(",
"not",
"trusted_roots",
")",
":",
"return",
"True",
"if",
"(",
"(",
"not",
"hasattr",
"(",
"openid_request",
",",
"'trust_root'",
")",
")",
"or",
"(",
"not",
"openid_request",
".",
"trust_root",
")",
")",
":",
"log",
".",
"error",
"(",
"'no trust_root'",
")",
"return",
"False",
"trust_root",
"=",
"TrustRoot",
".",
"parse",
"(",
"openid_request",
".",
"trust_root",
")",
"if",
"(",
"not",
"trust_root",
")",
":",
"log",
".",
"error",
"(",
"'invalid trust_root'",
")",
"return",
"False",
"if",
"(",
"(",
"not",
"hasattr",
"(",
"openid_request",
",",
"'return_to'",
")",
")",
"or",
"(",
"not",
"openid_request",
".",
"return_to",
")",
")",
":",
"log",
".",
"error",
"(",
"'empty return_to'",
")",
"return",
"False",
"if",
"(",
"not",
"trust_root",
".",
"validateURL",
"(",
"openid_request",
".",
"return_to",
")",
")",
":",
"log",
".",
"error",
"(",
"'invalid return_to'",
")",
"return",
"False",
"if",
"(",
"not",
"any",
"(",
"(",
"r",
"for",
"r",
"in",
"trusted_roots",
"if",
"fnmatch",
".",
"fnmatch",
"(",
"trust_root",
",",
"r",
")",
")",
")",
")",
":",
"log",
".",
"error",
"(",
"'non-trusted root'",
")",
"return",
"False",
"return",
"True"
] | only allow openid requests from valid trust roots . | train | false |
43,184 | def getEndGeometryXMLString(output):
addEndXMLTag(0, 'fabmetheus', output)
return output.getvalue()
| [
"def",
"getEndGeometryXMLString",
"(",
"output",
")",
":",
"addEndXMLTag",
"(",
"0",
",",
"'fabmetheus'",
",",
"output",
")",
"return",
"output",
".",
"getvalue",
"(",
")"
] | get the string representation of this object info . | train | false |
43,185 | def id_to_ec2_id(instance_id, template='i-%08x'):
return (template % int(instance_id))
| [
"def",
"id_to_ec2_id",
"(",
"instance_id",
",",
"template",
"=",
"'i-%08x'",
")",
":",
"return",
"(",
"template",
"%",
"int",
"(",
"instance_id",
")",
")"
] | convert an instance id to an ec2 id . | train | false |
43,187 | def induce_pcfg(start, productions):
pcount = {}
lcount = {}
for prod in productions:
lcount[prod.lhs()] = (lcount.get(prod.lhs(), 0) + 1)
pcount[prod] = (pcount.get(prod, 0) + 1)
prods = [ProbabilisticProduction(p.lhs(), p.rhs(), prob=(pcount[p] / lcount[p.lhs()])) for p in pcount]
return PCFG(start, prods)
| [
"def",
"induce_pcfg",
"(",
"start",
",",
"productions",
")",
":",
"pcount",
"=",
"{",
"}",
"lcount",
"=",
"{",
"}",
"for",
"prod",
"in",
"productions",
":",
"lcount",
"[",
"prod",
".",
"lhs",
"(",
")",
"]",
"=",
"(",
"lcount",
".",
"get",
"(",
"prod",
".",
"lhs",
"(",
")",
",",
"0",
")",
"+",
"1",
")",
"pcount",
"[",
"prod",
"]",
"=",
"(",
"pcount",
".",
"get",
"(",
"prod",
",",
"0",
")",
"+",
"1",
")",
"prods",
"=",
"[",
"ProbabilisticProduction",
"(",
"p",
".",
"lhs",
"(",
")",
",",
"p",
".",
"rhs",
"(",
")",
",",
"prob",
"=",
"(",
"pcount",
"[",
"p",
"]",
"/",
"lcount",
"[",
"p",
".",
"lhs",
"(",
")",
"]",
")",
")",
"for",
"p",
"in",
"pcount",
"]",
"return",
"PCFG",
"(",
"start",
",",
"prods",
")"
] | induce a pcfg grammar from a list of productions . | train | false |
43,188 | def source(object):
print(('In file: %s' % inspect.getsourcefile(object)))
print(inspect.getsource(object))
| [
"def",
"source",
"(",
"object",
")",
":",
"print",
"(",
"(",
"'In file: %s'",
"%",
"inspect",
".",
"getsourcefile",
"(",
"object",
")",
")",
")",
"print",
"(",
"inspect",
".",
"getsource",
"(",
"object",
")",
")"
] | require a package source . | train | false |
43,189 | def make_loopable(clip, cross):
d = clip.duration
clip2 = clip.fx(transfx.crossfadein, cross).set_start((d - cross))
return CompositeVideoClip([clip, clip2]).subclip(cross, d)
| [
"def",
"make_loopable",
"(",
"clip",
",",
"cross",
")",
":",
"d",
"=",
"clip",
".",
"duration",
"clip2",
"=",
"clip",
".",
"fx",
"(",
"transfx",
".",
"crossfadein",
",",
"cross",
")",
".",
"set_start",
"(",
"(",
"d",
"-",
"cross",
")",
")",
"return",
"CompositeVideoClip",
"(",
"[",
"clip",
",",
"clip2",
"]",
")",
".",
"subclip",
"(",
"cross",
",",
"d",
")"
] | makes the clip fade in progressively at its own end . | train | false |
43,190 | def mvstdtprob(a, b, R, df, ieps=1e-05, quadkwds=None, mvstkwds=None):
kwds = dict(args=(a, b, R, df), epsabs=0.0001, epsrel=0.01, limit=150)
if (not (quadkwds is None)):
kwds.update(quadkwds)
(res, err) = integrate.quad(funbgh2, *chi.ppf([ieps, (1 - ieps)], df), **kwds)
prob = (res * bghfactor(df))
return prob
| [
"def",
"mvstdtprob",
"(",
"a",
",",
"b",
",",
"R",
",",
"df",
",",
"ieps",
"=",
"1e-05",
",",
"quadkwds",
"=",
"None",
",",
"mvstkwds",
"=",
"None",
")",
":",
"kwds",
"=",
"dict",
"(",
"args",
"=",
"(",
"a",
",",
"b",
",",
"R",
",",
"df",
")",
",",
"epsabs",
"=",
"0.0001",
",",
"epsrel",
"=",
"0.01",
",",
"limit",
"=",
"150",
")",
"if",
"(",
"not",
"(",
"quadkwds",
"is",
"None",
")",
")",
":",
"kwds",
".",
"update",
"(",
"quadkwds",
")",
"(",
"res",
",",
"err",
")",
"=",
"integrate",
".",
"quad",
"(",
"funbgh2",
",",
"*",
"chi",
".",
"ppf",
"(",
"[",
"ieps",
",",
"(",
"1",
"-",
"ieps",
")",
"]",
",",
"df",
")",
",",
"**",
"kwds",
")",
"prob",
"=",
"(",
"res",
"*",
"bghfactor",
"(",
"df",
")",
")",
"return",
"prob"
] | probability of rectangular area of standard t distribution assumes mean is zero and r is correlation matrix notes this function does not calculate the estimate of the combined error between the underlying multivariate normal probability calculations and the integration . | train | false |
43,191 | @Memoize
def cycle_color(s):
return next(dg['cyc'])(s)
| [
"@",
"Memoize",
"def",
"cycle_color",
"(",
"s",
")",
":",
"return",
"next",
"(",
"dg",
"[",
"'cyc'",
"]",
")",
"(",
"s",
")"
] | cycle the colors_shuffle . | train | false |
43,192 | def accuracy_score(y_true, y_pred, normalize=True, sample_weight=None):
(y_type, y_true, y_pred) = _check_targets(y_true, y_pred)
if y_type.startswith('multilabel'):
differing_labels = count_nonzero((y_true - y_pred), axis=1)
score = (differing_labels == 0)
else:
score = (y_true == y_pred)
return _weighted_sum(score, sample_weight, normalize)
| [
"def",
"accuracy_score",
"(",
"y_true",
",",
"y_pred",
",",
"normalize",
"=",
"True",
",",
"sample_weight",
"=",
"None",
")",
":",
"(",
"y_type",
",",
"y_true",
",",
"y_pred",
")",
"=",
"_check_targets",
"(",
"y_true",
",",
"y_pred",
")",
"if",
"y_type",
".",
"startswith",
"(",
"'multilabel'",
")",
":",
"differing_labels",
"=",
"count_nonzero",
"(",
"(",
"y_true",
"-",
"y_pred",
")",
",",
"axis",
"=",
"1",
")",
"score",
"=",
"(",
"differing_labels",
"==",
"0",
")",
"else",
":",
"score",
"=",
"(",
"y_true",
"==",
"y_pred",
")",
"return",
"_weighted_sum",
"(",
"score",
",",
"sample_weight",
",",
"normalize",
")"
] | accuracy classification score . | train | false |
43,193 | def test_close_process_when_aborted():
with pipeline.get_cat_pipeline(pipeline.PIPE, pipeline.PIPE) as pl:
assert (len(pl.commands) == 1)
assert (pl.commands[0]._process.poll() is None)
pl.abort()
pipeline_wait(pl)
| [
"def",
"test_close_process_when_aborted",
"(",
")",
":",
"with",
"pipeline",
".",
"get_cat_pipeline",
"(",
"pipeline",
".",
"PIPE",
",",
"pipeline",
".",
"PIPE",
")",
"as",
"pl",
":",
"assert",
"(",
"len",
"(",
"pl",
".",
"commands",
")",
"==",
"1",
")",
"assert",
"(",
"pl",
".",
"commands",
"[",
"0",
"]",
".",
"_process",
".",
"poll",
"(",
")",
"is",
"None",
")",
"pl",
".",
"abort",
"(",
")",
"pipeline_wait",
"(",
"pl",
")"
] | process leaks must not occur when the pipeline is aborted . | train | false |
43,195 | def list_known_phylogenetic_metrics():
result = []
for name in dir(qiime.beta_metrics):
if name.startswith('dist_'):
result.append(name[5:])
result.sort()
return result
| [
"def",
"list_known_phylogenetic_metrics",
"(",
")",
":",
"result",
"=",
"[",
"]",
"for",
"name",
"in",
"dir",
"(",
"qiime",
".",
"beta_metrics",
")",
":",
"if",
"name",
".",
"startswith",
"(",
"'dist_'",
")",
":",
"result",
".",
"append",
"(",
"name",
"[",
"5",
":",
"]",
")",
"result",
".",
"sort",
"(",
")",
"return",
"result"
] | lists known phylogenetic metrics from cogent . | train | false |
43,196 | def getPage(url, contextFactory=None, response_transform=None, *args, **kwargs):
def _clientfactory(url, *args, **kwargs):
url = to_unicode(url)
timeout = kwargs.pop('timeout', 0)
f = client.ScrapyHTTPClientFactory(Request(url, *args, **kwargs), timeout=timeout)
f.deferred.addCallback((response_transform or (lambda r: r.body)))
return f
from twisted.web.client import _makeGetterFactory
return _makeGetterFactory(to_bytes(url), _clientfactory, contextFactory=contextFactory, *args, **kwargs).deferred
| [
"def",
"getPage",
"(",
"url",
",",
"contextFactory",
"=",
"None",
",",
"response_transform",
"=",
"None",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"def",
"_clientfactory",
"(",
"url",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"url",
"=",
"to_unicode",
"(",
"url",
")",
"timeout",
"=",
"kwargs",
".",
"pop",
"(",
"'timeout'",
",",
"0",
")",
"f",
"=",
"client",
".",
"ScrapyHTTPClientFactory",
"(",
"Request",
"(",
"url",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
",",
"timeout",
"=",
"timeout",
")",
"f",
".",
"deferred",
".",
"addCallback",
"(",
"(",
"response_transform",
"or",
"(",
"lambda",
"r",
":",
"r",
".",
"body",
")",
")",
")",
"return",
"f",
"from",
"twisted",
".",
"web",
".",
"client",
"import",
"_makeGetterFactory",
"return",
"_makeGetterFactory",
"(",
"to_bytes",
"(",
"url",
")",
",",
"_clientfactory",
",",
"contextFactory",
"=",
"contextFactory",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
".",
"deferred"
] | download a web page as a string . | train | false |
43,197 | @register.tag('with')
def do_with(parser, token):
bits = token.split_contents()
remaining_bits = bits[1:]
extra_context = token_kwargs(remaining_bits, parser, support_legacy=True)
if (not extra_context):
raise TemplateSyntaxError(('%r expected at least one variable assignment' % bits[0]))
if remaining_bits:
raise TemplateSyntaxError(('%r received an invalid token: %r' % (bits[0], remaining_bits[0])))
nodelist = parser.parse(('endwith',))
parser.delete_first_token()
return WithNode(None, None, nodelist, extra_context=extra_context)
| [
"@",
"register",
".",
"tag",
"(",
"'with'",
")",
"def",
"do_with",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"remaining_bits",
"=",
"bits",
"[",
"1",
":",
"]",
"extra_context",
"=",
"token_kwargs",
"(",
"remaining_bits",
",",
"parser",
",",
"support_legacy",
"=",
"True",
")",
"if",
"(",
"not",
"extra_context",
")",
":",
"raise",
"TemplateSyntaxError",
"(",
"(",
"'%r expected at least one variable assignment'",
"%",
"bits",
"[",
"0",
"]",
")",
")",
"if",
"remaining_bits",
":",
"raise",
"TemplateSyntaxError",
"(",
"(",
"'%r received an invalid token: %r'",
"%",
"(",
"bits",
"[",
"0",
"]",
",",
"remaining_bits",
"[",
"0",
"]",
")",
")",
")",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"'endwith'",
",",
")",
")",
"parser",
".",
"delete_first_token",
"(",
")",
"return",
"WithNode",
"(",
"None",
",",
"None",
",",
"nodelist",
",",
"extra_context",
"=",
"extra_context",
")"
] | adds one or more values to the context for caching and easy access . | train | false |
43,198 | def getSegmentsFromXIntersections(xIntersections, y):
segments = []
end = len(xIntersections)
if ((len(xIntersections) % 2) == 1):
end -= 1
for xIntersectionIndex in xrange(0, end, 2):
firstX = xIntersections[xIntersectionIndex]
secondX = xIntersections[(xIntersectionIndex + 1)]
if (firstX != secondX):
segments.append(getSegmentFromPoints(complex(firstX, y), complex(secondX, y)))
return segments
| [
"def",
"getSegmentsFromXIntersections",
"(",
"xIntersections",
",",
"y",
")",
":",
"segments",
"=",
"[",
"]",
"end",
"=",
"len",
"(",
"xIntersections",
")",
"if",
"(",
"(",
"len",
"(",
"xIntersections",
")",
"%",
"2",
")",
"==",
"1",
")",
":",
"end",
"-=",
"1",
"for",
"xIntersectionIndex",
"in",
"xrange",
"(",
"0",
",",
"end",
",",
"2",
")",
":",
"firstX",
"=",
"xIntersections",
"[",
"xIntersectionIndex",
"]",
"secondX",
"=",
"xIntersections",
"[",
"(",
"xIntersectionIndex",
"+",
"1",
")",
"]",
"if",
"(",
"firstX",
"!=",
"secondX",
")",
":",
"segments",
".",
"append",
"(",
"getSegmentFromPoints",
"(",
"complex",
"(",
"firstX",
",",
"y",
")",
",",
"complex",
"(",
"secondX",
",",
"y",
")",
")",
")",
"return",
"segments"
] | get endpoint segments from the x intersections . | train | false |
43,200 | def build_doc(doc, opts):
doclist = doc.split(u'\n')
newdoc = []
flags_doc = []
for line in doclist:
linelist = line.split()
if (not linelist):
continue
if (u',' in linelist[0]):
flag = linelist[0].split(u',')[0]
else:
flag = linelist[0]
attr = opts.get(flag)
if (attr is not None):
linelist[0] = (u'%s :\n ' % str(attr))
newline = u' '.join(linelist)
newdoc.append(newline)
elif line[0].isspace():
flags_doc.append(line)
return format_params(newdoc, flags_doc)
| [
"def",
"build_doc",
"(",
"doc",
",",
"opts",
")",
":",
"doclist",
"=",
"doc",
".",
"split",
"(",
"u'\\n'",
")",
"newdoc",
"=",
"[",
"]",
"flags_doc",
"=",
"[",
"]",
"for",
"line",
"in",
"doclist",
":",
"linelist",
"=",
"line",
".",
"split",
"(",
")",
"if",
"(",
"not",
"linelist",
")",
":",
"continue",
"if",
"(",
"u','",
"in",
"linelist",
"[",
"0",
"]",
")",
":",
"flag",
"=",
"linelist",
"[",
"0",
"]",
".",
"split",
"(",
"u','",
")",
"[",
"0",
"]",
"else",
":",
"flag",
"=",
"linelist",
"[",
"0",
"]",
"attr",
"=",
"opts",
".",
"get",
"(",
"flag",
")",
"if",
"(",
"attr",
"is",
"not",
"None",
")",
":",
"linelist",
"[",
"0",
"]",
"=",
"(",
"u'%s :\\n '",
"%",
"str",
"(",
"attr",
")",
")",
"newline",
"=",
"u' '",
".",
"join",
"(",
"linelist",
")",
"newdoc",
".",
"append",
"(",
"newline",
")",
"elif",
"line",
"[",
"0",
"]",
".",
"isspace",
"(",
")",
":",
"flags_doc",
".",
"append",
"(",
"line",
")",
"return",
"format_params",
"(",
"newdoc",
",",
"flags_doc",
")"
] | build docstring from doc and options parameters rep_doc : string documentation string opts : dict dictionary of option attributes and keys . | train | false |
43,201 | def GetVersionNamespace(version):
ns = nsMap[version]
if (not ns):
ns = serviceNsMap[version]
versionId = versionIdMap[version]
if (not versionId):
namespace = ns
else:
namespace = ('%s/%s' % (ns, versionId))
return namespace
| [
"def",
"GetVersionNamespace",
"(",
"version",
")",
":",
"ns",
"=",
"nsMap",
"[",
"version",
"]",
"if",
"(",
"not",
"ns",
")",
":",
"ns",
"=",
"serviceNsMap",
"[",
"version",
"]",
"versionId",
"=",
"versionIdMap",
"[",
"version",
"]",
"if",
"(",
"not",
"versionId",
")",
":",
"namespace",
"=",
"ns",
"else",
":",
"namespace",
"=",
"(",
"'%s/%s'",
"%",
"(",
"ns",
",",
"versionId",
")",
")",
"return",
"namespace"
] | get version namespace from version . | train | true |
43,202 | def YamlDumper(aff4object):
aff4object.Flush()
result = {}
for (attribute, values) in aff4object.synced_attributes.items():
result[attribute.predicate] = []
for value in values:
value = value.ToRDFValue()
result[attribute.predicate].append([value.__class__.__name__, value.SerializeToString(), str(value.age)])
return yaml.dump(dict(aff4_class=aff4object.__class__.__name__, _urn=aff4object.urn.SerializeToString(), attributes=result, age_policy=aff4object.age_policy))
| [
"def",
"YamlDumper",
"(",
"aff4object",
")",
":",
"aff4object",
".",
"Flush",
"(",
")",
"result",
"=",
"{",
"}",
"for",
"(",
"attribute",
",",
"values",
")",
"in",
"aff4object",
".",
"synced_attributes",
".",
"items",
"(",
")",
":",
"result",
"[",
"attribute",
".",
"predicate",
"]",
"=",
"[",
"]",
"for",
"value",
"in",
"values",
":",
"value",
"=",
"value",
".",
"ToRDFValue",
"(",
")",
"result",
"[",
"attribute",
".",
"predicate",
"]",
".",
"append",
"(",
"[",
"value",
".",
"__class__",
".",
"__name__",
",",
"value",
".",
"SerializeToString",
"(",
")",
",",
"str",
"(",
"value",
".",
"age",
")",
"]",
")",
"return",
"yaml",
".",
"dump",
"(",
"dict",
"(",
"aff4_class",
"=",
"aff4object",
".",
"__class__",
".",
"__name__",
",",
"_urn",
"=",
"aff4object",
".",
"urn",
".",
"SerializeToString",
"(",
")",
",",
"attributes",
"=",
"result",
",",
"age_policy",
"=",
"aff4object",
".",
"age_policy",
")",
")"
] | dumps the given aff4object into a yaml representation . | train | false |
43,203 | def get_default_fields():
default_field = DEFAULT_FIELD
default_field.update({'name': 'id', 'type': 'string', 'multiValued': 'false'})
return [default_field]
| [
"def",
"get_default_fields",
"(",
")",
":",
"default_field",
"=",
"DEFAULT_FIELD",
"default_field",
".",
"update",
"(",
"{",
"'name'",
":",
"'id'",
",",
"'type'",
":",
"'string'",
",",
"'multiValued'",
":",
"'false'",
"}",
")",
"return",
"[",
"default_field",
"]"
] | returns a list of default fields for the solr schema . | train | false |
43,204 | def prompt_choice_for_config(cookiecutter_dict, env, key, options, no_input):
rendered_options = [render_variable(env, raw, cookiecutter_dict) for raw in options]
if no_input:
return rendered_options[0]
return read_user_choice(key, rendered_options)
| [
"def",
"prompt_choice_for_config",
"(",
"cookiecutter_dict",
",",
"env",
",",
"key",
",",
"options",
",",
"no_input",
")",
":",
"rendered_options",
"=",
"[",
"render_variable",
"(",
"env",
",",
"raw",
",",
"cookiecutter_dict",
")",
"for",
"raw",
"in",
"options",
"]",
"if",
"no_input",
":",
"return",
"rendered_options",
"[",
"0",
"]",
"return",
"read_user_choice",
"(",
"key",
",",
"rendered_options",
")"
] | prompt the user which option to choose from the given . | train | true |
43,205 | def name_or_value(value):
try:
if issubclass(value, amqp_object.AMQPObject):
return value.NAME
except TypeError:
pass
if isinstance(value, frame.Method):
return value.method.NAME
if isinstance(value, amqp_object.AMQPObject):
return value.NAME
return canonical_str(value)
| [
"def",
"name_or_value",
"(",
"value",
")",
":",
"try",
":",
"if",
"issubclass",
"(",
"value",
",",
"amqp_object",
".",
"AMQPObject",
")",
":",
"return",
"value",
".",
"NAME",
"except",
"TypeError",
":",
"pass",
"if",
"isinstance",
"(",
"value",
",",
"frame",
".",
"Method",
")",
":",
"return",
"value",
".",
"method",
".",
"NAME",
"if",
"isinstance",
"(",
"value",
",",
"amqp_object",
".",
"AMQPObject",
")",
":",
"return",
"value",
".",
"NAME",
"return",
"canonical_str",
"(",
"value",
")"
] | will take frame objects . | train | false |
43,206 | def get_yaml_from_table(table):
header = {'cols': list(six.itervalues(table.columns))}
if table.meta:
header['meta'] = table.meta
return get_yaml_from_header(header)
| [
"def",
"get_yaml_from_table",
"(",
"table",
")",
":",
"header",
"=",
"{",
"'cols'",
":",
"list",
"(",
"six",
".",
"itervalues",
"(",
"table",
".",
"columns",
")",
")",
"}",
"if",
"table",
".",
"meta",
":",
"header",
"[",
"'meta'",
"]",
"=",
"table",
".",
"meta",
"return",
"get_yaml_from_header",
"(",
"header",
")"
] | return lines with a yaml representation of header content from the table . | train | false |
43,207 | @retry_on_failure
def test_gethostbyaddr():
socket.gethostbyaddr('localhost')
socket.gethostbyaddr('127.0.0.1')
if (is_cli and (not is_net40)):
socket.gethostbyaddr('<broadcast>')
| [
"@",
"retry_on_failure",
"def",
"test_gethostbyaddr",
"(",
")",
":",
"socket",
".",
"gethostbyaddr",
"(",
"'localhost'",
")",
"socket",
".",
"gethostbyaddr",
"(",
"'127.0.0.1'",
")",
"if",
"(",
"is_cli",
"and",
"(",
"not",
"is_net40",
")",
")",
":",
"socket",
".",
"gethostbyaddr",
"(",
"'<broadcast>'",
")"
] | tests socket . | train | false |
43,208 | @register.assignment_tag
def assignment_two_params(one, two):
return ('assignment_two_params - Expected result: %s, %s' % (one, two))
| [
"@",
"register",
".",
"assignment_tag",
"def",
"assignment_two_params",
"(",
"one",
",",
"two",
")",
":",
"return",
"(",
"'assignment_two_params - Expected result: %s, %s'",
"%",
"(",
"one",
",",
"two",
")",
")"
] | expected assignment_two_params __doc__ . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.