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 |
|---|---|---|---|---|---|
27,028 | def randomized_primality_testing(n, k):
for _ in range(k):
x = rsa.randnum.randint((n - 1))
if jacobi_witness(x, n):
return False
return True
| [
"def",
"randomized_primality_testing",
"(",
"n",
",",
"k",
")",
":",
"for",
"_",
"in",
"range",
"(",
"k",
")",
":",
"x",
"=",
"rsa",
".",
"randnum",
".",
"randint",
"(",
"(",
"n",
"-",
"1",
")",
")",
"if",
"jacobi_witness",
"(",
"x",
",",
"n",
... | calculates whether n is composite or prime returns false if the number is composite . | train | false |
27,029 | def write_source_files(*args, **kwargs):
for source in source_files:
_copy_from_to(source['copy_raw_from'], source['copy_raw_to'])
| [
"def",
"write_source_files",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"for",
"source",
"in",
"source_files",
":",
"_copy_from_to",
"(",
"source",
"[",
"'copy_raw_from'",
"]",
",",
"source",
"[",
"'copy_raw_to'",
"]",
")"
] | called by the page_writer_finalized signal to process source files . | train | false |
27,030 | def GenerateBinomialTable(m):
table = numpy.zeros(((m + 1), (m + 1)), dtype=numpy.float64)
for i in range((m + 1)):
table[(i, 0)] = 1
for i in range(1, (m + 1)):
for j in range(1, (m + 1)):
v = (table[((i - 1), j)] + table[((i - 1), (j - 1))])
assert ((not math.isnan(v)) and (not math.isinf(v)))
table[(i, j)] = v
return tf.convert_to_tensor(table)
| [
"def",
"GenerateBinomialTable",
"(",
"m",
")",
":",
"table",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"(",
"m",
"+",
"1",
")",
",",
"(",
"m",
"+",
"1",
")",
")",
",",
"dtype",
"=",
"numpy",
".",
"float64",
")",
"for",
"i",
"in",
"range",
"(",
"(... | generate binomial table . | train | false |
27,034 | def get_major_version(version=None):
version = get_complete_version(version)
parts = (2 if (version[2] == 0) else 3)
major = u'.'.join((str(x) for x in version[:parts]))
return major
| [
"def",
"get_major_version",
"(",
"version",
"=",
"None",
")",
":",
"version",
"=",
"get_complete_version",
"(",
"version",
")",
"parts",
"=",
"(",
"2",
"if",
"(",
"version",
"[",
"2",
"]",
"==",
"0",
")",
"else",
"3",
")",
"major",
"=",
"u'.'",
".",
... | returns major version from version . | train | false |
27,035 | def test_decompose_bases():
from .. import cgs
from ...constants import e
d = e.esu.unit.decompose(bases=cgs.bases)
assert (d._bases == [u.cm, u.g, u.s])
assert (d._powers == [Fraction(3, 2), 0.5, (-1)])
assert (d._scale == 1.0)
| [
"def",
"test_decompose_bases",
"(",
")",
":",
"from",
".",
".",
"import",
"cgs",
"from",
"...",
"constants",
"import",
"e",
"d",
"=",
"e",
".",
"esu",
".",
"unit",
".",
"decompose",
"(",
"bases",
"=",
"cgs",
".",
"bases",
")",
"assert",
"(",
"d",
"... | from issue #576 . | train | false |
27,036 | def splittext(text, line_len):
if (len(text) <= line_len):
return (text, '')
pos = min((len(text) - 1), line_len)
while ((pos > 0) and (text[pos] != ' ')):
pos -= 1
if (pos == 0):
pos = min(len(text), line_len)
while ((len(text) > pos) and (text[pos] != ' ')):
pos += 1
return (text[:pos], text[(pos + 1):].strip())
| [
"def",
"splittext",
"(",
"text",
",",
"line_len",
")",
":",
"if",
"(",
"len",
"(",
"text",
")",
"<=",
"line_len",
")",
":",
"return",
"(",
"text",
",",
"''",
")",
"pos",
"=",
"min",
"(",
"(",
"len",
"(",
"text",
")",
"-",
"1",
")",
",",
"line... | split the given text on space according to the given max line size return a 2-uple: * a line <= line_len if possible * the rest of the text which has to be reported on another line . | train | false |
27,037 | def _coerce_to_key(value):
if (value is None):
return None
(value, multiple) = datastore.NormalizeAndTypeCheck(value, (Model, Key, basestring))
if (len(value) > 1):
raise datastore_errors.BadArgumentError('Expected only one model or key')
value = value[0]
if isinstance(value, Model):
return value.key()
elif isinstance(value, basestring):
return Key(value)
else:
return value
| [
"def",
"_coerce_to_key",
"(",
"value",
")",
":",
"if",
"(",
"value",
"is",
"None",
")",
":",
"return",
"None",
"(",
"value",
",",
"multiple",
")",
"=",
"datastore",
".",
"NormalizeAndTypeCheck",
"(",
"value",
",",
"(",
"Model",
",",
"Key",
",",
"basest... | returns the values key . | train | false |
27,038 | def getcolumns(stream):
pipe = Pipeline()
pipe.append(ColumnsSelect())
return pipe(stream)
| [
"def",
"getcolumns",
"(",
"stream",
")",
":",
"pipe",
"=",
"Pipeline",
"(",
")",
"pipe",
".",
"append",
"(",
"ColumnsSelect",
"(",
")",
")",
"return",
"pipe",
"(",
"stream",
")"
] | function that return the colums of a select query . | train | false |
27,040 | def split_python_version(version=None):
major = ((version >> 24) & 255)
minor = ((version >> 16) & 255)
micro = ((version >> 8) & 255)
release_level = ((version >> 4) & 15)
serial = (version & 15)
release_level_string = RELEASE_LEVEL_NAMES.get(release_level, None)
if (not release_level_string):
raise ValueError, ('Bad release level 0x%x in version 0x%08x' % (release_level, version))
return (major, minor, micro, release_level_string, serial)
| [
"def",
"split_python_version",
"(",
"version",
"=",
"None",
")",
":",
"major",
"=",
"(",
"(",
"version",
">>",
"24",
")",
"&",
"255",
")",
"minor",
"=",
"(",
"(",
"version",
">>",
"16",
")",
"&",
"255",
")",
"micro",
"=",
"(",
"(",
"version",
">>... | convert a binary python version string into the same tuple that is found in sys . | train | false |
27,041 | def equateVertexesByFunction(equationFunction, points, prefix, revolutions, xmlElement):
prefixedEquationName = (prefix + equationFunction.__name__[len('equate'):].replace('Dot', '.').lower())
if (prefixedEquationName not in xmlElement.attributeDictionary):
return
equationResult = EquationResult(prefixedEquationName, revolutions, xmlElement)
for point in points:
returnValue = equationResult.getReturnValue(point)
if (returnValue == None):
print 'Warning, returnValue in alterVertexesByEquation in equation is None for:'
print point
print xmlElement
else:
equationFunction(point, returnValue)
equationResult.function.reset()
| [
"def",
"equateVertexesByFunction",
"(",
"equationFunction",
",",
"points",
",",
"prefix",
",",
"revolutions",
",",
"xmlElement",
")",
":",
"prefixedEquationName",
"=",
"(",
"prefix",
"+",
"equationFunction",
".",
"__name__",
"[",
"len",
"(",
"'equate'",
")",
":"... | get equated points by equation function . | train | false |
27,043 | def ifrc24h():
settings.base.theme = 'mobile'
settings.pr.request_dob = False
settings.pr.request_gender = False
settings.pr.lookup_duplicates = False
return s3_rest_controller('assess', '24h')
| [
"def",
"ifrc24h",
"(",
")",
":",
"settings",
".",
"base",
".",
"theme",
"=",
"'mobile'",
"settings",
".",
"pr",
".",
"request_dob",
"=",
"False",
"settings",
".",
"pr",
".",
"request_gender",
"=",
"False",
"settings",
".",
"pr",
".",
"lookup_duplicates",
... | custom function to demo mobile assessment collection . | train | false |
27,044 | def rosenbrock(individual):
return (sum((((100 * (((x * x) - y) ** 2)) + ((1.0 - x) ** 2)) for (x, y) in zip(individual[:(-1)], individual[1:]))),)
| [
"def",
"rosenbrock",
"(",
"individual",
")",
":",
"return",
"(",
"sum",
"(",
"(",
"(",
"(",
"100",
"*",
"(",
"(",
"(",
"x",
"*",
"x",
")",
"-",
"y",
")",
"**",
"2",
")",
")",
"+",
"(",
"(",
"1.0",
"-",
"x",
")",
"**",
"2",
")",
")",
"fo... | rosenbrock test objective function . | train | false |
27,045 | def test_version():
assert virtualenv.virtualenv_version, 'Should have version'
| [
"def",
"test_version",
"(",
")",
":",
"assert",
"virtualenv",
".",
"virtualenv_version",
",",
"'Should have version'"
] | test invocation with --version argument . | train | false |
27,047 | def _read_long(f):
return np.int32(struct.unpack('>l', f.read(4))[0])
| [
"def",
"_read_long",
"(",
"f",
")",
":",
"return",
"np",
".",
"int32",
"(",
"struct",
".",
"unpack",
"(",
"'>l'",
",",
"f",
".",
"read",
"(",
"4",
")",
")",
"[",
"0",
"]",
")"
] | read a signed 32-bit integer . | train | false |
27,048 | def binary_propagation(input, structure=None, mask=None, output=None, border_value=0, origin=0):
return binary_dilation(input, structure, (-1), mask, output, border_value, origin)
| [
"def",
"binary_propagation",
"(",
"input",
",",
"structure",
"=",
"None",
",",
"mask",
"=",
"None",
",",
"output",
"=",
"None",
",",
"border_value",
"=",
"0",
",",
"origin",
"=",
"0",
")",
":",
"return",
"binary_dilation",
"(",
"input",
",",
"structure",... | multi-dimensional binary propagation with the given structuring element . | train | false |
27,049 | def compute_node_get_by_host(context, host):
session = get_session()
with session.begin():
service = session.query(models.Service).filter_by(host=host, binary='monitor-bmc').first()
node = session.query(models.ComputeNode).options(joinedload('service')).filter_by(deleted=False, service_id=service.id)
return node.first()
| [
"def",
"compute_node_get_by_host",
"(",
"context",
",",
"host",
")",
":",
"session",
"=",
"get_session",
"(",
")",
"with",
"session",
".",
"begin",
"(",
")",
":",
"service",
"=",
"session",
".",
"query",
"(",
"models",
".",
"Service",
")",
".",
"filter_b... | get all capacity entries for the given host . | train | false |
27,050 | def test_legendre_table():
n = 10
for ch_type in ['eeg', 'meg']:
(lut1, n_fact1) = _get_legen_table(ch_type, n_coeff=25, force_calc=True)
lut1 = lut1[:, :(n - 1)].copy()
n_fact1 = n_fact1[:(n - 1)].copy()
(lut2, n_fact2) = _get_legen_table(ch_type, n_coeff=n, force_calc=True)
assert_allclose(lut1, lut2)
assert_allclose(n_fact1, n_fact2)
| [
"def",
"test_legendre_table",
"(",
")",
":",
"n",
"=",
"10",
"for",
"ch_type",
"in",
"[",
"'eeg'",
",",
"'meg'",
"]",
":",
"(",
"lut1",
",",
"n_fact1",
")",
"=",
"_get_legen_table",
"(",
"ch_type",
",",
"n_coeff",
"=",
"25",
",",
"force_calc",
"=",
"... | test legendre table calculation . | train | false |
27,052 | def incoming():
return s3db.inv_incoming()
| [
"def",
"incoming",
"(",
")",
":",
"return",
"s3db",
".",
"inv_incoming",
"(",
")"
] | incoming shipments for sites used from requests rheader when looking at transport status . | train | false |
27,053 | def make_soap_enveloped_saml_thingy(thingy, header_parts=None):
envelope = ElementTree.Element('')
envelope.tag = ('{%s}Envelope' % NAMESPACE)
if header_parts:
header = ElementTree.Element('')
header.tag = ('{%s}Header' % NAMESPACE)
envelope.append(header)
for part in header_parts:
part.become_child_element_of(header)
body = ElementTree.Element('')
body.tag = ('{%s}Body' % NAMESPACE)
envelope.append(body)
if isinstance(thingy, basestring):
logger.debug(('thingy0: %s' % thingy))
_part = thingy.split('\n')
thingy = ''.join(_part[1:])
thingy = thingy.replace(PREFIX, '')
logger.debug(('thingy: %s' % thingy))
_child = ElementTree.Element('')
_child.tag = ('{%s}FuddleMuddle' % DUMMY_NAMESPACE)
body.append(_child)
_str = ElementTree.tostring(envelope, encoding='UTF-8')
logger.debug(('SOAP precursor: %s' % _str))
i = _str.find(DUMMY_NAMESPACE)
j = _str.rfind('xmlns:', 0, i)
cut1 = _str[j:((i + len(DUMMY_NAMESPACE)) + 1)]
_str = _str.replace(cut1, '')
first = _str.find(('<%s:FuddleMuddle' % (cut1[6:9],)))
last = _str.find('>', (first + 14))
cut2 = _str[first:(last + 1)]
return _str.replace(cut2, thingy)
else:
thingy.become_child_element_of(body)
return ElementTree.tostring(envelope, encoding='UTF-8')
| [
"def",
"make_soap_enveloped_saml_thingy",
"(",
"thingy",
",",
"header_parts",
"=",
"None",
")",
":",
"envelope",
"=",
"ElementTree",
".",
"Element",
"(",
"''",
")",
"envelope",
".",
"tag",
"=",
"(",
"'{%s}Envelope'",
"%",
"NAMESPACE",
")",
"if",
"header_parts"... | returns a soap envelope containing a saml request as a text string . | train | true |
27,054 | def init_tests(pep8style):
report = pep8style.init_report(TestReport)
runner = pep8style.input_file
def run_tests(filename):
'Run all the tests from a file.'
lines = (readlines(filename) + ['#:\n'])
line_offset = 0
codes = ['Okay']
testcase = []
count_files = report.counters['files']
for (index, line) in enumerate(lines):
if (not line.startswith('#:')):
if codes:
testcase.append(line)
continue
if (codes and index):
if ('noeol' in codes):
testcase[(-1)] = testcase[(-1)].rstrip('\n')
codes = [c for c in codes if (c not in ('Okay', 'noeol'))]
runner(filename, testcase, expected=codes, line_offset=line_offset)
line_offset = (index + 1)
codes = line.split()[1:]
del testcase[:]
report.counters['files'] = (count_files + 1)
return report.counters['failed tests']
pep8style.runner = run_tests
| [
"def",
"init_tests",
"(",
"pep8style",
")",
":",
"report",
"=",
"pep8style",
".",
"init_report",
"(",
"TestReport",
")",
"runner",
"=",
"pep8style",
".",
"input_file",
"def",
"run_tests",
"(",
"filename",
")",
":",
"lines",
"=",
"(",
"readlines",
"(",
"fil... | initialize testing framework . | train | false |
27,055 | def stringify_expr(s, local_dict, global_dict, transformations):
tokens = []
input_code = StringIO(s.strip())
for (toknum, tokval, _, _, _) in generate_tokens(input_code.readline):
tokens.append((toknum, tokval))
for transform in transformations:
tokens = transform(tokens, local_dict, global_dict)
return untokenize(tokens)
| [
"def",
"stringify_expr",
"(",
"s",
",",
"local_dict",
",",
"global_dict",
",",
"transformations",
")",
":",
"tokens",
"=",
"[",
"]",
"input_code",
"=",
"StringIO",
"(",
"s",
".",
"strip",
"(",
")",
")",
"for",
"(",
"toknum",
",",
"tokval",
",",
"_",
... | converts the string s to python code . | train | false |
27,058 | def list_passwords(kwargs=None, call=None):
response = _query('support', 'password/list')
ret = {}
for item in response['list']:
if ('server' in item):
server = item['server']['name']
if (server not in ret):
ret[server] = []
ret[server].append(item)
return ret
| [
"def",
"list_passwords",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"response",
"=",
"_query",
"(",
"'support'",
",",
"'password/list'",
")",
"ret",
"=",
"{",
"}",
"for",
"item",
"in",
"response",
"[",
"'list'",
"]",
":",
"if",
"... | list all password on the account . | train | true |
27,059 | def _tgrep_macro_use_action(_s, _l, tokens):
assert (len(tokens) == 1)
assert (tokens[0][0] == u'@')
macro_name = tokens[0][1:]
def macro_use(n, m=None, l=None):
if ((m is None) or (macro_name not in m)):
raise TgrepException(u'macro {0} not defined'.format(macro_name))
return m[macro_name](n, m, l)
return macro_use
| [
"def",
"_tgrep_macro_use_action",
"(",
"_s",
",",
"_l",
",",
"tokens",
")",
":",
"assert",
"(",
"len",
"(",
"tokens",
")",
"==",
"1",
")",
"assert",
"(",
"tokens",
"[",
"0",
"]",
"[",
"0",
"]",
"==",
"u'@'",
")",
"macro_name",
"=",
"tokens",
"[",
... | builds a lambda function which looks up the macro name used . | train | false |
27,060 | def get_module_for_descriptor_internal(user, descriptor, student_data, course_id, track_function, xqueue_callback_url_prefix, request_token, position=None, wrap_xmodule_display=True, grade_bucket_type=None, static_asset_path='', user_location=None, disable_staff_debug_info=False, course=None):
(system, student_data) = get_module_system_for_user(user=user, student_data=student_data, descriptor=descriptor, course_id=course_id, track_function=track_function, xqueue_callback_url_prefix=xqueue_callback_url_prefix, position=position, wrap_xmodule_display=wrap_xmodule_display, grade_bucket_type=grade_bucket_type, static_asset_path=static_asset_path, user_location=user_location, request_token=request_token, disable_staff_debug_info=disable_staff_debug_info, course=course)
descriptor.bind_for_student(system, user.id, [partial(OverrideFieldData.wrap, user, course), partial(LmsFieldData, student_data=student_data)])
descriptor.scope_ids = descriptor.scope_ids._replace(user_id=user.id)
user_needs_access_check = (getattr(user, 'known', True) and (not isinstance(user, SystemUser)))
if user_needs_access_check:
if (not has_access(user, 'load', descriptor, course_id)):
return None
return descriptor
| [
"def",
"get_module_for_descriptor_internal",
"(",
"user",
",",
"descriptor",
",",
"student_data",
",",
"course_id",
",",
"track_function",
",",
"xqueue_callback_url_prefix",
",",
"request_token",
",",
"position",
"=",
"None",
",",
"wrap_xmodule_display",
"=",
"True",
... | actually implement get_module . | train | false |
27,061 | def cms_settings(request):
from menus.menu_pool import MenuRenderer
@lru_cache.lru_cache(maxsize=None)
def _get_menu_renderer():
from menus.menu_pool import menu_pool
return menu_pool.get_renderer(request)
toolbar = get_toolbar_from_request(request)
_get_menu_renderer = lazy(_get_menu_renderer, MenuRenderer)
return {'cms_menu_renderer': _get_menu_renderer(), 'cms_content_renderer': toolbar.content_renderer, 'CMS_MEDIA_URL': get_cms_setting('MEDIA_URL'), 'CMS_TEMPLATE': (lambda : get_template_from_request(request))}
| [
"def",
"cms_settings",
"(",
"request",
")",
":",
"from",
"menus",
".",
"menu_pool",
"import",
"MenuRenderer",
"@",
"lru_cache",
".",
"lru_cache",
"(",
"maxsize",
"=",
"None",
")",
"def",
"_get_menu_renderer",
"(",
")",
":",
"from",
"menus",
".",
"menu_pool",... | adds cms-related variables to the context . | train | false |
27,062 | def floating_ip_set_auto_assigned(context, address):
return IMPL.floating_ip_set_auto_assigned(context, address)
| [
"def",
"floating_ip_set_auto_assigned",
"(",
"context",
",",
"address",
")",
":",
"return",
"IMPL",
".",
"floating_ip_set_auto_assigned",
"(",
"context",
",",
"address",
")"
] | set auto_assigned flag to floating ip . | train | false |
27,063 | def _cmp_perm_lists(first, second):
return ({tuple(a) for a in first} == {tuple(a) for a in second})
| [
"def",
"_cmp_perm_lists",
"(",
"first",
",",
"second",
")",
":",
"return",
"(",
"{",
"tuple",
"(",
"a",
")",
"for",
"a",
"in",
"first",
"}",
"==",
"{",
"tuple",
"(",
"a",
")",
"for",
"a",
"in",
"second",
"}",
")"
] | compare two lists of permutations as sets . | train | false |
27,067 | def _clear_sleep_timer_service(service):
_apply_service(service, SonosDevice.clear_sleep_timer)
| [
"def",
"_clear_sleep_timer_service",
"(",
"service",
")",
":",
"_apply_service",
"(",
"service",
",",
"SonosDevice",
".",
"clear_sleep_timer",
")"
] | set a timer . | train | false |
27,069 | def import_file(module, dt, dn, force=False, pre_process=None, reset_permissions=False):
path = get_file_path(module, dt, dn)
ret = import_file_by_path(path, force, pre_process=pre_process, reset_permissions=reset_permissions)
return ret
| [
"def",
"import_file",
"(",
"module",
",",
"dt",
",",
"dn",
",",
"force",
"=",
"False",
",",
"pre_process",
"=",
"None",
",",
"reset_permissions",
"=",
"False",
")",
":",
"path",
"=",
"get_file_path",
"(",
"module",
",",
"dt",
",",
"dn",
")",
"ret",
"... | import filedescriptor in to module space . | train | false |
27,070 | def get_site_packages_directory():
import site
try:
loc = site.getsitepackages()
print (' tl.ops : site-packages in ', loc)
return loc
except:
print ' tl.ops : Cannot find package dir from virtual environment'
return False
| [
"def",
"get_site_packages_directory",
"(",
")",
":",
"import",
"site",
"try",
":",
"loc",
"=",
"site",
".",
"getsitepackages",
"(",
")",
"print",
"(",
"' tl.ops : site-packages in '",
",",
"loc",
")",
"return",
"loc",
"except",
":",
"print",
"' tl.ops : Cannot... | print and return the site-packages directory . | train | false |
27,071 | def dmp_gcd(f, g, u, K):
return dmp_inner_gcd(f, g, u, K)[0]
| [
"def",
"dmp_gcd",
"(",
"f",
",",
"g",
",",
"u",
",",
"K",
")",
":",
"return",
"dmp_inner_gcd",
"(",
"f",
",",
"g",
",",
"u",
",",
"K",
")",
"[",
"0",
"]"
] | computes polynomial gcd of f and g in k[x] . | train | false |
27,072 | def test_maxfilter_io():
info = read_info(raw_fname)
mf = info['proc_history'][1]['max_info']
assert_true(mf['sss_info']['frame'], FIFF.FIFFV_COORD_HEAD)
assert_true((5 <= mf['sss_info']['in_order'] <= 11))
assert_true((mf['sss_info']['out_order'] <= 5))
assert_true((mf['sss_info']['nchan'] > len(mf['sss_info']['components'])))
assert_equal(info['ch_names'][:mf['sss_info']['nchan']], mf['sss_ctc']['proj_items_chs'])
assert_equal(mf['sss_ctc']['decoupler'].shape, (mf['sss_info']['nchan'], mf['sss_info']['nchan']))
assert_equal(np.unique(np.diag(mf['sss_ctc']['decoupler'].toarray())), np.array([1.0], dtype=np.float32))
assert_equal(mf['sss_cal']['cal_corrs'].shape, (306, 14))
assert_equal(mf['sss_cal']['cal_chans'].shape, (306, 2))
vv_coils = [v for (k, v) in FIFF.items() if ('FIFFV_COIL_VV' in k)]
assert_true(all(((k in vv_coils) for k in set(mf['sss_cal']['cal_chans'][:, 1]))))
| [
"def",
"test_maxfilter_io",
"(",
")",
":",
"info",
"=",
"read_info",
"(",
"raw_fname",
")",
"mf",
"=",
"info",
"[",
"'proc_history'",
"]",
"[",
"1",
"]",
"[",
"'max_info'",
"]",
"assert_true",
"(",
"mf",
"[",
"'sss_info'",
"]",
"[",
"'frame'",
"]",
","... | test maxfilter io . | train | false |
27,073 | def coherence(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None, nfft=None, detrend='constant', axis=(-1)):
(freqs, Pxx) = welch(x, fs, window, nperseg, noverlap, nfft, detrend, axis=axis)
(_, Pyy) = welch(y, fs, window, nperseg, noverlap, nfft, detrend, axis=axis)
(_, Pxy) = csd(x, y, fs, window, nperseg, noverlap, nfft, detrend, axis=axis)
Cxy = (((np.abs(Pxy) ** 2) / Pxx) / Pyy)
return (freqs, Cxy)
| [
"def",
"coherence",
"(",
"x",
",",
"y",
",",
"fs",
"=",
"1.0",
",",
"window",
"=",
"'hann'",
",",
"nperseg",
"=",
"None",
",",
"noverlap",
"=",
"None",
",",
"nfft",
"=",
"None",
",",
"detrend",
"=",
"'constant'",
",",
"axis",
"=",
"(",
"-",
"1",
... | estimate the magnitude squared coherence estimate . | train | false |
27,074 | def _RegistryGetValue(key, value):
try:
return _RegistryGetValueUsingWinReg(key, value)
except ImportError:
pass
text = _RegistryQuery(key, value)
if (not text):
return None
match = re.search('REG_\\w+\\s+([^\\r]+)\\r\\n', text)
if (not match):
return None
return match.group(1)
| [
"def",
"_RegistryGetValue",
"(",
"key",
",",
"value",
")",
":",
"try",
":",
"return",
"_RegistryGetValueUsingWinReg",
"(",
"key",
",",
"value",
")",
"except",
"ImportError",
":",
"pass",
"text",
"=",
"_RegistryQuery",
"(",
"key",
",",
"value",
")",
"if",
"... | use _winreg or reg . | train | false |
27,075 | def fn(outs, mode=None, model=None, *args, **kwargs):
model = modelcontext(model)
return model.fn(outs, mode, *args, **kwargs)
| [
"def",
"fn",
"(",
"outs",
",",
"mode",
"=",
"None",
",",
"model",
"=",
"None",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"model",
"=",
"modelcontext",
"(",
"model",
")",
"return",
"model",
".",
"fn",
"(",
"outs",
",",
"mode",
",",
"*",
"... | compiles a theano function which returns the values of outs and takes values of model vars as arguments . | train | false |
27,077 | def create_test_suites(test_target=None):
if (test_target and ('/' in test_target)):
raise Exception('The delimiter in test_target should be a dot (.)')
loader = unittest.TestLoader()
return ([loader.loadTestsFromName(test_target)] if test_target else [loader.discover(CURR_DIR, pattern='*_test.py', top_level_dir=CURR_DIR)])
| [
"def",
"create_test_suites",
"(",
"test_target",
"=",
"None",
")",
":",
"if",
"(",
"test_target",
"and",
"(",
"'/'",
"in",
"test_target",
")",
")",
":",
"raise",
"Exception",
"(",
"'The delimiter in test_target should be a dot (.)'",
")",
"loader",
"=",
"unittest"... | creates test suites . | train | false |
27,078 | def cygpath(path):
if (not path.startswith(('/cygdrive', '//'))):
for (regex, parser, recurse) in _cygpath_parsers:
match = regex.match(path)
if match:
path = parser(*match.groups())
if recurse:
path = cygpath(path)
break
else:
path = _cygexpath(None, path)
return path
| [
"def",
"cygpath",
"(",
"path",
")",
":",
"if",
"(",
"not",
"path",
".",
"startswith",
"(",
"(",
"'/cygdrive'",
",",
"'//'",
")",
")",
")",
":",
"for",
"(",
"regex",
",",
"parser",
",",
"recurse",
")",
"in",
"_cygpath_parsers",
":",
"match",
"=",
"r... | use :meth:git . | train | true |
27,079 | def safe_readline(handle):
line = handle.readline()
if (not line):
raise ValueError('Unexpected end of stream.')
return line
| [
"def",
"safe_readline",
"(",
"handle",
")",
":",
"line",
"=",
"handle",
".",
"readline",
"(",
")",
"if",
"(",
"not",
"line",
")",
":",
"raise",
"ValueError",
"(",
"'Unexpected end of stream.'",
")",
"return",
"line"
] | safe_readline -> line read a line from an undohandle and return it . | train | false |
27,081 | def test_sanity():
import exceptions
special_types = ['UnicodeTranslateError', 'UnicodeEncodeError', 'UnicodeDecodeError']
exception_types = [x for x in exceptions.__dict__.keys() if ((x.startswith('__') == False) and (special_types.count(x) == 0))]
exception_types = [eval(('exceptions.' + x)) for x in exception_types]
for exception_type in exception_types:
except_list = [exception_type(), exception_type('a single param')]
for t_except in except_list:
try:
raise t_except
except exception_type as e:
pass
str_except = str(t_except)
Assert((not hasattr(t_except, '__getstate__')))
if (not is_silverlight):
encode_except = exceptions.UnicodeEncodeError('1', u'2', 3, 4, '5')
AreEqual(encode_except.encoding, '1')
AreEqual(encode_except.object, u'2')
AreEqual(encode_except.start, 3)
AreEqual(encode_except.end, 4)
AreEqual(encode_except.reason, '5')
AreEqual(encode_except.message, '')
exceptions.UnicodeDecodeError('1', '2', 3, 4, 'e')
decode_except = exceptions.UnicodeDecodeError('1', '2', 3, 4, '5')
AreEqual(decode_except.encoding, '1')
AreEqual(decode_except.object, '2')
AreEqual(decode_except.start, 3)
AreEqual(decode_except.end, 4)
AreEqual(decode_except.reason, '5')
AreEqual(decode_except.message, '')
translate_except = exceptions.UnicodeTranslateError(u'1', 2, 3, '4')
AreEqual(translate_except.object, u'1')
AreEqual(translate_except.start, 2)
AreEqual(translate_except.end, 3)
AreEqual(translate_except.reason, '4')
AreEqual(translate_except.message, '')
AreEqual(translate_except.encoding, None)
| [
"def",
"test_sanity",
"(",
")",
":",
"import",
"exceptions",
"special_types",
"=",
"[",
"'UnicodeTranslateError'",
",",
"'UnicodeEncodeError'",
",",
"'UnicodeDecodeError'",
"]",
"exception_types",
"=",
"[",
"x",
"for",
"x",
"in",
"exceptions",
".",
"__dict__",
"."... | URL minimal sanity check . | train | false |
27,084 | def serializable_property(name, docstring=None):
def set(obj, value):
setattr(obj, ('_' + name), value)
obj._needs_serialization = True
def get(obj):
return getattr(obj, ('_' + name))
return property(get, set, doc=docstring)
| [
"def",
"serializable_property",
"(",
"name",
",",
"docstring",
"=",
"None",
")",
":",
"def",
"set",
"(",
"obj",
",",
"value",
")",
":",
"setattr",
"(",
"obj",
",",
"(",
"'_'",
"+",
"name",
")",
",",
"value",
")",
"obj",
".",
"_needs_serialization",
"... | a property that helps tracking whether serialization is necessary . | train | false |
27,085 | @lru_cache((512 if settings.PRODUCTION else 0))
@register.filter(name='render_markdown_path', is_safe=True)
def render_markdown_path(markdown_file_path):
global md_extensions
if (md_extensions is None):
md_extensions = [markdown.extensions.toc.makeExtension(), markdown.extensions.admonition.makeExtension(), markdown.extensions.codehilite.makeExtension(linenums=False, guess_lang=False), zerver.lib.bugdown.fenced_code.makeExtension(), markdown_include.include.makeExtension(base_path='templates/zerver/help/include/')]
md_engine = markdown.Markdown(extensions=md_extensions)
md_engine.reset()
markdown_string = force_text(open(markdown_file_path).read())
html = md_engine.convert(markdown_string)
return mark_safe(html)
| [
"@",
"lru_cache",
"(",
"(",
"512",
"if",
"settings",
".",
"PRODUCTION",
"else",
"0",
")",
")",
"@",
"register",
".",
"filter",
"(",
"name",
"=",
"'render_markdown_path'",
",",
"is_safe",
"=",
"True",
")",
"def",
"render_markdown_path",
"(",
"markdown_file_pa... | given a path to a markdown file . | train | false |
27,086 | def minimum_cut_value(G, s, t, capacity='capacity', flow_func=None, **kwargs):
if (flow_func is None):
if kwargs:
raise nx.NetworkXError('You have to explicitly set a flow_func if you need to pass parameters via kwargs.')
flow_func = default_flow_func
if (not callable(flow_func)):
raise nx.NetworkXError('flow_func has to be callable.')
if ((kwargs.get('cutoff') is not None) and (flow_func in flow_funcs)):
raise nx.NetworkXError('cutoff should not be specified.')
R = flow_func(G, s, t, capacity=capacity, value_only=True, **kwargs)
return R.graph['flow_value']
| [
"def",
"minimum_cut_value",
"(",
"G",
",",
"s",
",",
"t",
",",
"capacity",
"=",
"'capacity'",
",",
"flow_func",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"flow_func",
"is",
"None",
")",
":",
"if",
"kwargs",
":",
"raise",
"nx",
".",
"Ne... | compute the value of a minimum -cut . | train | false |
27,087 | def set_object_info_cache(app, env, account, container, obj, resp):
cache_key = get_cache_key(account, container, obj)
if (('swift.infocache' in env) and (not resp)):
env['swift.infocache'].pop(cache_key, None)
return
info = headers_to_object_info(resp.headers, resp.status_int)
env.setdefault('swift.infocache', {})[cache_key] = info
return info
| [
"def",
"set_object_info_cache",
"(",
"app",
",",
"env",
",",
"account",
",",
"container",
",",
"obj",
",",
"resp",
")",
":",
"cache_key",
"=",
"get_cache_key",
"(",
"account",
",",
"container",
",",
"obj",
")",
"if",
"(",
"(",
"'swift.infocache'",
"in",
... | cache object info in the wsgi environment . | train | false |
27,088 | def deserialize_count_specs(text):
specs = text.splitlines()
specs = [line.split(',') for line in specs if line.strip()]
return {int(num): slug.strip().lower() for (num, slug) in specs}
| [
"def",
"deserialize_count_specs",
"(",
"text",
")",
":",
"specs",
"=",
"text",
".",
"splitlines",
"(",
")",
"specs",
"=",
"[",
"line",
".",
"split",
"(",
"','",
")",
"for",
"line",
"in",
"specs",
"if",
"line",
".",
"strip",
"(",
")",
"]",
"return",
... | takes a string in the format of: int . | train | false |
27,092 | def compute_frequency(t, theta):
dt = (t[1] - t[0])
f = ((np.diff(theta) / (2 * np.pi)) / dt)
tf = (0.5 * (t[1:] + t[:(-1)]))
return (tf, f)
| [
"def",
"compute_frequency",
"(",
"t",
",",
"theta",
")",
":",
"dt",
"=",
"(",
"t",
"[",
"1",
"]",
"-",
"t",
"[",
"0",
"]",
")",
"f",
"=",
"(",
"(",
"np",
".",
"diff",
"(",
"theta",
")",
"/",
"(",
"2",
"*",
"np",
".",
"pi",
")",
")",
"/"... | compute theta(t)/ . | train | false |
27,093 | def TopologicallySorted(graph, get_edges):
get_edges = memoize(get_edges)
visited = set()
visiting = set()
ordered_nodes = []
def Visit(node):
if (node in visiting):
raise CycleError(visiting)
if (node in visited):
return
visited.add(node)
visiting.add(node)
for neighbor in get_edges(node):
Visit(neighbor)
visiting.remove(node)
ordered_nodes.insert(0, node)
for node in sorted(graph):
Visit(node)
return ordered_nodes
| [
"def",
"TopologicallySorted",
"(",
"graph",
",",
"get_edges",
")",
":",
"get_edges",
"=",
"memoize",
"(",
"get_edges",
")",
"visited",
"=",
"set",
"(",
")",
"visiting",
"=",
"set",
"(",
")",
"ordered_nodes",
"=",
"[",
"]",
"def",
"Visit",
"(",
"node",
... | topologically sort based on a user provided edge definition . | train | false |
27,094 | def _play(black_policy_fn, white_policy_fn, board_size=19):
moves = []
(prev_state, prev_action) = (None, None)
curr_state = GoState(pachi_py.CreateBoard(board_size), BLACK)
while (not curr_state.board.is_terminal):
a = (black_policy_fn if (curr_state.color == BLACK) else white_policy_fn)(curr_state, prev_state, prev_action)
next_state = curr_state.act(a)
moves.append((curr_state, a, next_state))
(prev_state, prev_action) = (curr_state, a)
curr_state = next_state
return moves
| [
"def",
"_play",
"(",
"black_policy_fn",
",",
"white_policy_fn",
",",
"board_size",
"=",
"19",
")",
":",
"moves",
"=",
"[",
"]",
"(",
"prev_state",
",",
"prev_action",
")",
"=",
"(",
"None",
",",
"None",
")",
"curr_state",
"=",
"GoState",
"(",
"pachi_py",... | samples a trajectory for two player policies . | train | false |
27,095 | def create_transactions_table(session):
create_table = '\n CREATE TABLE IF NOT EXISTS transactions (\n txid_hash blob,\n operation tinyint,\n namespace text,\n path blob,\n start_time timestamp,\n is_xg boolean,\n in_progress blob,\n entity blob,\n task blob,\n PRIMARY KEY (txid_hash, operation, namespace, path)\n )\n '
statement = SimpleStatement(create_table, retry_policy=NO_RETRIES)
try:
session.execute(statement)
except cassandra.OperationTimedOut:
logging.warning('Encountered an operation timeout while creating transactions table. Waiting 1 minute for schema to settle.')
time.sleep(60)
raise
| [
"def",
"create_transactions_table",
"(",
"session",
")",
":",
"create_table",
"=",
"'\\n CREATE TABLE IF NOT EXISTS transactions (\\n txid_hash blob,\\n operation tinyint,\\n namespace text,\\n path blob,\\n start_time timestamp,\\n is_xg boolean,\\n in_progress... | create the table used for storing transaction metadata . | train | false |
27,096 | def _probvec(r, out):
n = r.shape[0]
r.sort()
out[0] = r[0]
for i in range(1, n):
out[i] = (r[i] - r[(i - 1)])
out[n] = (1 - r[(n - 1)])
| [
"def",
"_probvec",
"(",
"r",
",",
"out",
")",
":",
"n",
"=",
"r",
".",
"shape",
"[",
"0",
"]",
"r",
".",
"sort",
"(",
")",
"out",
"[",
"0",
"]",
"=",
"r",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"n",
")",
":",
"out",
... | fill out with randomly sampled probability vectors as rows . | train | true |
27,097 | def delete_command(client, args):
delete_task(client, args.task_id)
print 'Task {} deleted.'.format(args.task_id)
| [
"def",
"delete_command",
"(",
"client",
",",
"args",
")",
":",
"delete_task",
"(",
"client",
",",
"args",
".",
"task_id",
")",
"print",
"'Task {} deleted.'",
".",
"format",
"(",
"args",
".",
"task_id",
")"
] | deletes a zone . | train | false |
27,100 | def is_instrumented(instance, key):
return manager_of_class(instance.__class__).is_instrumented(key, search=True)
| [
"def",
"is_instrumented",
"(",
"instance",
",",
"key",
")",
":",
"return",
"manager_of_class",
"(",
"instance",
".",
"__class__",
")",
".",
"is_instrumented",
"(",
"key",
",",
"search",
"=",
"True",
")"
] | return true if the given attribute on the given instance is instrumented by the attributes package . | train | false |
27,101 | def skip_unless(condition, msg=None):
return skip_if((not condition), msg)
| [
"def",
"skip_unless",
"(",
"condition",
",",
"msg",
"=",
"None",
")",
":",
"return",
"skip_if",
"(",
"(",
"not",
"condition",
")",
",",
"msg",
")"
] | skip tests unless a condition holds . | train | false |
27,102 | def set_up_storage(schemas, storage_class, prefix='', addons=None, **kwargs):
_schemas = []
_schemas.extend(schemas)
for addon in (addons or []):
_schemas.extend(addon.models)
for schema in _schemas:
collection = '{0}{1}'.format(prefix, schema._name)
schema.set_storage(storage_class(db=database, collection=collection, **kwargs))
for index in getattr(schema, '__indices__', []):
database[collection].ensure_index(**index)
| [
"def",
"set_up_storage",
"(",
"schemas",
",",
"storage_class",
",",
"prefix",
"=",
"''",
",",
"addons",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"_schemas",
"=",
"[",
"]",
"_schemas",
".",
"extend",
"(",
"schemas",
")",
"for",
"addon",
"in",
"(",
... | setup the storage backend for each schema in schemas . | train | false |
27,103 | def get_attributes_by_tag_name(dom, tag_name):
elem = dom.getElementsByTagName(tag_name)[0]
return dict(list(elem.attributes.items()))
| [
"def",
"get_attributes_by_tag_name",
"(",
"dom",
",",
"tag_name",
")",
":",
"elem",
"=",
"dom",
".",
"getElementsByTagName",
"(",
"tag_name",
")",
"[",
"0",
"]",
"return",
"dict",
"(",
"list",
"(",
"elem",
".",
"attributes",
".",
"items",
"(",
")",
")",
... | retrieve an attribute from an xml document and return it in a consistent format only used with xml . | train | false |
27,107 | @must_be_logged_in
def unconfirmed_email_remove(auth=None):
user = auth.user
json_body = request.get_json()
try:
given_token = json_body['token']
except KeyError:
raise HTTPError(http.BAD_REQUEST, data={'message_short': 'Missing token', 'message_long': 'Must provide a token'})
user.clean_email_verifications(given_token=given_token)
user.save()
return ({'status': 'success', 'removed_email': json_body['address']}, 200)
| [
"@",
"must_be_logged_in",
"def",
"unconfirmed_email_remove",
"(",
"auth",
"=",
"None",
")",
":",
"user",
"=",
"auth",
".",
"user",
"json_body",
"=",
"request",
".",
"get_json",
"(",
")",
"try",
":",
"given_token",
"=",
"json_body",
"[",
"'token'",
"]",
"ex... | called at login if user cancels their merge or email add . | train | false |
27,108 | def acquireAttribute(objects, attr, default=_DEFAULT):
for obj in objects:
if hasattr(obj, attr):
return getattr(obj, attr)
if (default is not _DEFAULT):
return default
raise AttributeError(('attribute %r not found in %r' % (attr, objects)))
| [
"def",
"acquireAttribute",
"(",
"objects",
",",
"attr",
",",
"default",
"=",
"_DEFAULT",
")",
":",
"for",
"obj",
"in",
"objects",
":",
"if",
"hasattr",
"(",
"obj",
",",
"attr",
")",
":",
"return",
"getattr",
"(",
"obj",
",",
"attr",
")",
"if",
"(",
... | go through the list objects sequentially until we find one which has attribute attr . | train | false |
27,109 | def GSSAuth(auth_method, gss_deleg_creds=True):
if (_API == 'MIT'):
return _SSH_GSSAPI(auth_method, gss_deleg_creds)
elif ((_API == 'SSPI') and (os.name == 'nt')):
return _SSH_SSPI(auth_method, gss_deleg_creds)
else:
raise ImportError('Unable to import a GSS-API / SSPI module!')
| [
"def",
"GSSAuth",
"(",
"auth_method",
",",
"gss_deleg_creds",
"=",
"True",
")",
":",
"if",
"(",
"_API",
"==",
"'MIT'",
")",
":",
"return",
"_SSH_GSSAPI",
"(",
"auth_method",
",",
"gss_deleg_creds",
")",
"elif",
"(",
"(",
"_API",
"==",
"'SSPI'",
")",
"and... | provide ssh2 gss-api / sspi authentication . | train | true |
27,111 | def perform_suggestion(unit, form, request):
if (form.cleaned_data[u'target'][0] == u''):
messages.error(request, _(u'Your suggestion is empty!'))
return False
elif (not can_suggest(request.user, unit.translation)):
messages.error(request, _(u"You don't have privileges to add suggestions!"))
return False
recent_changes = Change.objects.content(True).filter(translation=unit.translation).exclude(user=None)
if (not recent_changes.exists()):
messages.info(request, _(u'There is currently no active translator for this translation, please consider becoming a translator as your suggestion might otherwise remain unreviewed.'))
Suggestion.objects.add(unit, join_plural(form.cleaned_data[u'target']), request)
return True
| [
"def",
"perform_suggestion",
"(",
"unit",
",",
"form",
",",
"request",
")",
":",
"if",
"(",
"form",
".",
"cleaned_data",
"[",
"u'target'",
"]",
"[",
"0",
"]",
"==",
"u''",
")",
":",
"messages",
".",
"error",
"(",
"request",
",",
"_",
"(",
"u'Your sug... | handle suggesion saving . | train | false |
27,113 | def addUnsupportedPointIndexes(alongAway):
addedUnsupportedPointIndexes = []
for pointIndex in xrange(len(alongAway.loop)):
point = alongAway.loop[pointIndex]
if (pointIndex not in alongAway.unsupportedPointIndexes):
if (not alongAway.getIsClockwisePointSupported(point)):
alongAway.unsupportedPointIndexes.append(pointIndex)
addedUnsupportedPointIndexes.append(pointIndex)
for pointIndex in addedUnsupportedPointIndexes:
point = alongAway.loop[pointIndex]
point.y += alongAway.maximumYPlus
| [
"def",
"addUnsupportedPointIndexes",
"(",
"alongAway",
")",
":",
"addedUnsupportedPointIndexes",
"=",
"[",
"]",
"for",
"pointIndex",
"in",
"xrange",
"(",
"len",
"(",
"alongAway",
".",
"loop",
")",
")",
":",
"point",
"=",
"alongAway",
".",
"loop",
"[",
"point... | add the indexes of the unsupported points . | train | false |
27,115 | def reverse_text_len(width, fs):
return int((width / (0.6 * fs)))
| [
"def",
"reverse_text_len",
"(",
"width",
",",
"fs",
")",
":",
"return",
"int",
"(",
"(",
"width",
"/",
"(",
"0.6",
"*",
"fs",
")",
")",
")"
] | approximation of text length . | train | false |
27,116 | def version_to_list(version):
ver_list = []
for p in version.split(u'.'):
try:
n = int(p)
except ValueError:
n = p
ver_list.append(n)
return ver_list
| [
"def",
"version_to_list",
"(",
"version",
")",
":",
"ver_list",
"=",
"[",
"]",
"for",
"p",
"in",
"version",
".",
"split",
"(",
"u'.'",
")",
":",
"try",
":",
"n",
"=",
"int",
"(",
"p",
")",
"except",
"ValueError",
":",
"n",
"=",
"p",
"ver_list",
"... | convert a version string to a list of numbers or strings . | train | false |
27,117 | def _test_read_factory(source, count):
fname = os.path.basename(source)
def test_read(self):
phx = PhyloXMLIO.read(source)
self.assertTrue(phx)
self.assertEqual(len(phx), count[0])
self.assertEqual(len(phx.other), count[1])
test_read.__doc__ = ('Read %s to produce a phyloXML object.' % fname)
return test_read
| [
"def",
"_test_read_factory",
"(",
"source",
",",
"count",
")",
":",
"fname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"source",
")",
"def",
"test_read",
"(",
"self",
")",
":",
"phx",
"=",
"PhyloXMLIO",
".",
"read",
"(",
"source",
")",
"self",
".... | generate a test method for read()ing the given source . | train | false |
27,118 | @register.filter(name='rule_member_name')
def rule_member_name(instance, member):
member = getattr(instance, member)
names = member.all()
return names
| [
"@",
"register",
".",
"filter",
"(",
"name",
"=",
"'rule_member_name'",
")",
"def",
"rule_member_name",
"(",
"instance",
",",
"member",
")",
":",
"member",
"=",
"getattr",
"(",
"instance",
",",
"member",
")",
"names",
"=",
"member",
".",
"all",
"(",
")",... | instance is a rule object . | train | false |
27,119 | def resolve_object(request, model, query, permission='base.view_resourcebase', permission_required=True, permission_msg=None):
obj = get_object_or_404(model, **query)
obj_to_check = obj.get_self_resource()
if settings.RESOURCE_PUBLISHING:
if ((not obj_to_check.is_published) and (not request.user.has_perm('publish_resourcebase', obj_to_check))):
raise Http404
allowed = True
if (permission.split('.')[(-1)] in ['change_layer_data', 'change_layer_style']):
if (obj.__class__.__name__ == 'Layer'):
obj_to_check = obj
if permission:
if (permission_required or (request.method != 'GET')):
allowed = request.user.has_perm(permission, obj_to_check)
if (not allowed):
mesg = (permission_msg or _('Permission Denied'))
raise PermissionDenied(mesg)
return obj
| [
"def",
"resolve_object",
"(",
"request",
",",
"model",
",",
"query",
",",
"permission",
"=",
"'base.view_resourcebase'",
",",
"permission_required",
"=",
"True",
",",
"permission_msg",
"=",
"None",
")",
":",
"obj",
"=",
"get_object_or_404",
"(",
"model",
",",
... | resolve an object using the provided query and check the optional permission . | train | false |
27,122 | def epoch_timestamp(dt):
return (dt - EPOCH).total_seconds()
| [
"def",
"epoch_timestamp",
"(",
"dt",
")",
":",
"return",
"(",
"dt",
"-",
"EPOCH",
")",
".",
"total_seconds",
"(",
")"
] | returns the number of seconds from the epoch to date . | train | false |
27,123 | def constraint_present(name, constraint_id, constraint_type, constraint_options=None, cibname=None):
return _item_present(name=name, item='constraint', item_id=constraint_id, item_type=constraint_type, create=None, extra_args=constraint_options, cibname=cibname)
| [
"def",
"constraint_present",
"(",
"name",
",",
"constraint_id",
",",
"constraint_type",
",",
"constraint_options",
"=",
"None",
",",
"cibname",
"=",
"None",
")",
":",
"return",
"_item_present",
"(",
"name",
"=",
"name",
",",
"item",
"=",
"'constraint'",
",",
... | ensure that a constraint is created should be run on one cluster node only can only be run on a node with a functional pacemaker/corosync name irrelevant . | train | true |
27,124 | def get_dict_names(dict1_path, dict2_path):
dict1_name = os.path.basename(dict1_path)
dict2_name = os.path.basename(dict2_path)
if (dict1_name == dict2_name):
dict1_name = 'dict1'
dict2_name = 'dict2'
return (dict1_name, dict2_name)
| [
"def",
"get_dict_names",
"(",
"dict1_path",
",",
"dict2_path",
")",
":",
"dict1_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"dict1_path",
")",
"dict2_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"dict2_path",
")",
"if",
"(",
"dict1_name",
... | get the name of the dictionaries for the end user . | train | false |
27,125 | def connect_to_cloud_blockstorage(region=None):
return _create_client(ep_name='volume', region=region)
| [
"def",
"connect_to_cloud_blockstorage",
"(",
"region",
"=",
"None",
")",
":",
"return",
"_create_client",
"(",
"ep_name",
"=",
"'volume'",
",",
"region",
"=",
"region",
")"
] | creates a client for working with cloud blockstorage . | train | false |
27,126 | @disable_for_loaddata
def flush_similar_cache_handler(sender, **kwargs):
entry = kwargs['instance']
if entry.is_visible:
EntryPublishedVectorBuilder().cache_flush()
| [
"@",
"disable_for_loaddata",
"def",
"flush_similar_cache_handler",
"(",
"sender",
",",
"**",
"kwargs",
")",
":",
"entry",
"=",
"kwargs",
"[",
"'instance'",
"]",
"if",
"entry",
".",
"is_visible",
":",
"EntryPublishedVectorBuilder",
"(",
")",
".",
"cache_flush",
"... | flush the cache of similar entries when an entry is saved . | train | false |
27,127 | def add_daily(name, user, command, environment=None):
add_task(name, '@daily', user, command, environment)
| [
"def",
"add_daily",
"(",
"name",
",",
"user",
",",
"command",
",",
"environment",
"=",
"None",
")",
":",
"add_task",
"(",
"name",
",",
"'@daily'",
",",
"user",
",",
"command",
",",
"environment",
")"
] | shortcut to add a daily cron task . | train | false |
27,128 | def v4_int_to_packed(address):
try:
return _compat_to_bytes(address, 4, u'big')
except (struct.error, OverflowError):
raise ValueError(u'Address negative or too large for IPv4')
| [
"def",
"v4_int_to_packed",
"(",
"address",
")",
":",
"try",
":",
"return",
"_compat_to_bytes",
"(",
"address",
",",
"4",
",",
"u'big'",
")",
"except",
"(",
"struct",
".",
"error",
",",
"OverflowError",
")",
":",
"raise",
"ValueError",
"(",
"u'Address negativ... | represent an address as 4 packed bytes in network order . | train | false |
27,129 | def remove_quotes(val):
if (val is None):
return
if ((val[0] in ('"', "'")) and (val[0] == val[(-1)])):
val = val[1:(-1)]
return val
| [
"def",
"remove_quotes",
"(",
"val",
")",
":",
"if",
"(",
"val",
"is",
"None",
")",
":",
"return",
"if",
"(",
"(",
"val",
"[",
"0",
"]",
"in",
"(",
"'\"'",
",",
"\"'\"",
")",
")",
"and",
"(",
"val",
"[",
"0",
"]",
"==",
"val",
"[",
"(",
"-",... | helper that removes surrounding quotes from strings . | train | false |
27,130 | def UnpackPlacemark(value):
pm_values = []
for x in value.split(','):
try:
decoded_x = base64hex.B64HexDecode(x.rstrip('='), padding=False).decode('utf-8')
except:
decoded_x = ''
pm_values.append(decoded_x)
return Placemark(*pm_values)
| [
"def",
"UnpackPlacemark",
"(",
"value",
")",
":",
"pm_values",
"=",
"[",
"]",
"for",
"x",
"in",
"value",
".",
"split",
"(",
"','",
")",
":",
"try",
":",
"decoded_x",
"=",
"base64hex",
".",
"B64HexDecode",
"(",
"x",
".",
"rstrip",
"(",
"'='",
")",
"... | converts from a comma-separated . | train | false |
27,131 | def signame(sig):
if (_signames is None):
_init_signames()
return (_signames.get(sig) or ('signal %d' % sig))
| [
"def",
"signame",
"(",
"sig",
")",
":",
"if",
"(",
"_signames",
"is",
"None",
")",
":",
"_init_signames",
"(",
")",
"return",
"(",
"_signames",
".",
"get",
"(",
"sig",
")",
"or",
"(",
"'signal %d'",
"%",
"sig",
")",
")"
] | return a symbolic name for a signal . | train | false |
27,132 | def create_sphere(rows=10, cols=10, depth=10, radius=1.0, offset=True, subdivisions=3, method='latitude'):
if (method == 'latitude'):
return _latitude(rows, cols, radius, offset)
elif (method == 'ico'):
return _ico(radius, subdivisions)
elif (method == 'cube'):
return _cube(rows, cols, depth, radius)
else:
raise Exception("Invalid method. Accepts: 'latitude', 'ico', 'cube'")
| [
"def",
"create_sphere",
"(",
"rows",
"=",
"10",
",",
"cols",
"=",
"10",
",",
"depth",
"=",
"10",
",",
"radius",
"=",
"1.0",
",",
"offset",
"=",
"True",
",",
"subdivisions",
"=",
"3",
",",
"method",
"=",
"'latitude'",
")",
":",
"if",
"(",
"method",
... | create a sphere parameters rows : int number of rows . | train | true |
27,134 | def test_summarize_model():
skip_if_no_matplotlib()
with open('model.pkl', 'wb') as f:
cPickle.dump(MLP(layers=[Linear(dim=5, layer_name='h0', irange=0.1)], nvis=10), f, protocol=cPickle.HIGHEST_PROTOCOL)
summarize('model.pkl')
os.remove('model.pkl')
| [
"def",
"test_summarize_model",
"(",
")",
":",
"skip_if_no_matplotlib",
"(",
")",
"with",
"open",
"(",
"'model.pkl'",
",",
"'wb'",
")",
"as",
"f",
":",
"cPickle",
".",
"dump",
"(",
"MLP",
"(",
"layers",
"=",
"[",
"Linear",
"(",
"dim",
"=",
"5",
",",
"... | asks the summarize_model . | train | false |
27,135 | def _raw_document_class(document_class):
marker = getattr(document_class, '_type_marker', None)
return (marker == _RAW_BSON_DOCUMENT_MARKER)
| [
"def",
"_raw_document_class",
"(",
"document_class",
")",
":",
"marker",
"=",
"getattr",
"(",
"document_class",
",",
"'_type_marker'",
",",
"None",
")",
"return",
"(",
"marker",
"==",
"_RAW_BSON_DOCUMENT_MARKER",
")"
] | determine if a document_class is a rawbsondocument class . | train | false |
27,136 | @register.tag('extends')
def do_extends(parser, token):
bits = token.split_contents()
if (len(bits) != 2):
raise TemplateSyntaxError(("'%s' takes one argument" % bits[0]))
parent_name = parser.compile_filter(bits[1])
nodelist = parser.parse()
if nodelist.get_nodes_by_type(ExtendsNode):
raise TemplateSyntaxError(("'%s' cannot appear more than once in the same template" % bits[0]))
return ExtendsNode(nodelist, parent_name)
| [
"@",
"register",
".",
"tag",
"(",
"'extends'",
")",
"def",
"do_extends",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"(",
"len",
"(",
"bits",
")",
"!=",
"2",
")",
":",
"raise",
"TemplateSyntaxEr... | signal that this template extends a parent template . | train | false |
27,139 | def getRandomNumber(N, randfunc):
S = randfunc((N / 8))
odd_bits = (N % 8)
if (odd_bits != 0):
char = (ord(randfunc(1)) >> (8 - odd_bits))
S = (chr(char) + S)
value = bytes_to_long(S)
value |= (2L ** (N - 1))
assert (size(value) >= N)
return value
| [
"def",
"getRandomNumber",
"(",
"N",
",",
"randfunc",
")",
":",
"S",
"=",
"randfunc",
"(",
"(",
"N",
"/",
"8",
")",
")",
"odd_bits",
"=",
"(",
"N",
"%",
"8",
")",
"if",
"(",
"odd_bits",
"!=",
"0",
")",
":",
"char",
"=",
"(",
"ord",
"(",
"randf... | getrandomnumber:long return an n-bit random number . | train | false |
27,140 | def _parse_exclude(exclude_file):
if os.path.isfile(exclude_file):
exclude = excludemod.parseExcludeFile(exclude_file, (lambda x: None))
else:
exclude = dict()
return exclude
| [
"def",
"_parse_exclude",
"(",
"exclude_file",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"exclude_file",
")",
":",
"exclude",
"=",
"excludemod",
".",
"parseExcludeFile",
"(",
"exclude_file",
",",
"(",
"lambda",
"x",
":",
"None",
")",
")",
"el... | parse an exclude file . | train | true |
27,141 | def safe(text):
return _safe(text)
| [
"def",
"safe",
"(",
"text",
")",
":",
"return",
"_safe",
"(",
"text",
")"
] | marks the value as a string that should not be auto-escaped . | train | false |
27,142 | def set_replication_enabled(status, host=None, core_name=None):
if ((not _is_master()) and (_get_none_or_value(host) is None)):
return _get_return_dict(False, errors=['Only minions configured as master can run this'])
cmd = ('enablereplication' if status else 'disablereplication')
if ((_get_none_or_value(core_name) is None) and _check_for_cores()):
ret = _get_return_dict()
success = True
for name in __opts__['solr.cores']:
resp = set_replication_enabled(status, host, name)
if (not resp['success']):
success = False
data = {name: {'data': resp['data']}}
ret = _update_return_dict(ret, success, data, resp['errors'], resp['warnings'])
return ret
elif status:
return _replication_request(cmd, host=host, core_name=core_name)
else:
return _replication_request(cmd, host=host, core_name=core_name)
| [
"def",
"set_replication_enabled",
"(",
"status",
",",
"host",
"=",
"None",
",",
"core_name",
"=",
"None",
")",
":",
"if",
"(",
"(",
"not",
"_is_master",
"(",
")",
")",
"and",
"(",
"_get_none_or_value",
"(",
"host",
")",
"is",
"None",
")",
")",
":",
"... | master only sets the master to ignore poll requests from the slaves . | train | true |
27,143 | def did_composer_install(dir):
lockFile = '{0}/vendor'.format(dir)
if os.path.exists(lockFile):
return True
return False
| [
"def",
"did_composer_install",
"(",
"dir",
")",
":",
"lockFile",
"=",
"'{0}/vendor'",
".",
"format",
"(",
"dir",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"lockFile",
")",
":",
"return",
"True",
"return",
"False"
] | test to see if the vendor directory exists in this directory dir directory location of the composer . | train | true |
27,145 | @decorator.decorator
def use_clip_fps_by_default(f, clip, *a, **k):
def fun(fps):
if (fps is not None):
return fps
elif (hasattr(clip, 'fps') and (clip.fps is not None)):
return clip.fps
else:
raise AttributeError(("No 'fps' (frames per second) attribute specified for function %s and the clip has no 'fps' attribute. Either provide e.g. fps=24 in the arguments of the function, or define the clip's fps with `clip.fps=24`" % f.__name__))
if hasattr(f, 'func_code'):
func_code = f.func_code
else:
func_code = f.__code__
names = func_code.co_varnames[1:]
new_a = [(fun(arg) if (name == 'fps') else arg) for (arg, name) in zip(a, names)]
new_kw = {k: (fun(v) if (k == 'fps') else v) for (k, v) in k.items()}
return f(clip, *new_a, **new_kw)
| [
"@",
"decorator",
".",
"decorator",
"def",
"use_clip_fps_by_default",
"(",
"f",
",",
"clip",
",",
"*",
"a",
",",
"**",
"k",
")",
":",
"def",
"fun",
"(",
"fps",
")",
":",
"if",
"(",
"fps",
"is",
"not",
"None",
")",
":",
"return",
"fps",
"elif",
"(... | will use clip . | train | false |
27,146 | def _gorg(a):
assert isinstance(a, GenericMeta)
while (a.__origin__ is not None):
a = a.__origin__
return a
| [
"def",
"_gorg",
"(",
"a",
")",
":",
"assert",
"isinstance",
"(",
"a",
",",
"GenericMeta",
")",
"while",
"(",
"a",
".",
"__origin__",
"is",
"not",
"None",
")",
":",
"a",
"=",
"a",
".",
"__origin__",
"return",
"a"
] | return the farthest origin of a generic class . | train | true |
27,147 | def _add_edge_filter(values, graph):
values = values.astype(int)
center = values[(len(values) // 2)]
for value in values:
if ((value != center) and (not graph.has_edge(center, value))):
graph.add_edge(center, value)
return 0.0
| [
"def",
"_add_edge_filter",
"(",
"values",
",",
"graph",
")",
":",
"values",
"=",
"values",
".",
"astype",
"(",
"int",
")",
"center",
"=",
"values",
"[",
"(",
"len",
"(",
"values",
")",
"//",
"2",
")",
"]",
"for",
"value",
"in",
"values",
":",
"if",... | create edge in graph between central element of values and the rest . | train | false |
27,148 | def get_diff_renderer_class():
return _diff_renderer_class
| [
"def",
"get_diff_renderer_class",
"(",
")",
":",
"return",
"_diff_renderer_class"
] | returns the diffrenderer class used for rendering diffs . | train | false |
27,149 | def systemInformationType5bis():
a = L2PseudoLength(l2pLength=18)
b = TpPd(pd=6)
c = MessageType(mesType=5)
d = NeighbourCellsDescription()
packet = (((a / b) / c) / d)
return packet
| [
"def",
"systemInformationType5bis",
"(",
")",
":",
"a",
"=",
"L2PseudoLength",
"(",
"l2pLength",
"=",
"18",
")",
"b",
"=",
"TpPd",
"(",
"pd",
"=",
"6",
")",
"c",
"=",
"MessageType",
"(",
"mesType",
"=",
"5",
")",
"d",
"=",
"NeighbourCellsDescription",
... | system information type 5bis section 9 . | train | true |
27,150 | def decimal_to_dt(dec):
if (dec is None):
return None
integer = int(dec)
micro = ((dec - decimal.Decimal(integer)) * decimal.Decimal(units.M))
daittyme = datetime.datetime.utcfromtimestamp(integer)
return daittyme.replace(microsecond=int(round(micro)))
| [
"def",
"decimal_to_dt",
"(",
"dec",
")",
":",
"if",
"(",
"dec",
"is",
"None",
")",
":",
"return",
"None",
"integer",
"=",
"int",
"(",
"dec",
")",
"micro",
"=",
"(",
"(",
"dec",
"-",
"decimal",
".",
"Decimal",
"(",
"integer",
")",
")",
"*",
"decim... | return a datetime from decimal unixtime format . | train | false |
27,152 | def _int_inversion(g, x, t):
(b, a) = _get_coeff_exp(g.argument, x)
(C, g) = _inflate_fox_h(meijerg(g.an, g.aother, g.bm, g.bother, (b / (t ** a))), (- a))
return ((C / t) * g)
| [
"def",
"_int_inversion",
"(",
"g",
",",
"x",
",",
"t",
")",
":",
"(",
"b",
",",
"a",
")",
"=",
"_get_coeff_exp",
"(",
"g",
".",
"argument",
",",
"x",
")",
"(",
"C",
",",
"g",
")",
"=",
"_inflate_fox_h",
"(",
"meijerg",
"(",
"g",
".",
"an",
",... | compute the laplace inversion integral . | train | false |
27,153 | @webob.dec.wsgify
@microversion.version_handler(1.2)
def delete_resource_class(req):
name = util.wsgi_path_item(req.environ, 'name')
context = req.environ['placement.context']
rc = objects.ResourceClass.get_by_name(context, name)
try:
rc.destroy()
except exception.ResourceClassCannotDeleteStandard as exc:
raise webob.exc.HTTPBadRequest((_('Cannot delete standard resource class %(rp_name)s: %(error)s') % {'rp_name': name, 'error': exc}), json_formatter=util.json_error_formatter)
except exception.ResourceClassInUse as exc:
raise webob.exc.HTTPConflict((_('Unable to delete resource class %(rp_name)s: %(error)s') % {'rp_name': name, 'error': exc}), json_formatter=util.json_error_formatter)
req.response.status = 204
req.response.content_type = None
return req.response
| [
"@",
"webob",
".",
"dec",
".",
"wsgify",
"@",
"microversion",
".",
"version_handler",
"(",
"1.2",
")",
"def",
"delete_resource_class",
"(",
"req",
")",
":",
"name",
"=",
"util",
".",
"wsgi_path_item",
"(",
"req",
".",
"environ",
",",
"'name'",
")",
"cont... | delete to destroy a single resource class . | train | false |
27,154 | def test_imap_many_folders_one_role(monkeypatch, constants):
folders = constants['imap_folders']
duplicates = [(('\\HasNoChildren', '\\Trash'), '/', u'[Gmail]/Trash'), ('\\HasNoChildren', '/', u'[Gmail]/Sent')]
folders += duplicates
client = patch_generic_client(monkeypatch, folders)
raw_folders = client.folders()
folder_names = client.folder_names()
for role in ['inbox', 'trash', 'drafts', 'sent', 'spam']:
assert (role in folder_names)
number_roles = (2 if (role in ['sent', 'trash']) else 1)
test_set = filter((lambda x: (x == role)), map((lambda y: y.role), raw_folders))
assert (len(test_set) == number_roles), 'assigned wrong number of {}'.format(role)
| [
"def",
"test_imap_many_folders_one_role",
"(",
"monkeypatch",
",",
"constants",
")",
":",
"folders",
"=",
"constants",
"[",
"'imap_folders'",
"]",
"duplicates",
"=",
"[",
"(",
"(",
"'\\\\HasNoChildren'",
",",
"'\\\\Trash'",
")",
",",
"'/'",
",",
"u'[Gmail]/Trash'"... | tests that accounts with many folders with similar system folders have only one role . | train | false |
27,155 | def startsWith(str, prefix):
return (str[:len(prefix)] == prefix)
| [
"def",
"startsWith",
"(",
"str",
",",
"prefix",
")",
":",
"return",
"(",
"str",
"[",
":",
"len",
"(",
"prefix",
")",
"]",
"==",
"prefix",
")"
] | return true iff _str_ starts with _prefix_ . | train | false |
27,156 | def disable_paging(remote_conn, cmd='terminal length 0'):
cmd = cmd.strip()
remote_conn.send((cmd + '\n'))
time.sleep(1)
clear_buffer(remote_conn)
| [
"def",
"disable_paging",
"(",
"remote_conn",
",",
"cmd",
"=",
"'terminal length 0'",
")",
":",
"cmd",
"=",
"cmd",
".",
"strip",
"(",
")",
"remote_conn",
".",
"send",
"(",
"(",
"cmd",
"+",
"'\\n'",
")",
")",
"time",
".",
"sleep",
"(",
"1",
")",
"clear... | disable the paging of output . | train | false |
27,157 | def load_collectors(paths=None, filter=None):
collectors = {}
log = logging.getLogger('diamond')
if (paths is None):
return
if isinstance(paths, basestring):
paths = paths.split(',')
paths = map(str.strip, paths)
load_include_path(paths)
for path in paths:
if (not os.path.exists(path)):
raise OSError(('Directory does not exist: %s' % path))
if (path.endswith('tests') or path.endswith('fixtures')):
return collectors
for f in os.listdir(path):
fpath = os.path.join(path, f)
if os.path.isdir(fpath):
subcollectors = load_collectors([fpath])
for key in subcollectors:
collectors[key] = subcollectors[key]
elif (os.path.isfile(fpath) and (len(f) > 3) and (f[(-3):] == '.py') and (f[0:4] != 'test') and (f[0] != '.')):
if (filter and (os.path.join(path, f) != filter)):
continue
modname = f[:(-3)]
try:
mod = __import__(modname, globals(), locals(), ['*'])
except (KeyboardInterrupt, SystemExit) as err:
log.error(('System or keyboard interrupt while loading module %s' % modname))
if isinstance(err, SystemExit):
sys.exit(err.code)
raise KeyboardInterrupt
except:
log.error('Failed to import module: %s. %s', modname, traceback.format_exc())
continue
for attrname in dir(mod):
attr = getattr(mod, attrname)
if (inspect.isclass(attr) and issubclass(attr, Collector) and (attr != Collector)):
if attrname.startswith('parent_'):
continue
fqcn = '.'.join([modname, attrname])
try:
cls = load_dynamic_class(fqcn, Collector)
collectors[cls.__name__] = cls
except Exception:
log.error('Failed to load Collector: %s. %s', fqcn, traceback.format_exc())
continue
return collectors
| [
"def",
"load_collectors",
"(",
"paths",
"=",
"None",
",",
"filter",
"=",
"None",
")",
":",
"collectors",
"=",
"{",
"}",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"'diamond'",
")",
"if",
"(",
"paths",
"is",
"None",
")",
":",
"return",
"if",
"isins... | load all collectors . | train | false |
27,158 | @check_job_permission
def job_single_logs(request, job, offset=LOG_OFFSET_BYTES):
def cmp_exec_time(task1, task2):
return cmp(task1.execStartTimeMs, task2.execStartTimeMs)
task = None
failed_tasks = job.filter_tasks(task_states=('failed',))
failed_tasks.sort(cmp_exec_time)
if failed_tasks:
task = failed_tasks[0]
if ((not task.taskAttemptIds) and (len(failed_tasks) > 1)):
task = failed_tasks[1]
else:
task_states = ['running', 'succeeded']
if job.is_mr2:
task_states.append('scheduled')
recent_tasks = job.filter_tasks(task_states=task_states, task_types=('map', 'reduce'))
recent_tasks.sort(cmp_exec_time, reverse=True)
if recent_tasks:
task = recent_tasks[0]
if ((task is None) or (not task.taskAttemptIds)):
raise PopupException((_('No tasks found for job %(id)s.') % {'id': job.jobId}))
params = {'job': job.jobId, 'taskid': task.taskId, 'attemptid': task.taskAttemptIds[(-1)], 'offset': offset}
return single_task_attempt_logs(request, **params)
| [
"@",
"check_job_permission",
"def",
"job_single_logs",
"(",
"request",
",",
"job",
",",
"offset",
"=",
"LOG_OFFSET_BYTES",
")",
":",
"def",
"cmp_exec_time",
"(",
"task1",
",",
"task2",
")",
":",
"return",
"cmp",
"(",
"task1",
".",
"execStartTimeMs",
",",
"ta... | try to smartly detect the most useful task attempt and get its mr logs . | train | false |
27,160 | def _get_suggestion_from_model(suggestion_model):
return feedback_domain.Suggestion(suggestion_model.id, suggestion_model.author_id, suggestion_model.exploration_id, suggestion_model.exploration_version, suggestion_model.state_name, suggestion_model.description, suggestion_model.state_content)
| [
"def",
"_get_suggestion_from_model",
"(",
"suggestion_model",
")",
":",
"return",
"feedback_domain",
".",
"Suggestion",
"(",
"suggestion_model",
".",
"id",
",",
"suggestion_model",
".",
"author_id",
",",
"suggestion_model",
".",
"exploration_id",
",",
"suggestion_model"... | converts the given suggestionmodel to a suggestion object . | train | false |
27,163 | def sync_states(saltenv=None, refresh=True):
ret = _sync('states', saltenv)
if refresh:
refresh_modules()
return ret
| [
"def",
"sync_states",
"(",
"saltenv",
"=",
"None",
",",
"refresh",
"=",
"True",
")",
":",
"ret",
"=",
"_sync",
"(",
"'states'",
",",
"saltenv",
")",
"if",
"refresh",
":",
"refresh_modules",
"(",
")",
"return",
"ret"
] | sync state modules from salt://_states to the master saltenv : base the fileserver environment from which to sync . | train | false |
27,164 | def get_flattened_track(track):
flat_track = [track]
if (track.can_show_chains and track.is_showing_chains):
instruments = list(find_instrument_devices(track))
flat_track.extend([c for c in instruments[0].chains])
return flat_track
| [
"def",
"get_flattened_track",
"(",
"track",
")",
":",
"flat_track",
"=",
"[",
"track",
"]",
"if",
"(",
"track",
".",
"can_show_chains",
"and",
"track",
".",
"is_showing_chains",
")",
":",
"instruments",
"=",
"list",
"(",
"find_instrument_devices",
"(",
"track"... | returns a flat list of a track with its instrument chains . | train | false |
27,166 | def _check_hdr_version(header):
tags = ['Brain Vision Data Exchange Header File Version 1.0', 'Brain Vision Data Exchange Header File Version 2.0']
if (header not in tags):
raise ValueError(('Currently only support %r, not %rContact MNE-Developers for support.' % (str(tags), header)))
| [
"def",
"_check_hdr_version",
"(",
"header",
")",
":",
"tags",
"=",
"[",
"'Brain Vision Data Exchange Header File Version 1.0'",
",",
"'Brain Vision Data Exchange Header File Version 2.0'",
"]",
"if",
"(",
"header",
"not",
"in",
"tags",
")",
":",
"raise",
"ValueError",
"... | check the header version . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.