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 |
|---|---|---|---|---|---|
26,629 | def GzipDecode(s):
with closing(StringIO(s)) as sio:
with gzip.GzipFile(fileobj=sio, mode='rb') as gzfile:
return gzfile.read()
| [
"def",
"GzipDecode",
"(",
"s",
")",
":",
"with",
"closing",
"(",
"StringIO",
"(",
"s",
")",
")",
"as",
"sio",
":",
"with",
"gzip",
".",
"GzipFile",
"(",
"fileobj",
"=",
"sio",
",",
"mode",
"=",
"'rb'",
")",
"as",
"gzfile",
":",
"return",
"gzfile",
... | decompresses s and returns the result as a byte string . | train | false |
26,630 | def getGeometryOutputByOffset(geometryOutput, interpolationOffset, xmlElement):
geometryOutputValues = geometryOutput.values()
if (len(geometryOutputValues) < 1):
return geometryOutput
connectionStart = interpolationOffset.getVector3ByPortion(PortionDirection(0.0))
connectionEnd = interpolationOffset.getVector3ByPortion(PortionDirection(1.0))
return getGeometryOutputByConnection(connectionEnd, connectionStart, geometryOutput, xmlElement)
| [
"def",
"getGeometryOutputByOffset",
"(",
"geometryOutput",
",",
"interpolationOffset",
",",
"xmlElement",
")",
":",
"geometryOutputValues",
"=",
"geometryOutput",
".",
"values",
"(",
")",
"if",
"(",
"len",
"(",
"geometryOutputValues",
")",
"<",
"1",
")",
":",
"r... | get solid output by interpolationoffset . | train | false |
26,631 | def set_private_viewability_of_exploration(committer_id, exploration_id, viewable_if_private):
if (not Actor(committer_id).can_change_private_viewability(feconf.ACTIVITY_TYPE_EXPLORATION, exploration_id)):
logging.error(('User %s tried to change private viewability of exploration %s but was refused permission.' % (committer_id, exploration_id)))
raise Exception('The viewability status of this exploration cannot be changed.')
exploration_rights = get_exploration_rights(exploration_id)
old_viewable_if_private = exploration_rights.viewable_if_private
if (old_viewable_if_private == viewable_if_private):
raise Exception(('Trying to change viewability status of this exploration to %s, but that is already the current value.' % viewable_if_private))
exploration_rights.viewable_if_private = viewable_if_private
commit_cmds = [{'cmd': CMD_CHANGE_PRIVATE_VIEWABILITY, 'old_viewable_if_private': old_viewable_if_private, 'new_viewable_if_private': viewable_if_private}]
commit_message = ('Made exploration viewable to anyone with the link.' if viewable_if_private else 'Made exploration viewable only to invited playtesters.')
_save_activity_rights(committer_id, exploration_rights, feconf.ACTIVITY_TYPE_EXPLORATION, commit_message, commit_cmds)
_update_exploration_summary(exploration_rights)
| [
"def",
"set_private_viewability_of_exploration",
"(",
"committer_id",
",",
"exploration_id",
",",
"viewable_if_private",
")",
":",
"if",
"(",
"not",
"Actor",
"(",
"committer_id",
")",
".",
"can_change_private_viewability",
"(",
"feconf",
".",
"ACTIVITY_TYPE_EXPLORATION",
... | sets the viewable_if_private attribute for an explorations rights object . | train | false |
26,634 | def get_stream_when_active(stream_name, region=None, key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
stream_status = None
attempt = 0
max_retry_delay = 10
while (stream_status != 'ACTIVE'):
time.sleep(_jittered_backoff(attempt, max_retry_delay))
attempt += 1
stream_response = _get_basic_stream(stream_name, conn)
if ('error' in stream_response):
return stream_response
stream_status = stream_response['result']['StreamDescription']['StreamStatus']
if stream_response['result']['StreamDescription']['HasMoreShards']:
stream_response = _get_full_stream(stream_name, region, key, keyid, profile)
return stream_response
| [
"def",
"get_stream_when_active",
"(",
"stream_name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
... | get complete stream info from aws . | train | true |
26,635 | def _passthrough_scorer(estimator, *args, **kwargs):
return estimator.score(*args, **kwargs)
| [
"def",
"_passthrough_scorer",
"(",
"estimator",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"estimator",
".",
"score",
"(",
"*",
"args",
",",
"**",
"kwargs",
")"
] | function that wraps estimator . | train | false |
26,636 | @mock_streams('stdout')
@with_patched_input(p)
def test_prompt_with_default():
s = 'This is my prompt'
d = 'default!'
prompt(s, default=d)
eq_(sys.stdout.getvalue(), ('%s [%s] ' % (s, d)))
| [
"@",
"mock_streams",
"(",
"'stdout'",
")",
"@",
"with_patched_input",
"(",
"p",
")",
"def",
"test_prompt_with_default",
"(",
")",
":",
"s",
"=",
"'This is my prompt'",
"d",
"=",
"'default!'",
"prompt",
"(",
"s",
",",
"default",
"=",
"d",
")",
"eq_",
"(",
... | prompt() appends given default value plus one space on either side . | train | false |
26,637 | def is_archive(path):
if zipfile.is_zipfile(path):
try:
zf = zipfile.ZipFile(path)
return (0, zf, '.zip')
except:
return ((-1), None, '')
elif rarfile.is_rarfile(path):
try:
zf = rarfile.RarFile(path)
rarfile.UNRAR_TOOL = sabnzbd.newsunpack.RAR_COMMAND
return (0, zf, '.rar')
except:
return ((-1), None, '')
elif is_sevenfile(path):
try:
zf = SevenZip(path)
return (0, zf, '.7z')
except:
return ((-1), None, '')
else:
return (1, None, '')
| [
"def",
"is_archive",
"(",
"path",
")",
":",
"if",
"zipfile",
".",
"is_zipfile",
"(",
"path",
")",
":",
"try",
":",
"zf",
"=",
"zipfile",
".",
"ZipFile",
"(",
"path",
")",
"return",
"(",
"0",
",",
"zf",
",",
"'.zip'",
")",
"except",
":",
"return",
... | check if file in path is an zip . | train | false |
26,638 | def addPathToPixelTable(path, pixelDictionary, value, width):
for pointIndex in xrange((len(path) - 1)):
pointBegin = path[pointIndex]
pointEnd = path[(pointIndex + 1)]
addValueSegmentToPixelTable(pointBegin, pointEnd, pixelDictionary, value, width)
| [
"def",
"addPathToPixelTable",
"(",
"path",
",",
"pixelDictionary",
",",
"value",
",",
"width",
")",
":",
"for",
"pointIndex",
"in",
"xrange",
"(",
"(",
"len",
"(",
"path",
")",
"-",
"1",
")",
")",
":",
"pointBegin",
"=",
"path",
"[",
"pointIndex",
"]",... | add path to the pixel table . | train | false |
26,639 | def retry_if(predicate):
def should_retry(exc_type, value, traceback):
if predicate(value):
return None
raise exc_type, value, traceback
return should_retry
| [
"def",
"retry_if",
"(",
"predicate",
")",
":",
"def",
"should_retry",
"(",
"exc_type",
",",
"value",
",",
"traceback",
")",
":",
"if",
"predicate",
"(",
"value",
")",
":",
"return",
"None",
"raise",
"exc_type",
",",
"value",
",",
"traceback",
"return",
"... | create a predicate compatible with with_retry which will retry if the raised exception satisfies the given predicate . | train | false |
26,641 | def blockquote_text(text):
return '\n'.join((('> ' + line) for line in text.splitlines()))
| [
"def",
"blockquote_text",
"(",
"text",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"(",
"(",
"'> '",
"+",
"line",
")",
"for",
"line",
"in",
"text",
".",
"splitlines",
"(",
")",
")",
")"
] | wrap a chunk of markdown text into a blockquote . | train | false |
26,642 | def _get_image_info(hypervisor, name, **kwargs):
ret = {}
if (hypervisor in ['esxi', 'vmware']):
ret['disktype'] = 'vmdk'
ret['filename'] = '{0}{1}'.format(name, '.vmdk')
ret['pool'] = '[{0}] '.format(kwargs.get('pool', '0'))
elif (hypervisor in ['kvm', 'qemu']):
ret['disktype'] = 'qcow2'
ret['filename'] = '{0}{1}'.format(name, '.qcow2')
ret['pool'] = __salt__['config.option']('virt.images')
return ret
| [
"def",
"_get_image_info",
"(",
"hypervisor",
",",
"name",
",",
"**",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"(",
"hypervisor",
"in",
"[",
"'esxi'",
",",
"'vmware'",
"]",
")",
":",
"ret",
"[",
"'disktype'",
"]",
"=",
"'vmdk'",
"ret",
"[",
"... | determine disk image info . | train | false |
26,643 | def _find_closing_brace(string, start_pos):
bracks_open = 1
escaped = False
for (idx, char) in enumerate(string[start_pos:]):
if (char == '('):
if (not escaped):
bracks_open += 1
elif (char == ')'):
if (not escaped):
bracks_open -= 1
if (not bracks_open):
return ((start_pos + idx) + 1)
if (char == '\\'):
escaped = (not escaped)
else:
escaped = False
| [
"def",
"_find_closing_brace",
"(",
"string",
",",
"start_pos",
")",
":",
"bracks_open",
"=",
"1",
"escaped",
"=",
"False",
"for",
"(",
"idx",
",",
"char",
")",
"in",
"enumerate",
"(",
"string",
"[",
"start_pos",
":",
"]",
")",
":",
"if",
"(",
"char",
... | finds the corresponding closing brace after start_pos . | train | false |
26,644 | def clean_host(host, default_port=None):
host = host.strip()
if host:
match_host_port = re.search('(?:http.*://)?(?P<host>[^:/]+).?(?P<port>[0-9]*).*', host)
cleaned_host = match_host_port.group('host')
cleaned_port = match_host_port.group('port')
if cleaned_host:
if cleaned_port:
host = ((cleaned_host + ':') + cleaned_port)
elif default_port:
host = ((cleaned_host + ':') + str(default_port))
else:
host = cleaned_host
else:
host = ''
return host
| [
"def",
"clean_host",
"(",
"host",
",",
"default_port",
"=",
"None",
")",
":",
"host",
"=",
"host",
".",
"strip",
"(",
")",
"if",
"host",
":",
"match_host_port",
"=",
"re",
".",
"search",
"(",
"'(?:http.*://)?(?P<host>[^:/]+).?(?P<port>[0-9]*).*'",
",",
"host",... | returns host or host:port or empty string from a given url or host if no port is found and default_port is given use host:default_port . | train | false |
26,645 | def _url_quote(string, encoding):
if encoding:
if isinstance(string, unicode):
s = string.encode(encoding)
elif isinstance(string, str):
s = string
else:
s = unicode(string).encode(encoding)
else:
s = str(string)
return urllib.quote(s, '/')
| [
"def",
"_url_quote",
"(",
"string",
",",
"encoding",
")",
":",
"if",
"encoding",
":",
"if",
"isinstance",
"(",
"string",
",",
"unicode",
")",
":",
"s",
"=",
"string",
".",
"encode",
"(",
"encoding",
")",
"elif",
"isinstance",
"(",
"string",
",",
"str",... | a unicode handling version of urllib . | train | false |
26,646 | def test_lex_comment_382():
entry = tokenize('foo ;bar\n;baz')
assert (entry == [HySymbol('foo')])
| [
"def",
"test_lex_comment_382",
"(",
")",
":",
"entry",
"=",
"tokenize",
"(",
"'foo ;bar\\n;baz'",
")",
"assert",
"(",
"entry",
"==",
"[",
"HySymbol",
"(",
"'foo'",
")",
"]",
")"
] | ensure that we can tokenize sources with a comment at the end . | train | false |
26,647 | def CreateFileVersions(token):
CreateFileVersion('aff4:/C.0000000000000001/fs/os/c/Downloads/a.txt', 'Hello World', timestamp=TIME_1, token=token)
CreateFileVersion('aff4:/C.0000000000000001/fs/os/c/Downloads/a.txt', 'Goodbye World', timestamp=TIME_2, token=token)
| [
"def",
"CreateFileVersions",
"(",
"token",
")",
":",
"CreateFileVersion",
"(",
"'aff4:/C.0000000000000001/fs/os/c/Downloads/a.txt'",
",",
"'Hello World'",
",",
"timestamp",
"=",
"TIME_1",
",",
"token",
"=",
"token",
")",
"CreateFileVersion",
"(",
"'aff4:/C.000000000000000... | add new versions for a file . | train | false |
26,648 | def relative_uri(base, to):
if to.startswith(SEP):
return to
b2 = base.split(SEP)
t2 = to.split(SEP)
for (x, y) in zip(b2[:(-1)], t2[:(-1)]):
if (x != y):
break
b2.pop(0)
t2.pop(0)
if (b2 == t2):
return ''
if ((len(b2) == 1) and (t2 == [''])):
return ('.' + SEP)
return ((('..' + SEP) * (len(b2) - 1)) + SEP.join(t2))
| [
"def",
"relative_uri",
"(",
"base",
",",
"to",
")",
":",
"if",
"to",
".",
"startswith",
"(",
"SEP",
")",
":",
"return",
"to",
"b2",
"=",
"base",
".",
"split",
"(",
"SEP",
")",
"t2",
"=",
"to",
".",
"split",
"(",
"SEP",
")",
"for",
"(",
"x",
"... | return a relative url from base to to . | train | false |
26,650 | def fill_template(template_text, context=None, **kwargs):
if (template_text is None):
raise TypeError('Template text specified as None to fill_template.')
if (not context):
context = kwargs
return str(Template(source=template_text, searchList=[context]))
| [
"def",
"fill_template",
"(",
"template_text",
",",
"context",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"template_text",
"is",
"None",
")",
":",
"raise",
"TypeError",
"(",
"'Template text specified as None to fill_template.'",
")",
"if",
"(",
"not",... | fill a cheetah template out for specified context . | train | false |
26,653 | def _FindCommandInPath(command):
if (('/' in command) or ('\\' in command)):
return command
else:
paths = os.environ.get('PATH', '').split(os.pathsep)
for path in paths:
item = os.path.join(path, command)
if (os.path.isfile(item) and os.access(item, os.X_OK)):
return item
return command
| [
"def",
"_FindCommandInPath",
"(",
"command",
")",
":",
"if",
"(",
"(",
"'/'",
"in",
"command",
")",
"or",
"(",
"'\\\\'",
"in",
"command",
")",
")",
":",
"return",
"command",
"else",
":",
"paths",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PATH'",
... | if there are no slashes in the command given . | train | false |
26,654 | def json_validator(value, context):
if isinstance(value, (list, dict)):
return value
try:
value = json.loads(value)
except ValueError:
raise df.Invalid('Cannot parse JSON')
return value
| [
"def",
"json_validator",
"(",
"value",
",",
"context",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"dict",
")",
")",
":",
"return",
"value",
"try",
":",
"value",
"=",
"json",
".",
"loads",
"(",
"value",
")",
"except",
"ValueErr... | validate and parse a json value . | train | false |
26,656 | def to_pascalcase(string):
string = re.sub('(\\s)', (lambda match: '_'), string)
string = re.sub('^(_*)(.)', (lambda match: (match.group(1) + match.group(2).upper())), string)
return re.sub('(?<=[^_])_+([^_])', (lambda match: match.group(1).upper()), string)
| [
"def",
"to_pascalcase",
"(",
"string",
")",
":",
"string",
"=",
"re",
".",
"sub",
"(",
"'(\\\\s)'",
",",
"(",
"lambda",
"match",
":",
"'_'",
")",
",",
"string",
")",
"string",
"=",
"re",
".",
"sub",
"(",
"'^(_*)(.)'",
",",
"(",
"lambda",
"match",
"... | converts the given to string pascal-case . | train | false |
26,657 | def _display_unit(unit):
name = getattr(unit, 'display_name', None)
if name:
return u'{0} ({1})'.format(name, unit.location.to_deprecated_string())
else:
return unit.location.to_deprecated_string()
| [
"def",
"_display_unit",
"(",
"unit",
")",
":",
"name",
"=",
"getattr",
"(",
"unit",
",",
"'display_name'",
",",
"None",
")",
"if",
"name",
":",
"return",
"u'{0} ({1})'",
".",
"format",
"(",
"name",
",",
"unit",
".",
"location",
".",
"to_deprecated_string",... | gets string for displaying unit to user . | train | false |
26,659 | def NamesOfDeclaredExtraKeyFlags():
names_of_extra_key_flags = list(module_bar.NamesOfDefinedFlags())
for flag_name in NamesOfDeclaredKeyFlags():
while (flag_name in names_of_extra_key_flags):
names_of_extra_key_flags.remove(flag_name)
return names_of_extra_key_flags
| [
"def",
"NamesOfDeclaredExtraKeyFlags",
"(",
")",
":",
"names_of_extra_key_flags",
"=",
"list",
"(",
"module_bar",
".",
"NamesOfDefinedFlags",
"(",
")",
")",
"for",
"flag_name",
"in",
"NamesOfDeclaredKeyFlags",
"(",
")",
":",
"while",
"(",
"flag_name",
"in",
"names... | returns the list of names of additional key flags for this module . | train | false |
26,660 | def parse_etags(value):
if (not value):
return ETags()
strong = []
weak = []
end = len(value)
pos = 0
while (pos < end):
match = _etag_re.match(value, pos)
if (match is None):
break
(is_weak, quoted, raw) = match.groups()
if (raw == '*'):
return ETags(star_tag=True)
elif quoted:
raw = quoted
if is_weak:
weak.append(raw)
else:
strong.append(raw)
pos = match.end()
return ETags(strong, weak)
| [
"def",
"parse_etags",
"(",
"value",
")",
":",
"if",
"(",
"not",
"value",
")",
":",
"return",
"ETags",
"(",
")",
"strong",
"=",
"[",
"]",
"weak",
"=",
"[",
"]",
"end",
"=",
"len",
"(",
"value",
")",
"pos",
"=",
"0",
"while",
"(",
"pos",
"<",
"... | parses a string with one or several etags passed in if-none-match and if-match headers by the rules in rfc 2616 . | train | true |
26,661 | def _reset_drivers():
global _drivers
_drivers = None
| [
"def",
"_reset_drivers",
"(",
")",
":",
"global",
"_drivers",
"_drivers",
"=",
"None"
] | used by unit tests to reset the drivers . | train | false |
26,663 | def unpack_glist(glist_ptr, cffi_type, transfer_full=True):
current = glist_ptr
while current:
(yield ffi.cast(cffi_type, current.data))
if transfer_full:
free(current.data)
current = current.next
if transfer_full:
lib.g_list_free(glist_ptr)
| [
"def",
"unpack_glist",
"(",
"glist_ptr",
",",
"cffi_type",
",",
"transfer_full",
"=",
"True",
")",
":",
"current",
"=",
"glist_ptr",
"while",
"current",
":",
"(",
"yield",
"ffi",
".",
"cast",
"(",
"cffi_type",
",",
"current",
".",
"data",
")",
")",
"if",... | takes a glist . | train | true |
26,664 | def _collapse_address_list_recursive(addresses):
ret_array = []
optimized = False
for cur_addr in addresses:
if (not ret_array):
ret_array.append(cur_addr)
continue
if (cur_addr in ret_array[(-1)]):
optimized = True
elif (cur_addr == ret_array[(-1)].supernet().subnet()[1]):
ret_array.append(ret_array.pop().supernet())
optimized = True
else:
ret_array.append(cur_addr)
if optimized:
return _collapse_address_list_recursive(ret_array)
return ret_array
| [
"def",
"_collapse_address_list_recursive",
"(",
"addresses",
")",
":",
"ret_array",
"=",
"[",
"]",
"optimized",
"=",
"False",
"for",
"cur_addr",
"in",
"addresses",
":",
"if",
"(",
"not",
"ret_array",
")",
":",
"ret_array",
".",
"append",
"(",
"cur_addr",
")"... | loops through the addresses . | train | true |
26,665 | def violinplot(vals, fillcolor='#1f77b4', rugplot=True):
vals = np.asarray(vals, np.float)
vals_min = calc_stats(vals)['min']
vals_max = calc_stats(vals)['max']
q1 = calc_stats(vals)['q1']
q2 = calc_stats(vals)['q2']
q3 = calc_stats(vals)['q3']
d1 = calc_stats(vals)['d1']
d2 = calc_stats(vals)['d2']
pdf = scipy_stats.gaussian_kde(vals)
xx = np.linspace(vals_min, vals_max, 100)
yy = pdf(xx)
max_pdf = np.max(yy)
distance = (((2.0 * max_pdf) / 10) if rugplot else 0)
plot_xrange = [(((- max_pdf) - distance) - 0.1), (max_pdf + 0.1)]
plot_data = [make_half_violin((- yy), xx, fillcolor=fillcolor), make_half_violin(yy, xx, fillcolor=fillcolor), make_non_outlier_interval(d1, d2), make_quartiles(q1, q3), make_median(q2)]
if rugplot:
plot_data.append(make_violin_rugplot(vals, max_pdf, distance=distance, color=fillcolor))
return (plot_data, plot_xrange)
| [
"def",
"violinplot",
"(",
"vals",
",",
"fillcolor",
"=",
"'#1f77b4'",
",",
"rugplot",
"=",
"True",
")",
":",
"vals",
"=",
"np",
".",
"asarray",
"(",
"vals",
",",
"np",
".",
"float",
")",
"vals_min",
"=",
"calc_stats",
"(",
"vals",
")",
"[",
"'min'",
... | make a violin plot of each dataset in the data sequence . | train | false |
26,666 | def _is_full_redirect(redirect_url):
redirect_views = getattr(settings, 'HARDTREE_AJAX_RELOAD_ON_REDIRECT', ['user_login'])
for view in redirect_views:
url = ''
try:
url = reverse(view)
except NoReverseMatch:
pass
if (url and (url == redirect_url)):
return True
return False
| [
"def",
"_is_full_redirect",
"(",
"redirect_url",
")",
":",
"redirect_views",
"=",
"getattr",
"(",
"settings",
",",
"'HARDTREE_AJAX_RELOAD_ON_REDIRECT'",
",",
"[",
"'user_login'",
"]",
")",
"for",
"view",
"in",
"redirect_views",
":",
"url",
"=",
"''",
"try",
":",... | returns true if this page requires full reload with ajax enabled . | train | false |
26,667 | @nose.tools.nottest
def pooling_patches(dims, ksize, stride, pad, cover_all):
if cover_all:
xss = itertools.product(*[six.moves.range((- p), (((d + p) - k) + s), s) for (d, k, s, p) in six.moves.zip(dims, ksize, stride, pad)])
else:
xss = itertools.product(*[six.moves.range((- p), (((d + p) - k) + 1), s) for (d, k, s, p) in six.moves.zip(dims, ksize, stride, pad)])
return [tuple((slice(max(x, 0), min((x + k), d)) for (x, d, k) in six.moves.zip(xs, dims, ksize))) for xs in xss]
| [
"@",
"nose",
".",
"tools",
".",
"nottest",
"def",
"pooling_patches",
"(",
"dims",
",",
"ksize",
",",
"stride",
",",
"pad",
",",
"cover_all",
")",
":",
"if",
"cover_all",
":",
"xss",
"=",
"itertools",
".",
"product",
"(",
"*",
"[",
"six",
".",
"moves"... | return tuples of slices that indicate pooling patches . | train | false |
26,668 | def getTruncatedRotatedBoundaryLayers(repository, rotatedBoundaryLayers):
return rotatedBoundaryLayers[repository.layersFrom.value:repository.layersTo.value]
| [
"def",
"getTruncatedRotatedBoundaryLayers",
"(",
"repository",
",",
"rotatedBoundaryLayers",
")",
":",
"return",
"rotatedBoundaryLayers",
"[",
"repository",
".",
"layersFrom",
".",
"value",
":",
"repository",
".",
"layersTo",
".",
"value",
"]"
] | get the truncated rotated boundary layers . | train | false |
26,669 | def can_mount():
if (os.getuid() != 0):
logging.debug('Can not use mount: current user is not "root"')
return False
if (not has_userland_tool('mount')):
logging.debug('Can not use mount: missing "mount" tool')
return False
utils.system('modprobe iso9660', 10, True)
if ('iso9660' not in open('/proc/filesystems').read()):
logging.debug('Can not use mount: lack of iso9660 kernel support')
return False
return True
| [
"def",
"can_mount",
"(",
")",
":",
"if",
"(",
"os",
".",
"getuid",
"(",
")",
"!=",
"0",
")",
":",
"logging",
".",
"debug",
"(",
"'Can not use mount: current user is not \"root\"'",
")",
"return",
"False",
"if",
"(",
"not",
"has_userland_tool",
"(",
"'mount'"... | test wether the current user can perform a loop mount afaik . | train | false |
26,670 | def update_layers(service):
if (service.method == 'C'):
_register_cascaded_layers(service)
elif (service.type in ['WMS', 'OWS']):
_register_indexed_layers(service)
elif (service.type == 'REST'):
_register_arcgis_layers(service)
elif (service.type == 'CSW'):
_harvest_csw(service)
elif (service.type == 'OGP'):
_harvest_ogp_layers(service, 25)
| [
"def",
"update_layers",
"(",
"service",
")",
":",
"if",
"(",
"service",
".",
"method",
"==",
"'C'",
")",
":",
"_register_cascaded_layers",
"(",
"service",
")",
"elif",
"(",
"service",
".",
"type",
"in",
"[",
"'WMS'",
",",
"'OWS'",
"]",
")",
":",
"_regi... | import/update layers for an existing service . | train | false |
26,671 | def _ImportSymbols(protobuf, symbols, prefix='SOCKET_'):
for sym in symbols:
globals()[sym] = getattr(protobuf, (prefix + sym))
| [
"def",
"_ImportSymbols",
"(",
"protobuf",
",",
"symbols",
",",
"prefix",
"=",
"'SOCKET_'",
")",
":",
"for",
"sym",
"in",
"symbols",
":",
"globals",
"(",
")",
"[",
"sym",
"]",
"=",
"getattr",
"(",
"protobuf",
",",
"(",
"prefix",
"+",
"sym",
")",
")"
] | import symbols defined in a protobuf into the global namespace . | train | false |
26,672 | def inverse_laplace_transform(F, s, t, plane=None, **hints):
if (isinstance(F, MatrixBase) and hasattr(F, 'applyfunc')):
return F.applyfunc((lambda Fij: inverse_laplace_transform(Fij, s, t, plane, **hints)))
return InverseLaplaceTransform(F, s, t, plane).doit(**hints)
| [
"def",
"inverse_laplace_transform",
"(",
"F",
",",
"s",
",",
"t",
",",
"plane",
"=",
"None",
",",
"**",
"hints",
")",
":",
"if",
"(",
"isinstance",
"(",
"F",
",",
"MatrixBase",
")",
"and",
"hasattr",
"(",
"F",
",",
"'applyfunc'",
")",
")",
":",
"re... | compute the inverse laplace transform of f(s) . | train | false |
26,674 | def optionally(preprocessor):
@wraps(preprocessor)
def wrapper(func, argname, arg):
return (arg if (arg is None) else preprocessor(func, argname, arg))
return wrapper
| [
"def",
"optionally",
"(",
"preprocessor",
")",
":",
"@",
"wraps",
"(",
"preprocessor",
")",
"def",
"wrapper",
"(",
"func",
",",
"argname",
",",
"arg",
")",
":",
"return",
"(",
"arg",
"if",
"(",
"arg",
"is",
"None",
")",
"else",
"preprocessor",
"(",
"... | modify a preprocessor to explicitly allow none . | train | true |
26,676 | def registerAdapter(adapterFactory, origInterface, *interfaceClasses):
self = globalRegistry
assert interfaceClasses, 'You need to pass an Interface'
global ALLOW_DUPLICATES
if (not isinstance(origInterface, interface.InterfaceClass)):
origInterface = declarations.implementedBy(origInterface)
for interfaceClass in interfaceClasses:
factory = self.registered([origInterface], interfaceClass)
if ((factory is not None) and (not ALLOW_DUPLICATES)):
raise ValueError(('an adapter (%s) was already registered.' % (factory,)))
for interfaceClass in interfaceClasses:
self.register([origInterface], interfaceClass, '', adapterFactory)
| [
"def",
"registerAdapter",
"(",
"adapterFactory",
",",
"origInterface",
",",
"*",
"interfaceClasses",
")",
":",
"self",
"=",
"globalRegistry",
"assert",
"interfaceClasses",
",",
"'You need to pass an Interface'",
"global",
"ALLOW_DUPLICATES",
"if",
"(",
"not",
"isinstanc... | register an adapter class . | train | false |
26,677 | def insert(tup, loc, val):
L = list(tup)
L[loc] = val
return tuple(L)
| [
"def",
"insert",
"(",
"tup",
",",
"loc",
",",
"val",
")",
":",
"L",
"=",
"list",
"(",
"tup",
")",
"L",
"[",
"loc",
"]",
"=",
"val",
"return",
"tuple",
"(",
"L",
")"
] | add an item or items to a queue . | train | false |
26,678 | def print_inplace(msg):
term_width = get_terminal_size().columns
spacing = (term_width - terminal_len(msg))
if is_win32:
spacing -= 1
sys.stderr.write('\r{0}'.format(msg))
sys.stderr.write((' ' * max(0, spacing)))
sys.stderr.flush()
| [
"def",
"print_inplace",
"(",
"msg",
")",
":",
"term_width",
"=",
"get_terminal_size",
"(",
")",
".",
"columns",
"spacing",
"=",
"(",
"term_width",
"-",
"terminal_len",
"(",
"msg",
")",
")",
"if",
"is_win32",
":",
"spacing",
"-=",
"1",
"sys",
".",
"stderr... | clears out the previous line and prints a new one . | train | true |
26,679 | def split_url(url):
(scheme, remainder) = splittype(url)
(host, path) = splithost(remainder)
return (scheme.lower(), host, path)
| [
"def",
"split_url",
"(",
"url",
")",
":",
"(",
"scheme",
",",
"remainder",
")",
"=",
"splittype",
"(",
"url",
")",
"(",
"host",
",",
"path",
")",
"=",
"splithost",
"(",
"remainder",
")",
"return",
"(",
"scheme",
".",
"lower",
"(",
")",
",",
"host",... | splits a url into . | train | false |
26,680 | def create_or_edit(sheet):
if (not exists(sheet)):
create(sheet)
elif (exists(sheet) and (not exists_in_default_path(sheet))):
copy(path(sheet), os.path.join(sheets.default_path(), sheet))
edit(sheet)
else:
edit(sheet)
| [
"def",
"create_or_edit",
"(",
"sheet",
")",
":",
"if",
"(",
"not",
"exists",
"(",
"sheet",
")",
")",
":",
"create",
"(",
"sheet",
")",
"elif",
"(",
"exists",
"(",
"sheet",
")",
"and",
"(",
"not",
"exists_in_default_path",
"(",
"sheet",
")",
")",
")",... | creates or edits a cheatsheet . | train | false |
26,681 | def get_package_list(name_startswith):
(dpkg_exit_code, _, _) = run_command(cmd='dpkg', shell=True)
(rpm_exit_code, _, _) = run_command(cmd='rpm', shell=True)
if (dpkg_exit_code != 127):
result = get_deb_package_list(name_startswith=name_startswith)
elif (rpm_exit_code != 127):
result = get_rpm_package_list(name_startswith=name_startswith)
else:
raise Exception('Unsupported platform (dpkg or rpm binary not available)')
return result
| [
"def",
"get_package_list",
"(",
"name_startswith",
")",
":",
"(",
"dpkg_exit_code",
",",
"_",
",",
"_",
")",
"=",
"run_command",
"(",
"cmd",
"=",
"'dpkg'",
",",
"shell",
"=",
"True",
")",
"(",
"rpm_exit_code",
",",
"_",
",",
"_",
")",
"=",
"run_command... | retrieve system packages which name matches the provided startswith filter . | train | false |
26,682 | def validate_ohlc(open, high, low, close, direction, **kwargs):
for lst in [open, low, close]:
for index in range(len(high)):
if (high[index] < lst[index]):
raise exceptions.PlotlyError('Oops! Looks like some of your high values are less the corresponding open, low, or close values. Double check that your data is entered in O-H-L-C order')
for lst in [open, high, close]:
for index in range(len(low)):
if (low[index] > lst[index]):
raise exceptions.PlotlyError('Oops! Looks like some of your low values are greater than the corresponding high, open, or close values. Double check that your data is entered in O-H-L-C order')
direction_opts = ('increasing', 'decreasing', 'both')
if (direction not in direction_opts):
raise exceptions.PlotlyError("direction must be defined as 'increasing', 'decreasing', or 'both'")
| [
"def",
"validate_ohlc",
"(",
"open",
",",
"high",
",",
"low",
",",
"close",
",",
"direction",
",",
"**",
"kwargs",
")",
":",
"for",
"lst",
"in",
"[",
"open",
",",
"low",
",",
"close",
"]",
":",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"hig... | ohlc and candlestick specific validations specifically . | train | false |
26,683 | def test_rus_fit_invalid_ratio():
ratio = (1.0 / 10000.0)
rus = RandomUnderSampler(ratio=ratio, random_state=RND_SEED)
assert_raises(RuntimeError, rus.fit, X, Y)
| [
"def",
"test_rus_fit_invalid_ratio",
"(",
")",
":",
"ratio",
"=",
"(",
"1.0",
"/",
"10000.0",
")",
"rus",
"=",
"RandomUnderSampler",
"(",
"ratio",
"=",
"ratio",
",",
"random_state",
"=",
"RND_SEED",
")",
"assert_raises",
"(",
"RuntimeError",
",",
"rus",
".",... | test either if an error is raised when the balancing ratio to fit is smaller than the one of the data . | train | false |
26,684 | def Cov(xs, ys, meanx=None, meany=None):
xs = np.asarray(xs)
ys = np.asarray(ys)
if (meanx is None):
meanx = np.mean(xs)
if (meany is None):
meany = np.mean(ys)
cov = (np.dot((xs - meanx), (ys - meany)) / len(xs))
return cov
| [
"def",
"Cov",
"(",
"xs",
",",
"ys",
",",
"meanx",
"=",
"None",
",",
"meany",
"=",
"None",
")",
":",
"xs",
"=",
"np",
".",
"asarray",
"(",
"xs",
")",
"ys",
"=",
"np",
".",
"asarray",
"(",
"ys",
")",
"if",
"(",
"meanx",
"is",
"None",
")",
":"... | computes cov . | train | false |
26,685 | def test_install_from_broken_wheel(script, data):
from tests.lib import TestFailure
package = data.packages.join('brokenwheel-1.0-py2.py3-none-any.whl')
result = script.pip('install', package, '--no-index', expect_error=True)
with pytest.raises(TestFailure):
result.assert_installed('futurewheel', without_egg_link=True, editable=False)
| [
"def",
"test_install_from_broken_wheel",
"(",
"script",
",",
"data",
")",
":",
"from",
"tests",
".",
"lib",
"import",
"TestFailure",
"package",
"=",
"data",
".",
"packages",
".",
"join",
"(",
"'brokenwheel-1.0-py2.py3-none-any.whl'",
")",
"result",
"=",
"script",
... | test that installing a broken wheel fails properly . | train | false |
26,686 | def pentity():
s3.prep = (lambda r: (r.method == 'search_ac'))
return s3_rest_controller()
| [
"def",
"pentity",
"(",
")",
":",
"s3",
".",
"prep",
"=",
"(",
"lambda",
"r",
":",
"(",
"r",
".",
"method",
"==",
"'search_ac'",
")",
")",
"return",
"s3_rest_controller",
"(",
")"
] | restful crud controller - limited to just search_ac for use in autocompletes . | train | false |
26,687 | def check_splitter(command):
try:
env = os.environ.copy()
if ('xld' in command):
env['PATH'] += (os.pathsep + '/Applications')
elif headphones.CONFIG.CUE_SPLIT_FLAC_PATH:
command = os.path.join(headphones.CONFIG.CUE_SPLIT_SHNTOOL_PATH, 'shntool')
devnull = open(os.devnull)
subprocess.Popen([command], stdout=devnull, stderr=devnull, env=env).communicate()
except OSError as e:
if (e.errno == os.errno.ENOENT):
return False
return True
| [
"def",
"check_splitter",
"(",
"command",
")",
":",
"try",
":",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"if",
"(",
"'xld'",
"in",
"command",
")",
":",
"env",
"[",
"'PATH'",
"]",
"+=",
"(",
"os",
".",
"pathsep",
"+",
"'/Applications'... | check xld or shntool installed . | train | false |
26,688 | def _gather_buffer_space():
if HAS_PSUTIL:
total_mem = psutil.virtual_memory().total
else:
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total']
return max([(total_mem * 0.05), (10 << 20)])
| [
"def",
"_gather_buffer_space",
"(",
")",
":",
"if",
"HAS_PSUTIL",
":",
"total_mem",
"=",
"psutil",
".",
"virtual_memory",
"(",
")",
".",
"total",
"else",
":",
"os_data",
"=",
"{",
"'kernel'",
":",
"platform",
".",
"system",
"(",
")",
"}",
"grains",
"=",
... | gather some system data and then calculate buffer space . | train | true |
26,690 | def __signal_handler(signal, frame):
end()
| [
"def",
"__signal_handler",
"(",
"signal",
",",
"frame",
")",
":",
"end",
"(",
")"
] | callback for ctrl-c . | train | false |
26,691 | def getNewRepository():
return ExportRepository()
| [
"def",
"getNewRepository",
"(",
")",
":",
"return",
"ExportRepository",
"(",
")"
] | get the repository constructor . | train | false |
26,692 | def rotate(clip, angle, unit='deg', resample='bicubic', expand=True):
resample = {'bilinear': Image.BILINEAR, 'nearest': Image.NEAREST, 'bicubic': Image.BICUBIC}[resample]
if (not hasattr(angle, '__call__')):
a = (+ angle)
angle = (lambda t: a)
transpo = ([1, 0] if clip.ismask else [1, 0, 2])
def fl(gf, t):
a = angle(t)
im = gf(t)
if (unit == 'rad'):
a = ((360.0 * a) / (2 * np.pi))
if ((a == 90) and expand):
return np.transpose(im, axes=transpo)[::(-1)]
elif ((a == (-90)) and expand):
return np.transpose(im, axes=transpo)[:, ::(-1)]
elif ((a in [180, (-180)]) and expand):
return im[::(-1), ::(-1)]
elif (not PIL_FOUND):
raise ValueError('Without "Pillow" installed, only angles 90, -90,180 are supported, please install "Pillow" withpip install pillow')
else:
return pil_rotater(im, a, resample=resample, expand=expand)
return clip.fl(fl, apply_to=['mask'])
| [
"def",
"rotate",
"(",
"clip",
",",
"angle",
",",
"unit",
"=",
"'deg'",
",",
"resample",
"=",
"'bicubic'",
",",
"expand",
"=",
"True",
")",
":",
"resample",
"=",
"{",
"'bilinear'",
":",
"Image",
".",
"BILINEAR",
",",
"'nearest'",
":",
"Image",
".",
"N... | return the matrix to rotate a 2-d point about the origin by angle . | train | false |
26,693 | def route(obj):
classname = obj.__class__.__name__
log.info('Checking %s for webhooks', classname)
for (name, func) in getmembers(obj, ismethod):
if getattr(func, '_err_webhook_uri_rule', False):
log.info('Webhook routing %s', func.__name__)
for verb in func._err_webhook_methods:
wv = WebView(func, func._err_webhook_form_param, func._err_webhook_raw)
bottle_app.route(func._err_webhook_uri_rule, verb, callback=wv, name=((func.__name__ + '_') + verb))
| [
"def",
"route",
"(",
"obj",
")",
":",
"classname",
"=",
"obj",
".",
"__class__",
".",
"__name__",
"log",
".",
"info",
"(",
"'Checking %s for webhooks'",
",",
"classname",
")",
"for",
"(",
"name",
",",
"func",
")",
"in",
"getmembers",
"(",
"obj",
",",
"... | decorator marking the decorated method as being a handler for requests . | train | false |
26,694 | def radar_plot():
labels = np.array(['A', 'B', 'C', 'D', 'E', 'F'])
data = np.array([38, 43, 90, 67, 89, 73])
theta = np.linspace(0, (2 * np.pi), len(data), endpoint=False)
data = np.concatenate((data, [data[0]]))
theta = np.concatenate((theta, [theta[0]]))
plt.subplot(111, polar=True)
plt.thetagrids((theta * (180 / np.pi)), labels=labels)
plt.rgrids(np.arange(20, 101, 20), labels=np.arange(20, 101, 20), angle=0)
plt.ylim(0, 100)
plt.plot(theta, data, 'bo-', linewidth=2)
plt.fill(theta, data, color='red', alpha=0.25)
plt.show()
return
| [
"def",
"radar_plot",
"(",
")",
":",
"labels",
"=",
"np",
".",
"array",
"(",
"[",
"'A'",
",",
"'B'",
",",
"'C'",
",",
"'D'",
",",
"'E'",
",",
"'F'",
"]",
")",
"data",
"=",
"np",
".",
"array",
"(",
"[",
"38",
",",
"43",
",",
"90",
",",
"67",
... | radar plot . | train | false |
26,695 | @login_required
@ensure_csrf_cookie
@require_GET
def course_search_index_handler(request, course_key_string):
if (not GlobalStaff().has_user(request.user)):
raise PermissionDenied()
course_key = CourseKey.from_string(course_key_string)
content_type = request.META.get('CONTENT_TYPE', None)
if (content_type is None):
content_type = 'application/json; charset=utf-8'
with modulestore().bulk_operations(course_key):
try:
reindex_course_and_check_access(course_key, request.user)
except SearchIndexingError as search_err:
return HttpResponse(dump_js_escaped_json({'user_message': search_err.error_list}), content_type=content_type, status=500)
return HttpResponse(dump_js_escaped_json({'user_message': _('Course has been successfully reindexed.')}), content_type=content_type, status=200)
| [
"@",
"login_required",
"@",
"ensure_csrf_cookie",
"@",
"require_GET",
"def",
"course_search_index_handler",
"(",
"request",
",",
"course_key_string",
")",
":",
"if",
"(",
"not",
"GlobalStaff",
"(",
")",
".",
"has_user",
"(",
"request",
".",
"user",
")",
")",
"... | the restful handler for course indexing . | train | false |
26,696 | def end_request(request_id):
with _request_states_lock:
request_state = _request_states[request_id]
request_state.end_request()
with _request_states_lock:
del _request_states[request_id]
| [
"def",
"end_request",
"(",
"request_id",
")",
":",
"with",
"_request_states_lock",
":",
"request_state",
"=",
"_request_states",
"[",
"request_id",
"]",
"request_state",
".",
"end_request",
"(",
")",
"with",
"_request_states_lock",
":",
"del",
"_request_states",
"["... | ends the request with the provided request id . | train | false |
26,697 | def deconstruct(s, variables=()):
if (s in variables):
return Variable(s)
if isinstance(s, (Variable, CondVariable)):
return s
if ((not isinstance(s, Basic)) or s.is_Atom):
return s
return Compound(s.__class__, tuple((deconstruct(arg, variables) for arg in s.args)))
| [
"def",
"deconstruct",
"(",
"s",
",",
"variables",
"=",
"(",
")",
")",
":",
"if",
"(",
"s",
"in",
"variables",
")",
":",
"return",
"Variable",
"(",
"s",
")",
"if",
"isinstance",
"(",
"s",
",",
"(",
"Variable",
",",
"CondVariable",
")",
")",
":",
"... | turn a sympy object into a compound . | train | false |
26,698 | def mock_engine(dialect_name=None):
from sqlalchemy import create_engine
if (not dialect_name):
dialect_name = config.db.name
buffer = []
def executor(sql, *a, **kw):
buffer.append(sql)
def assert_sql(stmts):
recv = [re.sub('[\\n\\t]', '', str(s)) for s in buffer]
assert (recv == stmts), recv
def print_sql():
d = engine.dialect
return '\n'.join((str(s.compile(dialect=d)) for s in engine.mock))
engine = create_engine((dialect_name + '://'), strategy='mock', executor=executor)
assert (not hasattr(engine, 'mock'))
engine.mock = buffer
engine.assert_sql = assert_sql
engine.print_sql = print_sql
return engine
| [
"def",
"mock_engine",
"(",
"dialect_name",
"=",
"None",
")",
":",
"from",
"sqlalchemy",
"import",
"create_engine",
"if",
"(",
"not",
"dialect_name",
")",
":",
"dialect_name",
"=",
"config",
".",
"db",
".",
"name",
"buffer",
"=",
"[",
"]",
"def",
"executor"... | provides a mocking engine based on the current testing . | train | false |
26,699 | @task
def update_sumo(ctx, tag):
pre_update(tag)
update()
| [
"@",
"task",
"def",
"update_sumo",
"(",
"ctx",
",",
"tag",
")",
":",
"pre_update",
"(",
"tag",
")",
"update",
"(",
")"
] | do typical sumo update . | train | false |
26,700 | def _retry_on_unavailable(exc):
from grpc import StatusCode
return (exc.code() == StatusCode.UNAVAILABLE)
| [
"def",
"_retry_on_unavailable",
"(",
"exc",
")",
":",
"from",
"grpc",
"import",
"StatusCode",
"return",
"(",
"exc",
".",
"code",
"(",
")",
"==",
"StatusCode",
".",
"UNAVAILABLE",
")"
] | retry only errors whose status code is unavailable . | train | false |
26,701 | def diop_linear(eq, param=symbols('t', integer=True)):
from sympy.core.function import count_ops
(var, coeff, diop_type) = classify_diop(eq, _dict=False)
if (diop_type == 'linear'):
return _diop_linear(var, coeff, param)
| [
"def",
"diop_linear",
"(",
"eq",
",",
"param",
"=",
"symbols",
"(",
"'t'",
",",
"integer",
"=",
"True",
")",
")",
":",
"from",
"sympy",
".",
"core",
".",
"function",
"import",
"count_ops",
"(",
"var",
",",
"coeff",
",",
"diop_type",
")",
"=",
"classi... | solves linear diophantine equations . | train | false |
26,702 | def clock():
return load('clock_motion.png')
| [
"def",
"clock",
"(",
")",
":",
"return",
"load",
"(",
"'clock_motion.png'",
")"
] | get current logical clock value . | train | false |
26,703 | def resource_class_url(environ, resource_class):
prefix = environ.get('SCRIPT_NAME', '')
return ('%s/resource_classes/%s' % (prefix, resource_class.name))
| [
"def",
"resource_class_url",
"(",
"environ",
",",
"resource_class",
")",
":",
"prefix",
"=",
"environ",
".",
"get",
"(",
"'SCRIPT_NAME'",
",",
"''",
")",
"return",
"(",
"'%s/resource_classes/%s'",
"%",
"(",
"prefix",
",",
"resource_class",
".",
"name",
")",
... | produce the url for a resource class . | train | false |
26,704 | def test_write_no_multicols():
col1 = [1, 2, 3]
col2 = [(1.0, 1.0), (2.0, 2.0), (3.0, 3.0)]
col3 = [('a', 'a', 'a'), ('b', 'b', 'b'), ('c', 'c', 'c')]
table = Table([col1, col2, col3], names=('C1', 'C2', 'C3'))
expected = '<html>\n <head>\n <meta charset="utf-8"/>\n <meta content="text/html;charset=UTF-8" http-equiv="Content-type"/>\n </head>\n <body>\n <table>\n <thead>\n <tr>\n <th>C1</th>\n <th>C2</th>\n <th>C3</th>\n </tr>\n </thead>\n <tr>\n <td>1</td>\n <td>1.0 .. 1.0</td>\n <td>a .. a</td>\n </tr>\n <tr>\n <td>2</td>\n <td>2.0 .. 2.0</td>\n <td>b .. b</td>\n </tr>\n <tr>\n <td>3</td>\n <td>3.0 .. 3.0</td>\n <td>c .. c</td>\n </tr>\n </table>\n </body>\n</html>\n '
assert (html.HTML({'multicol': False}).write(table)[0].strip() == expected.strip())
| [
"def",
"test_write_no_multicols",
"(",
")",
":",
"col1",
"=",
"[",
"1",
",",
"2",
",",
"3",
"]",
"col2",
"=",
"[",
"(",
"1.0",
",",
"1.0",
")",
",",
"(",
"2.0",
",",
"2.0",
")",
",",
"(",
"3.0",
",",
"3.0",
")",
"]",
"col3",
"=",
"[",
"(",
... | test to make sure that the html writer will not use multi-dimensional columns if the multicol parameter is false . | train | false |
26,705 | def _query_pageant(msg):
hwnd = _get_pageant_window_object()
if (not hwnd):
return None
map_name = ('PageantRequest%08x' % thread.get_ident())
pymap = _winapi.MemoryMap(map_name, _AGENT_MAX_MSGLEN, _winapi.get_security_attributes_for_user())
with pymap:
pymap.write(msg)
char_buffer = array.array('b', (b(map_name) + zero_byte))
(char_buffer_address, char_buffer_size) = char_buffer.buffer_info()
cds = COPYDATASTRUCT(_AGENT_COPYDATA_ID, char_buffer_size, char_buffer_address)
response = ctypes.windll.user32.SendMessageA(hwnd, win32con_WM_COPYDATA, ctypes.sizeof(cds), ctypes.byref(cds))
if (response > 0):
pymap.seek(0)
datalen = pymap.read(4)
retlen = struct.unpack('>I', datalen)[0]
return (datalen + pymap.read(retlen))
return None
| [
"def",
"_query_pageant",
"(",
"msg",
")",
":",
"hwnd",
"=",
"_get_pageant_window_object",
"(",
")",
"if",
"(",
"not",
"hwnd",
")",
":",
"return",
"None",
"map_name",
"=",
"(",
"'PageantRequest%08x'",
"%",
"thread",
".",
"get_ident",
"(",
")",
")",
"pymap",... | communication with the pageant process is done through a shared memory-mapped file . | train | true |
26,708 | def isNum(x):
return (isfloat(x) or isint(x))
| [
"def",
"isNum",
"(",
"x",
")",
":",
"return",
"(",
"isfloat",
"(",
"x",
")",
"or",
"isint",
"(",
"x",
")",
")"
] | check if string argument is numerical . | train | false |
26,709 | @not_implemented_for('undirected')
def is_strongly_connected(G):
if (len(G) == 0):
raise nx.NetworkXPointlessConcept('Connectivity is undefined for the null graph.')
return (len(list(strongly_connected_components(G))[0]) == len(G))
| [
"@",
"not_implemented_for",
"(",
"'undirected'",
")",
"def",
"is_strongly_connected",
"(",
"G",
")",
":",
"if",
"(",
"len",
"(",
"G",
")",
"==",
"0",
")",
":",
"raise",
"nx",
".",
"NetworkXPointlessConcept",
"(",
"'Connectivity is undefined for the null graph.'",
... | test directed graph for strong connectivity . | train | false |
26,711 | @public
def is_zero_dimensional(F, *gens, **args):
return GroebnerBasis(F, *gens, **args).is_zero_dimensional
| [
"@",
"public",
"def",
"is_zero_dimensional",
"(",
"F",
",",
"*",
"gens",
",",
"**",
"args",
")",
":",
"return",
"GroebnerBasis",
"(",
"F",
",",
"*",
"gens",
",",
"**",
"args",
")",
".",
"is_zero_dimensional"
] | checks if the ideal generated by a groebner basis is zero-dimensional . | train | false |
26,712 | def _check_precision_positivity(precision, covariance_type):
if np.any(np.less_equal(precision, 0.0)):
raise ValueError(("'%s precision' should be positive" % covariance_type))
| [
"def",
"_check_precision_positivity",
"(",
"precision",
",",
"covariance_type",
")",
":",
"if",
"np",
".",
"any",
"(",
"np",
".",
"less_equal",
"(",
"precision",
",",
"0.0",
")",
")",
":",
"raise",
"ValueError",
"(",
"(",
"\"'%s precision' should be positive\"",... | check a precision vector is positive-definite . | train | false |
26,714 | def expand_numeric_pattern(string):
(lead, pattern, remnant) = re.split(NUMERIC_EXPANSION_PATTERN, string, maxsplit=1)
(x, y) = pattern.split('-')
for i in range(int(x), (int(y) + 1)):
if re.search(NUMERIC_EXPANSION_PATTERN, remnant):
for string in expand_numeric_pattern(remnant):
(yield '{}{}{}'.format(lead, i, string))
else:
(yield '{}{}{}'.format(lead, i, remnant))
| [
"def",
"expand_numeric_pattern",
"(",
"string",
")",
":",
"(",
"lead",
",",
"pattern",
",",
"remnant",
")",
"=",
"re",
".",
"split",
"(",
"NUMERIC_EXPANSION_PATTERN",
",",
"string",
",",
"maxsplit",
"=",
"1",
")",
"(",
"x",
",",
"y",
")",
"=",
"pattern... | expand a numeric pattern into a list of strings . | train | false |
26,716 | def lookupMailboxInfo(name, timeout=None):
return getResolver().lookupMailboxInfo(name, timeout)
| [
"def",
"lookupMailboxInfo",
"(",
"name",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"getResolver",
"(",
")",
".",
"lookupMailboxInfo",
"(",
"name",
",",
"timeout",
")"
] | perform an minfo record lookup . | train | false |
26,717 | def absolute_urls(html):
from bs4 import BeautifulSoup
from mezzanine.core.request import current_request
request = current_request()
if (request is not None):
dom = BeautifulSoup(html, u'html.parser')
for (tag, attr) in ABSOLUTE_URL_TAGS.items():
for node in dom.findAll(tag):
url = node.get(attr, u'')
if url:
node[attr] = request.build_absolute_uri(url)
html = str(dom)
return html
| [
"def",
"absolute_urls",
"(",
"html",
")",
":",
"from",
"bs4",
"import",
"BeautifulSoup",
"from",
"mezzanine",
".",
"core",
".",
"request",
"import",
"current_request",
"request",
"=",
"current_request",
"(",
")",
"if",
"(",
"request",
"is",
"not",
"None",
")... | converts relative urls into absolute urls . | train | true |
26,718 | def strip_none(data, omit_none=False):
if (data is None):
data = '~'
elif isinstance(data, list):
data2 = []
for x in data:
if (omit_none and (x is None)):
pass
else:
data2.append(strip_none(x))
return data2
elif isinstance(data, dict):
data2 = {}
for key in data.keys():
if (omit_none and (data[key] is None)):
pass
else:
data2[str(key)] = strip_none(data[key])
return data2
return data
| [
"def",
"strip_none",
"(",
"data",
",",
"omit_none",
"=",
"False",
")",
":",
"if",
"(",
"data",
"is",
"None",
")",
":",
"data",
"=",
"'~'",
"elif",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"data2",
"=",
"[",
"]",
"for",
"x",
"in",
"data",... | returns a dictionary stripped of any keys having values of none . | train | false |
26,720 | @printing_func
def write_name_file(name):
return Classpath(creator=u'write_name_file')
| [
"@",
"printing_func",
"def",
"write_name_file",
"(",
"name",
")",
":",
"return",
"Classpath",
"(",
"creator",
"=",
"u'write_name_file'",
")"
] | write a file containing the name of this target in the cwd . | train | false |
26,722 | def service_get_minimum_version(context, binary):
return IMPL.service_get_minimum_version(context, binary)
| [
"def",
"service_get_minimum_version",
"(",
"context",
",",
"binary",
")",
":",
"return",
"IMPL",
".",
"service_get_minimum_version",
"(",
"context",
",",
"binary",
")"
] | get the minimum service version in the database . | train | false |
26,724 | def chars_surround(chars, match):
return (chars_before(chars, match) and chars_after(chars, match))
| [
"def",
"chars_surround",
"(",
"chars",
",",
"match",
")",
":",
"return",
"(",
"chars_before",
"(",
"chars",
",",
"match",
")",
"and",
"chars_after",
"(",
"chars",
",",
"match",
")",
")"
] | validate the match if surrounding characters are in a given sequence . | train | false |
26,725 | def conditionally_add_query_item(query, item, condition):
condition = condition.lower()
if (condition == 'yes'):
return (query & Q(item, 'eq', True))
elif (condition == 'no'):
return (query & Q(item, 'eq', False))
elif (condition == 'either'):
return query
raise HTTPError(http.BAD_REQUEST)
| [
"def",
"conditionally_add_query_item",
"(",
"query",
",",
"item",
",",
"condition",
")",
":",
"condition",
"=",
"condition",
".",
"lower",
"(",
")",
"if",
"(",
"condition",
"==",
"'yes'",
")",
":",
"return",
"(",
"query",
"&",
"Q",
"(",
"item",
",",
"'... | helper for the search_projects_by_title function which will add a condition to a query it will give an error if the proper search term is not used . | train | false |
26,727 | @apply_to_text_file
def cssminify(data):
try:
url = 'http://cssminifier.com/raw'
_data = {'input': data}
response = requests.post(url, data=_data)
if (response.status_code != 200):
LOGGER.error("can't use cssminifier.com: HTTP status {}", response.status_code)
return data
return response.text
except Exception as exc:
LOGGER.error("can't use cssminifier.com: {}", exc)
return data
| [
"@",
"apply_to_text_file",
"def",
"cssminify",
"(",
"data",
")",
":",
"try",
":",
"url",
"=",
"'http://cssminifier.com/raw'",
"_data",
"=",
"{",
"'input'",
":",
"data",
"}",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"data",
"=",
"_data",
... | minify css using URL . | train | false |
26,729 | def all_migrations(applications=None):
if (applications is None):
applications = models.get_apps()
for model_module in applications:
app_path = '.'.join(model_module.__name__.split('.')[:(-1)])
app = ask_for_it_by_name(app_path)
try:
(yield Migrations(app))
except exceptions.NoMigrations:
pass
| [
"def",
"all_migrations",
"(",
"applications",
"=",
"None",
")",
":",
"if",
"(",
"applications",
"is",
"None",
")",
":",
"applications",
"=",
"models",
".",
"get_apps",
"(",
")",
"for",
"model_module",
"in",
"applications",
":",
"app_path",
"=",
"'.'",
".",... | returns all migrations for all applications that are migrated . | train | false |
26,731 | def _comparator(func):
def comparator_wrapper(self, other):
try:
assert (self.enumtype == other.enumtype)
result = func(self.index, other.index)
except (AssertionError, AttributeError):
result = NotImplemented
return result
comparator_wrapper.__name__ = func.__name__
comparator_wrapper.__doc__ = getattr(float, func.__name__).__doc__
return comparator_wrapper
| [
"def",
"_comparator",
"(",
"func",
")",
":",
"def",
"comparator_wrapper",
"(",
"self",
",",
"other",
")",
":",
"try",
":",
"assert",
"(",
"self",
".",
"enumtype",
"==",
"other",
".",
"enumtype",
")",
"result",
"=",
"func",
"(",
"self",
".",
"index",
... | decorator for enumvalue rich comparison methods . | train | true |
26,732 | def SILENT(x):
LOG_LEVEL('error')
| [
"def",
"SILENT",
"(",
"x",
")",
":",
"LOG_LEVEL",
"(",
"'error'",
")"
] | sets the logging verbosity to error which silences most output . | train | false |
26,733 | def online_variance(data):
n = 0
mean = 0
M2 = 0
for x in data:
n = (n + 1)
delta = (x - mean)
mean = (mean + (delta / n))
M2 = (M2 + (delta * (x - mean)))
variance_n = (M2 / n)
variance = (M2 / (n - 1))
return (variance, variance_n)
| [
"def",
"online_variance",
"(",
"data",
")",
":",
"n",
"=",
"0",
"mean",
"=",
"0",
"M2",
"=",
"0",
"for",
"x",
"in",
"data",
":",
"n",
"=",
"(",
"n",
"+",
"1",
")",
"delta",
"=",
"(",
"x",
"-",
"mean",
")",
"mean",
"=",
"(",
"mean",
"+",
"... | a numerically stable algorithm for calculating variance URL#on-line_algorithm . | train | false |
26,734 | def attach_import_node(node, modname, membername):
from_node = From(modname, [(membername, None)])
_attach_local_node(node, from_node, membername)
| [
"def",
"attach_import_node",
"(",
"node",
",",
"modname",
",",
"membername",
")",
":",
"from_node",
"=",
"From",
"(",
"modname",
",",
"[",
"(",
"membername",
",",
"None",
")",
"]",
")",
"_attach_local_node",
"(",
"node",
",",
"from_node",
",",
"membername"... | create a from node and register it in the locals of the given node with the specified name . | train | false |
26,736 | def get_object_or_None(klass, *args, **kwargs):
queryset = _get_queryset(klass)
try:
return queryset.get(*args, **kwargs)
except queryset.model.DoesNotExist:
return None
| [
"def",
"get_object_or_None",
"(",
"klass",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"queryset",
"=",
"_get_queryset",
"(",
"klass",
")",
"try",
":",
"return",
"queryset",
".",
"get",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"except",
"querys... | uses get() to return an object or none if the object does not exist . | train | true |
26,738 | def process_media(processPath, videoFiles, nzbName, process_method, force, is_priority, result):
processor = None
for cur_video_file in videoFiles:
cur_video_file_path = os.path.join(processPath, cur_video_file)
if already_postprocessed(processPath, cur_video_file, force, result):
result.output += logHelper(((u'Already Processed ' + cur_video_file_path) + u' : Skipping'), sickrage.srCore.srLogger.DEBUG)
continue
try:
processor = post_processor.PostProcessor(cur_video_file_path, nzbName, process_method, is_priority)
result.result = processor.process
process_fail_message = u''
except EpisodePostProcessingFailedException as e:
result.result = False
process_fail_message = e.message
if processor:
result.output += processor.log
if result.result:
result.output += logHelper((u'Processing succeeded for ' + cur_video_file_path))
else:
result.output += logHelper((((u'Processing failed for ' + cur_video_file_path) + u': ') + process_fail_message), sickrage.srCore.srLogger.WARNING)
result.missedfiles.append(((cur_video_file_path + u' : Processing failed: ') + process_fail_message))
result.aggresult = False
| [
"def",
"process_media",
"(",
"processPath",
",",
"videoFiles",
",",
"nzbName",
",",
"process_method",
",",
"force",
",",
"is_priority",
",",
"result",
")",
":",
"processor",
"=",
"None",
"for",
"cur_video_file",
"in",
"videoFiles",
":",
"cur_video_file_path",
"=... | postprocess mediafiles . | train | false |
26,739 | def GetTypeUrl(proto):
return (TYPE_URL_PREFIX + proto.DESCRIPTOR.full_name)
| [
"def",
"GetTypeUrl",
"(",
"proto",
")",
":",
"return",
"(",
"TYPE_URL_PREFIX",
"+",
"proto",
".",
"DESCRIPTOR",
".",
"full_name",
")"
] | returns type url for a given proto . | train | false |
26,741 | def aicc(llf, nobs, df_modelwc):
return (((-2.0) * llf) + (((2.0 * df_modelwc) * nobs) / ((nobs - df_modelwc) - 1.0)))
| [
"def",
"aicc",
"(",
"llf",
",",
"nobs",
",",
"df_modelwc",
")",
":",
"return",
"(",
"(",
"(",
"-",
"2.0",
")",
"*",
"llf",
")",
"+",
"(",
"(",
"(",
"2.0",
"*",
"df_modelwc",
")",
"*",
"nobs",
")",
"/",
"(",
"(",
"nobs",
"-",
"df_modelwc",
")"... | akaike information criterion with small sample correction parameters llf : float value of the loglikelihood nobs : int number of observations df_modelwc : int number of parameters including constant returns aicc : float information criterion references URL#aicc . | train | false |
26,743 | def test_custom_derived_cols_from_df(test_data):
ds = ChartDataSource.from_data(test_data.pd_data, dims=('x', 'y'), column_assigner=NumericalColumnsAssigner)
assert (ds['y'] == ['col1', 'col2'])
| [
"def",
"test_custom_derived_cols_from_df",
"(",
"test_data",
")",
":",
"ds",
"=",
"ChartDataSource",
".",
"from_data",
"(",
"test_data",
".",
"pd_data",
",",
"dims",
"=",
"(",
"'x'",
",",
"'y'",
")",
",",
"column_assigner",
"=",
"NumericalColumnsAssigner",
")",
... | wide dataframe columns assigned to y dimension for the chart . | train | false |
26,744 | @login_required
@ensure_csrf_cookie
@require_http_methods(('GET', 'POST'))
def library_handler(request, library_key_string=None):
if (not LIBRARIES_ENABLED):
log.exception('Attempted to use the content library API when the libraries feature is disabled.')
raise Http404
if ((library_key_string is not None) and (request.method == 'POST')):
return HttpResponseNotAllowed(('POST',))
if (request.method == 'POST'):
return _create_library(request)
if library_key_string:
return _display_library(library_key_string, request)
return _list_libraries(request)
| [
"@",
"login_required",
"@",
"ensure_csrf_cookie",
"@",
"require_http_methods",
"(",
"(",
"'GET'",
",",
"'POST'",
")",
")",
"def",
"library_handler",
"(",
"request",
",",
"library_key_string",
"=",
"None",
")",
":",
"if",
"(",
"not",
"LIBRARIES_ENABLED",
")",
"... | restful interface to most content library related functionality . | train | false |
26,745 | def _precess_from_J2000_Capitaine(epoch):
T = ((epoch - 2000.0) / 100.0)
pzeta = ((-3.173e-07), (-5.971e-06), 0.01801828, 0.2988499, 2306.083227, 2.650545)
pz = ((-2.904e-07), (-2.8596e-05), 0.01826837, 1.0927348, 2306.077181, (-2.650545))
ptheta = ((-1.274e-07), (-7.089e-06), (-0.04182264), (-0.4294934), 2004.191903, 0)
zeta = (np.polyval(pzeta, T) / 3600.0)
z = (np.polyval(pz, T) / 3600.0)
theta = (np.polyval(ptheta, T) / 3600.0)
return matrix_product(rotation_matrix((- z), u'z'), rotation_matrix(theta, u'y'), rotation_matrix((- zeta), u'z'))
| [
"def",
"_precess_from_J2000_Capitaine",
"(",
"epoch",
")",
":",
"T",
"=",
"(",
"(",
"epoch",
"-",
"2000.0",
")",
"/",
"100.0",
")",
"pzeta",
"=",
"(",
"(",
"-",
"3.173e-07",
")",
",",
"(",
"-",
"5.971e-06",
")",
",",
"0.01801828",
",",
"0.2988499",
"... | computes the precession matrix from j2000 to the given julian epoch . | train | false |
26,746 | def current_revision_link(obj):
if (not obj.current_revision):
return 'None'
rev = obj.current_revision
rev_url = reverse('admin:wiki_revision_change', args=[rev.id])
return ('<a href="%s">Current Revision (#%s)</a>' % (rev_url, rev.id))
| [
"def",
"current_revision_link",
"(",
"obj",
")",
":",
"if",
"(",
"not",
"obj",
".",
"current_revision",
")",
":",
"return",
"'None'",
"rev",
"=",
"obj",
".",
"current_revision",
"rev_url",
"=",
"reverse",
"(",
"'admin:wiki_revision_change'",
",",
"args",
"=",
... | html link to the current revision for the admin change list . | train | false |
26,747 | def BuildRequestData(filepath=None):
current_filepath = vimsupport.GetCurrentBufferFilepath()
if (filepath and (current_filepath != filepath)):
return {u'filepath': filepath, u'line_num': 1, u'column_num': 1, u'file_data': vimsupport.GetUnsavedAndSpecifiedBufferData(filepath)}
(line, column) = vimsupport.CurrentLineAndColumn()
return {u'filepath': current_filepath, u'line_num': (line + 1), u'column_num': (column + 1), u'file_data': vimsupport.GetUnsavedAndSpecifiedBufferData(current_filepath)}
| [
"def",
"BuildRequestData",
"(",
"filepath",
"=",
"None",
")",
":",
"current_filepath",
"=",
"vimsupport",
".",
"GetCurrentBufferFilepath",
"(",
")",
"if",
"(",
"filepath",
"and",
"(",
"current_filepath",
"!=",
"filepath",
")",
")",
":",
"return",
"{",
"u'filep... | build request for the current buffer or the buffer corresponding to |filepath| if specified . | train | false |
26,748 | def EvalPoissonPmf(k, lam):
return (((lam ** k) * math.exp((- lam))) / special.gamma((k + 1)))
| [
"def",
"EvalPoissonPmf",
"(",
"k",
",",
"lam",
")",
":",
"return",
"(",
"(",
"(",
"lam",
"**",
"k",
")",
"*",
"math",
".",
"exp",
"(",
"(",
"-",
"lam",
")",
")",
")",
"/",
"special",
".",
"gamma",
"(",
"(",
"k",
"+",
"1",
")",
")",
")"
] | computes the poisson pmf . | train | false |
26,749 | def _InitDir(output_dir):
try:
os.listdir(output_dir)
except:
os.makedirs(output_dir)
| [
"def",
"_InitDir",
"(",
"output_dir",
")",
":",
"try",
":",
"os",
".",
"listdir",
"(",
"output_dir",
")",
"except",
":",
"os",
".",
"makedirs",
"(",
"output_dir",
")"
] | initializes the output directory for fetching user logs . | train | false |
26,750 | @pytest.mark.network
def test_pip_wheel_success(script, data):
script.pip('install', 'wheel')
result = script.pip('wheel', '--no-index', '-f', data.find_links, 'simple==3.0')
wheel_file_name = ('simple-3.0-py%s-none-any.whl' % pyversion[0])
wheel_file_path = (script.scratch / wheel_file_name)
assert (wheel_file_path in result.files_created), result.stdout
assert ('Successfully built simple' in result.stdout), result.stdout
| [
"@",
"pytest",
".",
"mark",
".",
"network",
"def",
"test_pip_wheel_success",
"(",
"script",
",",
"data",
")",
":",
"script",
".",
"pip",
"(",
"'install'",
",",
"'wheel'",
")",
"result",
"=",
"script",
".",
"pip",
"(",
"'wheel'",
",",
"'--no-index'",
",",... | test pip wheel success . | train | false |
26,751 | def StrKey(key_str):
parts = key_str.split(u'\x00\x00')
for i in xrange(len(parts)):
if (parts[i][0] == ':'):
part = parts[i][1:]
part = zero_one_matcher.sub(u'\x00', part)
parts[i] = part
else:
parts[i] = int(parts[i])
return datastore.Key.from_path(*parts)
| [
"def",
"StrKey",
"(",
"key_str",
")",
":",
"parts",
"=",
"key_str",
".",
"split",
"(",
"u'\\x00\\x00'",
")",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"parts",
")",
")",
":",
"if",
"(",
"parts",
"[",
"i",
"]",
"[",
"0",
"]",
"==",
"':'",
")"... | the inverse of the keystr function . | train | false |
26,752 | def _rangeGen(data, std=1):
dataStd = np.std(data)
if (dataStd == 0):
dataStd = 1
minval = (np.min(data) - (std * dataStd))
maxval = (np.max(data) + (std * dataStd))
return (minval, maxval)
| [
"def",
"_rangeGen",
"(",
"data",
",",
"std",
"=",
"1",
")",
":",
"dataStd",
"=",
"np",
".",
"std",
"(",
"data",
")",
"if",
"(",
"dataStd",
"==",
"0",
")",
":",
"dataStd",
"=",
"1",
"minval",
"=",
"(",
"np",
".",
"min",
"(",
"data",
")",
"-",
... | return reasonable min/max values to use given the data . | train | true |
26,754 | @task
def adminserver(ctx, port=8001, host='127.0.0.1', pty=True):
env = 'DJANGO_SETTINGS_MODULE="admin.base.settings"'
cmd = '{} python manage.py runserver {}:{} --no-init-app --nothreading'.format(env, host, port)
if settings.SECURE_MODE:
cmd = cmd.replace('runserver', 'runsslserver')
cmd += ' --certificate {} --key {}'.format(settings.OSF_SERVER_CERT, settings.OSF_SERVER_KEY)
ctx.run(cmd, echo=True, pty=pty)
| [
"@",
"task",
"def",
"adminserver",
"(",
"ctx",
",",
"port",
"=",
"8001",
",",
"host",
"=",
"'127.0.0.1'",
",",
"pty",
"=",
"True",
")",
":",
"env",
"=",
"'DJANGO_SETTINGS_MODULE=\"admin.base.settings\"'",
"cmd",
"=",
"'{} python manage.py runserver {}:{} --no-init-a... | run the admin server . | train | false |
26,756 | def osx_shutdown():
try:
subprocess.call(['osascript', '-e', 'tell app "System Events" to shut down'])
except:
logging.error(T('Error while shutting down system'))
logging.info('Traceback: ', exc_info=True)
os._exit(0)
| [
"def",
"osx_shutdown",
"(",
")",
":",
"try",
":",
"subprocess",
".",
"call",
"(",
"[",
"'osascript'",
",",
"'-e'",
",",
"'tell app \"System Events\" to shut down'",
"]",
")",
"except",
":",
"logging",
".",
"error",
"(",
"T",
"(",
"'Error while shutting down syst... | shutdown osx system . | train | false |
26,758 | def list_portgroups(service_instance):
return list_objects(service_instance, vim.dvs.DistributedVirtualPortgroup)
| [
"def",
"list_portgroups",
"(",
"service_instance",
")",
":",
"return",
"list_objects",
"(",
"service_instance",
",",
"vim",
".",
"dvs",
".",
"DistributedVirtualPortgroup",
")"
] | returns a list of distributed virtual portgroups associated with a given service instance . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.