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 |
|---|---|---|---|---|---|
32,034 | def parse_sequence(source, info):
sequence = []
applied = False
while True:
(characters, case_flags, element) = parse_literal_and_element(source, info)
if (not element):
append_literal(characters, case_flags, sequence)
break
if ((element is COMMENT) or (element is FLAGS)):
append_literal(characters, c... | [
"def",
"parse_sequence",
"(",
"source",
",",
"info",
")",
":",
"sequence",
"=",
"[",
"]",
"applied",
"=",
"False",
"while",
"True",
":",
"(",
"characters",
",",
"case_flags",
",",
"element",
")",
"=",
"parse_literal_and_element",
"(",
"source",
",",
"info"... | parses a sequence . | train | false |
32,036 | def list_employees(order_by='id'):
ret = {}
(status, result) = _query(action='employees', command='directory')
root = ET.fromstring(result)
directory = root.getchildren()
for cat in directory:
if (cat.tag != 'employees'):
continue
for item in cat:
emp_id = item.items()[0][1]
emp_ret = {'id': emp_id}
... | [
"def",
"list_employees",
"(",
"order_by",
"=",
"'id'",
")",
":",
"ret",
"=",
"{",
"}",
"(",
"status",
",",
"result",
")",
"=",
"_query",
"(",
"action",
"=",
"'employees'",
",",
"command",
"=",
"'directory'",
")",
"root",
"=",
"ET",
".",
"fromstring",
... | show all employees for this company . | train | true |
32,037 | def test_unique():
with pytest.raises(TypeError):
usertypes.enum('Enum', ['item', 'item'])
| [
"def",
"test_unique",
"(",
")",
":",
"with",
"pytest",
".",
"raises",
"(",
"TypeError",
")",
":",
"usertypes",
".",
"enum",
"(",
"'Enum'",
",",
"[",
"'item'",
",",
"'item'",
"]",
")"
] | make sure elements need to be unique . | train | false |
32,038 | def document():
return s3_rest_controller()
| [
"def",
"document",
"(",
")",
":",
"return",
"s3_rest_controller",
"(",
")"
] | return an empty document with enough stuff filled out that it can be saved . | train | false |
32,039 | def DateTimeDelta2literal(d, c):
return string_literal(format_TIMEDELTA(d), c)
| [
"def",
"DateTimeDelta2literal",
"(",
"d",
",",
"c",
")",
":",
"return",
"string_literal",
"(",
"format_TIMEDELTA",
"(",
"d",
")",
",",
"c",
")"
] | format a datetimedelta object as a time . | train | false |
32,040 | @common_exceptions_400
def view_alreadyrunningerror(request):
raise AlreadyRunningError()
| [
"@",
"common_exceptions_400",
"def",
"view_alreadyrunningerror",
"(",
"request",
")",
":",
"raise",
"AlreadyRunningError",
"(",
")"
] | a dummy view that raises an alreadyrunningerror exception . | train | false |
32,041 | def shear_matrix(angle, direction, point, normal):
normal = unit_vector(normal[:3])
direction = unit_vector(direction[:3])
if (abs(numpy.dot(normal, direction)) > 1e-06):
raise ValueError('direction and normal vectors are not orthogonal')
angle = math.tan(angle)
M = numpy.identity(4)
M[:3, :3] += (angle * numpy... | [
"def",
"shear_matrix",
"(",
"angle",
",",
"direction",
",",
"point",
",",
"normal",
")",
":",
"normal",
"=",
"unit_vector",
"(",
"normal",
"[",
":",
"3",
"]",
")",
"direction",
"=",
"unit_vector",
"(",
"direction",
"[",
":",
"3",
"]",
")",
"if",
"(",... | return matrix to shear by angle along direction vector on shear plane . | train | true |
32,042 | @contextmanager
def serving(resources):
(server, port) = server_and_port(resources)
thread = Thread(target=server.serve_forever)
try:
thread.start()
(yield 'https://localhost:{port}/'.format(port=port))
finally:
server.shutdown()
thread.join()
| [
"@",
"contextmanager",
"def",
"serving",
"(",
"resources",
")",
":",
"(",
"server",
",",
"port",
")",
"=",
"server_and_port",
"(",
"resources",
")",
"thread",
"=",
"Thread",
"(",
"target",
"=",
"server",
".",
"serve_forever",
")",
"try",
":",
"thread",
"... | spin up a local https server . | train | false |
32,043 | def can_execute_unsafe_code(course_id):
for regex in getattr(settings, 'COURSES_WITH_UNSAFE_CODE', []):
if re.match(regex, unicode(course_id)):
return True
return False
| [
"def",
"can_execute_unsafe_code",
"(",
"course_id",
")",
":",
"for",
"regex",
"in",
"getattr",
"(",
"settings",
",",
"'COURSES_WITH_UNSAFE_CODE'",
",",
"[",
"]",
")",
":",
"if",
"re",
".",
"match",
"(",
"regex",
",",
"unicode",
"(",
"course_id",
")",
")",
... | determine if this course is allowed to run unsafe code . | train | false |
32,044 | def create_api(name, description, cloneFrom=None, region=None, key=None, keyid=None, profile=None):
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if cloneFrom:
api = conn.create_rest_api(name=name, description=description, cloneFrom=cloneFrom)
else:
api = conn.create_rest_api(... | [
"def",
"create_api",
"(",
"name",
",",
"description",
",",
"cloneFrom",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"... | create a new rest api service with the given name returns {created: true} if the rest api was created and returns {created: false} if the rest api was not created . | train | false |
32,046 | def test_add_contacts(contacts_provider, contact_sync, db, default_namespace):
num_original_contacts = db.session.query(Contact).filter_by(namespace_id=default_namespace.id).count()
contacts_provider.supply_contact('Contact One', 'contact.one@email.address')
contacts_provider.supply_contact('Contact Two', 'contact.t... | [
"def",
"test_add_contacts",
"(",
"contacts_provider",
",",
"contact_sync",
",",
"db",
",",
"default_namespace",
")",
":",
"num_original_contacts",
"=",
"db",
".",
"session",
".",
"query",
"(",
"Contact",
")",
".",
"filter_by",
"(",
"namespace_id",
"=",
"default_... | test that added contacts get stored . | train | false |
32,048 | def keep_lease_alive(lease):
while True:
sleep(5)
try:
lease.HttpNfcLeaseProgress(50)
if (lease.state == vim.HttpNfcLease.State.done):
return
except:
return
| [
"def",
"keep_lease_alive",
"(",
"lease",
")",
":",
"while",
"True",
":",
"sleep",
"(",
"5",
")",
"try",
":",
"lease",
".",
"HttpNfcLeaseProgress",
"(",
"50",
")",
"if",
"(",
"lease",
".",
"state",
"==",
"vim",
".",
"HttpNfcLease",
".",
"State",
".",
... | keeps the lease alive while posting the vmdk . | train | false |
32,049 | def guadd(a, b, c):
(x, y) = c.shape
for i in range(x):
for j in range(y):
c[(i, j)] = (a[(i, j)] + b[(i, j)])
| [
"def",
"guadd",
"(",
"a",
",",
"b",
",",
"c",
")",
":",
"(",
"x",
",",
"y",
")",
"=",
"c",
".",
"shape",
"for",
"i",
"in",
"range",
"(",
"x",
")",
":",
"for",
"j",
"in",
"range",
"(",
"y",
")",
":",
"c",
"[",
"(",
"i",
",",
"j",
")",
... | a generalized addition . | train | false |
32,050 | def saveOTF(font, destFile, glyphOrder, truetype=False):
if truetype:
compiler = compileTTF
else:
compiler = compileOTF
otf = compiler(font, featureCompilerClass=RobotoFeatureCompiler, kernWriter=RobotoKernWriter, glyphOrder=glyphOrder, useProductionNames=False)
otf.save(destFile)
| [
"def",
"saveOTF",
"(",
"font",
",",
"destFile",
",",
"glyphOrder",
",",
"truetype",
"=",
"False",
")",
":",
"if",
"truetype",
":",
"compiler",
"=",
"compileTTF",
"else",
":",
"compiler",
"=",
"compileOTF",
"otf",
"=",
"compiler",
"(",
"font",
",",
"featu... | save a robofab font as an otf binary using ufo2fdk . | train | false |
32,052 | @removals.remove(message='Use keystoneclient.session.request instead.', version='1.7.0', removal_version='2.0.0')
def request(*args, **kwargs):
return client_session.request(*args, **kwargs)
| [
"@",
"removals",
".",
"remove",
"(",
"message",
"=",
"'Use keystoneclient.session.request instead.'",
",",
"version",
"=",
"'1.7.0'",
",",
"removal_version",
"=",
"'2.0.0'",
")",
"def",
"request",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"cli... | constructs and sends a :class:request <request> . | train | false |
32,053 | def _is_pyrsistent(obj):
return isinstance(obj, (PRecord, PClass, PMap, PSet, PVector))
| [
"def",
"_is_pyrsistent",
"(",
"obj",
")",
":",
"return",
"isinstance",
"(",
"obj",
",",
"(",
"PRecord",
",",
"PClass",
",",
"PMap",
",",
"PSet",
",",
"PVector",
")",
")"
] | boolean check if an object is an instance of a pyrsistent object . | train | false |
32,054 | def get_cinder_client(session, region):
endpoint_errors = []
for version in CINDER_API_SUPPORTED_VERSIONS:
client = CinderClient(version=version, session=session, region_name=region)
try:
client.volumes.list(limit=1, detailed=False)
except EndpointNotFound as e:
endpoint_errors.append(e)
continue
els... | [
"def",
"get_cinder_client",
"(",
"session",
",",
"region",
")",
":",
"endpoint_errors",
"=",
"[",
"]",
"for",
"version",
"in",
"CINDER_API_SUPPORTED_VERSIONS",
":",
"client",
"=",
"CinderClient",
"(",
"version",
"=",
"version",
",",
"session",
"=",
"session",
... | create a cinder client from a keystone session . | train | false |
32,055 | @pick_context_manager_writer
def s3_image_create(context, image_uuid):
try:
s3_image_ref = models.S3Image()
s3_image_ref.update({'uuid': image_uuid})
s3_image_ref.save(context.session)
except Exception as e:
raise db_exc.DBError(e)
return s3_image_ref
| [
"@",
"pick_context_manager_writer",
"def",
"s3_image_create",
"(",
"context",
",",
"image_uuid",
")",
":",
"try",
":",
"s3_image_ref",
"=",
"models",
".",
"S3Image",
"(",
")",
"s3_image_ref",
".",
"update",
"(",
"{",
"'uuid'",
":",
"image_uuid",
"}",
")",
"s... | create local s3 image represented by provided uuid . | train | false |
32,056 | def uri_to_pk(uri):
return uri.rstrip('/').split('/')[(-1)]
| [
"def",
"uri_to_pk",
"(",
"uri",
")",
":",
"return",
"uri",
".",
"rstrip",
"(",
"'/'",
")",
".",
"split",
"(",
"'/'",
")",
"[",
"(",
"-",
"1",
")",
"]"
] | convert a resource uri to the primary key of the resource . | train | false |
32,057 | def sync_grains(saltenv='base'):
return salt.utils.extmods.sync(__opts__, 'grains', saltenv=saltenv)[0]
| [
"def",
"sync_grains",
"(",
"saltenv",
"=",
"'base'",
")",
":",
"return",
"salt",
".",
"utils",
".",
"extmods",
".",
"sync",
"(",
"__opts__",
",",
"'grains'",
",",
"saltenv",
"=",
"saltenv",
")",
"[",
"0",
"]"
] | sync grains modules from salt://_grains to the master saltenv : base the fileserver environment from which to sync . | train | false |
32,059 | def encode_b64jose(data):
return b64.b64encode(data).decode('ascii')
| [
"def",
"encode_b64jose",
"(",
"data",
")",
":",
"return",
"b64",
".",
"b64encode",
"(",
"data",
")",
".",
"decode",
"(",
"'ascii'",
")"
] | encode jose base-64 field . | train | false |
32,060 | def ipproto_to_str(t):
if (t in _ipproto_to_str):
return _ipproto_to_str[t]
else:
return ('%02x' % (t,))
| [
"def",
"ipproto_to_str",
"(",
"t",
")",
":",
"if",
"(",
"t",
"in",
"_ipproto_to_str",
")",
":",
"return",
"_ipproto_to_str",
"[",
"t",
"]",
"else",
":",
"return",
"(",
"'%02x'",
"%",
"(",
"t",
",",
")",
")"
] | given a numeric ip protocol number . | train | false |
32,061 | def every(*args, **kwargs):
interval = total_seconds(timedelta(*args, **kwargs))
def decorator(func):
def poll():
func()
threading.Timer(interval, poll).start()
poll()
return func
return decorator
| [
"def",
"every",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"interval",
"=",
"total_seconds",
"(",
"timedelta",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
")",
"def",
"decorator",
"(",
"func",
")",
":",
"def",
"poll",
"(",
")",
":",
"func",
... | method will been called every minutes or seconds . | train | false |
32,062 | def draw_to_notebook(layers, **kwargs):
from IPython.display import Image
layers = (layers.get_all_layers() if hasattr(layers, 'get_all_layers') else layers)
dot = make_pydot_graph(layers, **kwargs)
return Image(dot.create_png())
| [
"def",
"draw_to_notebook",
"(",
"layers",
",",
"**",
"kwargs",
")",
":",
"from",
"IPython",
".",
"display",
"import",
"Image",
"layers",
"=",
"(",
"layers",
".",
"get_all_layers",
"(",
")",
"if",
"hasattr",
"(",
"layers",
",",
"'get_all_layers'",
")",
"els... | draws a network diagram in an ipython notebook . | train | true |
32,063 | def parse_reboot(rule):
parser = argparse.ArgumentParser()
rules = shlex.split(rule)
rules.pop(0)
parser.add_argument('--eject', dest='eject', action='store_true')
args = clean_args(vars(parser.parse_args(rules)))
parser = None
return args
| [
"def",
"parse_reboot",
"(",
"rule",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"rules",
"=",
"shlex",
".",
"split",
"(",
"rule",
")",
"rules",
".",
"pop",
"(",
"0",
")",
"parser",
".",
"add_argument",
"(",
"'--eject'",
",",
... | parse the reboot line . | train | true |
32,064 | def _MatchBrackets(uwline):
bracket_stack = []
for token in uwline.tokens:
if (token.value in pytree_utils.OPENING_BRACKETS):
bracket_stack.append(token)
elif (token.value in pytree_utils.CLOSING_BRACKETS):
bracket_stack[(-1)].matching_bracket = token
token.matching_bracket = bracket_stack[(-1)]
brack... | [
"def",
"_MatchBrackets",
"(",
"uwline",
")",
":",
"bracket_stack",
"=",
"[",
"]",
"for",
"token",
"in",
"uwline",
".",
"tokens",
":",
"if",
"(",
"token",
".",
"value",
"in",
"pytree_utils",
".",
"OPENING_BRACKETS",
")",
":",
"bracket_stack",
".",
"append",... | visit the node and match the brackets . | train | false |
32,065 | def get_system_hz():
ticks = os.sysconf(os.sysconf_names['SC_CLK_TCK'])
if (ticks == (-1)):
return 100
else:
return ticks
| [
"def",
"get_system_hz",
"(",
")",
":",
"ticks",
"=",
"os",
".",
"sysconf",
"(",
"os",
".",
"sysconf_names",
"[",
"'SC_CLK_TCK'",
"]",
")",
"if",
"(",
"ticks",
"==",
"(",
"-",
"1",
")",
")",
":",
"return",
"100",
"else",
":",
"return",
"ticks"
] | return system hz use sc_clk_tck . | train | false |
32,066 | def simple_separated_format(separator):
return TableFormat(None, None, None, None, headerrow=DataRow(u'', separator, u''), datarow=DataRow(u'', separator, u''), padding=0, with_header_hide=None)
| [
"def",
"simple_separated_format",
"(",
"separator",
")",
":",
"return",
"TableFormat",
"(",
"None",
",",
"None",
",",
"None",
",",
"None",
",",
"headerrow",
"=",
"DataRow",
"(",
"u''",
",",
"separator",
",",
"u''",
")",
",",
"datarow",
"=",
"DataRow",
"(... | construct a simple tableformat with columns separated by a separator . | train | true |
32,068 | def _date_to_json(value):
if isinstance(value, datetime.date):
value = value.isoformat()
return value
| [
"def",
"_date_to_json",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"date",
")",
":",
"value",
"=",
"value",
".",
"isoformat",
"(",
")",
"return",
"value"
] | coerce value to an json-compatible representation . | train | true |
32,069 | def get_handler(debug=False, syslog=False, logfile=None, rotation_parameters=None):
if os.environ.get('APYCOT_ROOT'):
handler = logging.StreamHandler(sys.stdout)
if debug:
handler = logging.StreamHandler()
elif (logfile is None):
if syslog:
from logging import handlers
handler = handlers.SysLogHandler()
... | [
"def",
"get_handler",
"(",
"debug",
"=",
"False",
",",
"syslog",
"=",
"False",
",",
"logfile",
"=",
"None",
",",
"rotation_parameters",
"=",
"None",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'APYCOT_ROOT'",
")",
":",
"handler",
"=",
"logg... | get an apropriate handler according to given parameters . | train | false |
32,071 | def make_directory(path):
if (not path.isdir()):
path.makedirs()
return path
| [
"def",
"make_directory",
"(",
"path",
")",
":",
"if",
"(",
"not",
"path",
".",
"isdir",
"(",
")",
")",
":",
"path",
".",
"makedirs",
"(",
")",
"return",
"path"
] | create a directory at path . | train | false |
32,072 | def systemInformationType4(ChannelDescription_presence=0, MobileAllocation_presence=0):
a = L2PseudoLength()
b = TpPd(pd=6)
c = MessageType(mesType=28)
d = LocalAreaId()
e = CellSelectionParameters()
f = RachControlParameters()
packet = (((((a / b) / c) / d) / e) / f)
if (ChannelDescription_presence is 1):
g ... | [
"def",
"systemInformationType4",
"(",
"ChannelDescription_presence",
"=",
"0",
",",
"MobileAllocation_presence",
"=",
"0",
")",
":",
"a",
"=",
"L2PseudoLength",
"(",
")",
"b",
"=",
"TpPd",
"(",
"pd",
"=",
"6",
")",
"c",
"=",
"MessageType",
"(",
"mesType",
... | system information type 4 section 9 . | train | true |
32,076 | def p_additive_expression_3(t):
pass
| [
"def",
"p_additive_expression_3",
"(",
"t",
")",
":",
"pass"
] | additive_expression : additive_expression minus multiplicative_expression . | train | false |
32,077 | def print_latex(expr, **settings):
print(latex(expr, **settings))
| [
"def",
"print_latex",
"(",
"expr",
",",
"**",
"settings",
")",
":",
"print",
"(",
"latex",
"(",
"expr",
",",
"**",
"settings",
")",
")"
] | prints latex representation of the given expression . | train | false |
32,078 | def find_scene_numbering(indexer_id, indexer, season, episode):
if ((indexer_id is None) or (season is None) or (episode is None)):
return (season, episode)
indexer_id = int(indexer_id)
indexer = int(indexer)
dbData = [x[u'doc'] for x in sickrage.srCore.mainDB.db.get_many(u'scene_numbering', indexer_id, with_doc=... | [
"def",
"find_scene_numbering",
"(",
"indexer_id",
",",
"indexer",
",",
"season",
",",
"episode",
")",
":",
"if",
"(",
"(",
"indexer_id",
"is",
"None",
")",
"or",
"(",
"season",
"is",
"None",
")",
"or",
"(",
"episode",
"is",
"None",
")",
")",
":",
"re... | same as get_scene_numbering() . | train | false |
32,079 | def exec_and_timeit(func):
def wrapper(*arg):
t1 = time()
res = func(*arg)
t2 = time()
ms = ((t2 - t1) * 1000.0)
return (res, ms)
return wrapper
| [
"def",
"exec_and_timeit",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"arg",
")",
":",
"t1",
"=",
"time",
"(",
")",
"res",
"=",
"func",
"(",
"*",
"arg",
")",
"t2",
"=",
"time",
"(",
")",
"ms",
"=",
"(",
"(",
"t2",
"-",
"t1",
")",
"*"... | decorator that returns both function results and execution time . | train | false |
32,082 | def getBottomByPath(path):
bottom = 9.876543219876543e+17
for point in path:
bottom = min(bottom, point.z)
return bottom
| [
"def",
"getBottomByPath",
"(",
"path",
")",
":",
"bottom",
"=",
"9.876543219876543e+17",
"for",
"point",
"in",
"path",
":",
"bottom",
"=",
"min",
"(",
"bottom",
",",
"point",
".",
"z",
")",
"return",
"bottom"
] | get the bottom of the path . | train | false |
32,083 | def page_detail(request, slug, page_slug, template_name='groups/pages/page_detail.html'):
group = get_object_or_404(Group, slug=slug)
page = get_object_or_404(GroupPage, group=group, slug=page_slug)
return render(request, template_name, {'group': group, 'page': page})
| [
"def",
"page_detail",
"(",
"request",
",",
"slug",
",",
"page_slug",
",",
"template_name",
"=",
"'groups/pages/page_detail.html'",
")",
":",
"group",
"=",
"get_object_or_404",
"(",
"Group",
",",
"slug",
"=",
"slug",
")",
"page",
"=",
"get_object_or_404",
"(",
... | returns a group page . | train | false |
32,084 | def load_ctx(x):
if (not hasattr(x, 'ctx')):
return
x.ctx = ast.Load()
if isinstance(x, (ast.Tuple, ast.List)):
for e in x.elts:
load_ctx(e)
elif isinstance(x, ast.Starred):
load_ctx(x.value)
| [
"def",
"load_ctx",
"(",
"x",
")",
":",
"if",
"(",
"not",
"hasattr",
"(",
"x",
",",
"'ctx'",
")",
")",
":",
"return",
"x",
".",
"ctx",
"=",
"ast",
".",
"Load",
"(",
")",
"if",
"isinstance",
"(",
"x",
",",
"(",
"ast",
".",
"Tuple",
",",
"ast",
... | recursively sets ctx to ast . | train | false |
32,085 | def lang_add(cursor, lang, trust):
if trust:
query = ('CREATE TRUSTED LANGUAGE "%s"' % lang)
else:
query = ('CREATE LANGUAGE "%s"' % lang)
cursor.execute(query)
return True
| [
"def",
"lang_add",
"(",
"cursor",
",",
"lang",
",",
"trust",
")",
":",
"if",
"trust",
":",
"query",
"=",
"(",
"'CREATE TRUSTED LANGUAGE \"%s\"'",
"%",
"lang",
")",
"else",
":",
"query",
"=",
"(",
"'CREATE LANGUAGE \"%s\"'",
"%",
"lang",
")",
"cursor",
".",... | adds language for db . | train | false |
32,086 | def use_solver(**kwargs):
if ('useUmfpack' in kwargs):
globals()['useUmfpack'] = kwargs['useUmfpack']
| [
"def",
"use_solver",
"(",
"**",
"kwargs",
")",
":",
"if",
"(",
"'useUmfpack'",
"in",
"kwargs",
")",
":",
"globals",
"(",
")",
"[",
"'useUmfpack'",
"]",
"=",
"kwargs",
"[",
"'useUmfpack'",
"]"
] | select default sparse direct solver to be used . | train | false |
32,087 | def gen_keys(key='', key_path_dir=''):
key_basename = ('key-' + uuid4().hex)
if (not key_path_dir):
key_path_dir = os.path.join(KEY_DIR, 'role_key', key_basename)
private_key = os.path.join(key_path_dir, 'id_rsa')
public_key = os.path.join(key_path_dir, 'id_rsa.pub')
mkdir(key_path_dir, mode=755)
if (not key):
... | [
"def",
"gen_keys",
"(",
"key",
"=",
"''",
",",
"key_path_dir",
"=",
"''",
")",
":",
"key_basename",
"=",
"(",
"'key-'",
"+",
"uuid4",
"(",
")",
".",
"hex",
")",
"if",
"(",
"not",
"key_path_dir",
")",
":",
"key_path_dir",
"=",
"os",
".",
"path",
"."... | generate rsa keys of nbits bits . | train | false |
32,088 | def feature_enabled(feature, config):
return utils.grep(('^%s=y' % feature), config)
| [
"def",
"feature_enabled",
"(",
"feature",
",",
"config",
")",
":",
"return",
"utils",
".",
"grep",
"(",
"(",
"'^%s=y'",
"%",
"feature",
")",
",",
"config",
")"
] | verify whether a given kernel option is enabled . | train | false |
32,089 | @contextlib.contextmanager
def check_warnings(*filters, **kwargs):
quiet = kwargs.get('quiet')
if (not filters):
filters = (('', Warning),)
if (quiet is None):
quiet = True
return _filterwarnings(filters, quiet)
| [
"@",
"contextlib",
".",
"contextmanager",
"def",
"check_warnings",
"(",
"*",
"filters",
",",
"**",
"kwargs",
")",
":",
"quiet",
"=",
"kwargs",
".",
"get",
"(",
"'quiet'",
")",
"if",
"(",
"not",
"filters",
")",
":",
"filters",
"=",
"(",
"(",
"''",
","... | context manager to silence warnings . | train | false |
32,090 | def test_vae_automatically_finds_kl_integrator():
encoding_model = MLP(layers=[Linear(layer_name='h', dim=10, irange=0.01)])
decoding_model = MLP(layers=[Linear(layer_name='h', dim=10, irange=0.01)])
prior = DiagonalGaussianPrior()
conditional = BernoulliVector(mlp=decoding_model, name='conditional')
posterior = D... | [
"def",
"test_vae_automatically_finds_kl_integrator",
"(",
")",
":",
"encoding_model",
"=",
"MLP",
"(",
"layers",
"=",
"[",
"Linear",
"(",
"layer_name",
"=",
"'h'",
",",
"dim",
"=",
"10",
",",
"irange",
"=",
"0.01",
")",
"]",
")",
"decoding_model",
"=",
"ML... | vae automatically finds the right klintegrator . | train | false |
32,091 | def mysql_passwd(password, uppercase=True):
retVal = ('*%s' % sha1(sha1(password).digest()).hexdigest())
return (retVal.upper() if uppercase else retVal.lower())
| [
"def",
"mysql_passwd",
"(",
"password",
",",
"uppercase",
"=",
"True",
")",
":",
"retVal",
"=",
"(",
"'*%s'",
"%",
"sha1",
"(",
"sha1",
"(",
"password",
")",
".",
"digest",
"(",
")",
")",
".",
"hexdigest",
"(",
")",
")",
"return",
"(",
"retVal",
".... | reference(s): URL . | train | false |
32,092 | def ntt_convolute(a, b):
assert (len(a) == len(b))
x = ntt(a, 1)
y = ntt(b, 1)
for i in range(len(a)):
y[i] = (y[i] * x[i])
r = ntt(y, (-1))
return r
| [
"def",
"ntt_convolute",
"(",
"a",
",",
"b",
")",
":",
"assert",
"(",
"len",
"(",
"a",
")",
"==",
"len",
"(",
"b",
")",
")",
"x",
"=",
"ntt",
"(",
"a",
",",
"1",
")",
"y",
"=",
"ntt",
"(",
"b",
",",
"1",
")",
"for",
"i",
"in",
"range",
"... | convolute arrays a and b . | train | false |
32,093 | @command('u(?:ser)?pl\\s(.*)')
def user_pls(user):
return pl_search(user, is_user=True)
| [
"@",
"command",
"(",
"'u(?:ser)?pl\\\\s(.*)'",
")",
"def",
"user_pls",
"(",
"user",
")",
":",
"return",
"pl_search",
"(",
"user",
",",
"is_user",
"=",
"True",
")"
] | retrieve user playlists . | train | false |
32,094 | def reapply_cors(request, response):
service = request.current_service
if service:
request.info['cors_checked'] = False
cors.apply_cors_post_request(service, request, response)
response = cors.ensure_origin(service, request, response)
else:
origin = request.headers.get('Origin')
if origin:
settings = re... | [
"def",
"reapply_cors",
"(",
"request",
",",
"response",
")",
":",
"service",
"=",
"request",
".",
"current_service",
"if",
"service",
":",
"request",
".",
"info",
"[",
"'cors_checked'",
"]",
"=",
"False",
"cors",
".",
"apply_cors_post_request",
"(",
"service",... | reapply cors headers to the new response with regards to the request . | train | false |
32,095 | def read_stream_body(stream, callback):
chunks = []
class Delegate(HTTPMessageDelegate, ):
def headers_received(self, start_line, headers):
self.headers = headers
def data_received(self, chunk):
chunks.append(chunk)
def finish(self):
callback((self.headers, ''.join(chunks)))
conn = HTTP1Connection(str... | [
"def",
"read_stream_body",
"(",
"stream",
",",
"callback",
")",
":",
"chunks",
"=",
"[",
"]",
"class",
"Delegate",
"(",
"HTTPMessageDelegate",
",",
")",
":",
"def",
"headers_received",
"(",
"self",
",",
"start_line",
",",
"headers",
")",
":",
"self",
".",
... | reads an http response from stream and runs callback with its headers and body . | train | false |
32,096 | def matvec(x):
return np.zeros(3)
| [
"def",
"matvec",
"(",
"x",
")",
":",
"return",
"np",
".",
"zeros",
"(",
"3",
")"
] | needed for test_pickle as local functions are not pickleable . | train | false |
32,098 | def _ranging_attributes(attributes, param_class):
next_attributes = {param_class.next_in_enumeration(attribute) for attribute in attributes}
in_first = attributes.difference(next_attributes)
in_second = next_attributes.difference(attributes)
if ((len(in_first) == 1) and (len(in_second) == 1)):
for x in attributes... | [
"def",
"_ranging_attributes",
"(",
"attributes",
",",
"param_class",
")",
":",
"next_attributes",
"=",
"{",
"param_class",
".",
"next_in_enumeration",
"(",
"attribute",
")",
"for",
"attribute",
"in",
"attributes",
"}",
"in_first",
"=",
"attributes",
".",
"differen... | checks if there is a continuous range . | train | true |
32,099 | def _create_player(session, playername, password, permissions, typeclass=None):
try:
new_player = create.create_player(playername, None, password, permissions=permissions, typeclass=typeclass)
except Exception as e:
session.msg(('There was an error creating the Player:\n%s\n If this problem persists, contact an a... | [
"def",
"_create_player",
"(",
"session",
",",
"playername",
",",
"password",
",",
"permissions",
",",
"typeclass",
"=",
"None",
")",
":",
"try",
":",
"new_player",
"=",
"create",
".",
"create_player",
"(",
"playername",
",",
"None",
",",
"password",
",",
"... | helper function . | train | false |
32,100 | def file_access_rights(filename, rights, check_above=False):
if os.path.exists(filename):
return os.access(filename, rights)
elif check_above:
return os.access(os.path.dirname(os.path.abspath(filename)), rights)
else:
return False
| [
"def",
"file_access_rights",
"(",
"filename",
",",
"rights",
",",
"check_above",
"=",
"False",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"return",
"os",
".",
"access",
"(",
"filename",
",",
"rights",
")",
"elif",
"che... | determines if a file has given rights . | train | false |
32,102 | def country():
rebulk = Rebulk().defaults(name='country')
rebulk.functional(find_countries, conflict_solver=(lambda match, other: (match if ((other.name != 'language') or (match.value not in [babelfish.Country('US'), babelfish.Country('GB')])) else other)), properties={'country': [None]})
return rebulk
| [
"def",
"country",
"(",
")",
":",
"rebulk",
"=",
"Rebulk",
"(",
")",
".",
"defaults",
"(",
"name",
"=",
"'country'",
")",
"rebulk",
".",
"functional",
"(",
"find_countries",
",",
"conflict_solver",
"=",
"(",
"lambda",
"match",
",",
"other",
":",
"(",
"m... | builder for rebulk object . | train | false |
32,103 | def logm(A, disp=True):
A = _asarray_square(A)
import scipy.linalg._matfuncs_inv_ssq
F = scipy.linalg._matfuncs_inv_ssq._logm(A)
F = _maybe_real(A, F)
errtol = (1000 * eps)
errest = (norm((expm(F) - A), 1) / norm(A, 1))
if disp:
if ((not isfinite(errest)) or (errest >= errtol)):
print('logm result may be in... | [
"def",
"logm",
"(",
"A",
",",
"disp",
"=",
"True",
")",
":",
"A",
"=",
"_asarray_square",
"(",
"A",
")",
"import",
"scipy",
".",
"linalg",
".",
"_matfuncs_inv_ssq",
"F",
"=",
"scipy",
".",
"linalg",
".",
"_matfuncs_inv_ssq",
".",
"_logm",
"(",
"A",
"... | compute matrix logarithm . | train | false |
32,106 | def find_supported(ranked):
langs = dict(settings.LANGUAGE_URL_MAP)
for (lang, _) in ranked:
lang = lang.lower()
if (lang in langs):
return langs[lang]
pre = '-'.join(lang.split('-')[0:(-1)])
if pre:
ranked.append((pre, None))
return False
| [
"def",
"find_supported",
"(",
"ranked",
")",
":",
"langs",
"=",
"dict",
"(",
"settings",
".",
"LANGUAGE_URL_MAP",
")",
"for",
"(",
"lang",
",",
"_",
")",
"in",
"ranked",
":",
"lang",
"=",
"lang",
".",
"lower",
"(",
")",
"if",
"(",
"lang",
"in",
"la... | given a ranked language list . | train | false |
32,107 | def ensure_not_null(obj):
if obj.isNull():
raise QtValueError(obj, null=True)
| [
"def",
"ensure_not_null",
"(",
"obj",
")",
":",
"if",
"obj",
".",
"isNull",
"(",
")",
":",
"raise",
"QtValueError",
"(",
"obj",
",",
"null",
"=",
"True",
")"
] | ensure a qt object with an . | train | false |
32,108 | def get_remote_image_service(context, image_href):
if ('/' not in str(image_href)):
image_service = get_default_image_service()
return (image_service, image_href)
try:
(image_id, glance_netloc, use_ssl) = _parse_image_ref(image_href)
glance_client = GlanceClientWrapper(context=context, netloc=glance_netloc, u... | [
"def",
"get_remote_image_service",
"(",
"context",
",",
"image_href",
")",
":",
"if",
"(",
"'/'",
"not",
"in",
"str",
"(",
"image_href",
")",
")",
":",
"image_service",
"=",
"get_default_image_service",
"(",
")",
"return",
"(",
"image_service",
",",
"image_hre... | create an image_service and parse the id from the given image_href . | train | false |
32,109 | def _purge_jobs(timestamp):
with _get_serv() as cur:
try:
sql = 'delete from `jids` where jid in (select distinct jid from salt_returns where alter_time < %s)'
cur.execute(sql, (timestamp,))
cur.execute('COMMIT')
except MySQLdb.Error as e:
log.error("mysql returner archiver was unable to delete content... | [
"def",
"_purge_jobs",
"(",
"timestamp",
")",
":",
"with",
"_get_serv",
"(",
")",
"as",
"cur",
":",
"try",
":",
"sql",
"=",
"'delete from `jids` where jid in (select distinct jid from salt_returns where alter_time < %s)'",
"cur",
".",
"execute",
"(",
"sql",
",",
"(",
... | purge records from the returner tables . | train | false |
32,111 | def CancelApiCalls():
_apphosting_runtime___python__apiproxy.CancelApiCalls()
| [
"def",
"CancelApiCalls",
"(",
")",
":",
"_apphosting_runtime___python__apiproxy",
".",
"CancelApiCalls",
"(",
")"
] | cancels all outstanding api calls . | train | false |
32,113 | def _find_adapter(registry, ob):
for t in _get_mro(getattr(ob, '__class__', type(ob))):
if (t in registry):
return registry[t]
| [
"def",
"_find_adapter",
"(",
"registry",
",",
"ob",
")",
":",
"for",
"t",
"in",
"_get_mro",
"(",
"getattr",
"(",
"ob",
",",
"'__class__'",
",",
"type",
"(",
"ob",
")",
")",
")",
":",
"if",
"(",
"t",
"in",
"registry",
")",
":",
"return",
"registry",... | return an adapter factory for ob from registry . | train | true |
32,115 | def test_get_words_python():
expected_words = ['Apply', 'Browser', 'Count', 'Garcia', 'Juan', 'Make', 'Manuel', 'N', 'N_', 'Qt', 'QtWebKit', 'R', 'Set', 'Simple', 'This', 'Very', 'VerySimpleWebBrowser', 'Web', 'Z', 'Z_', '__file__', 'a', 'and', 'argwhere', 'array', 'as', 'author', 'birth', 'borders', 'com', 'def', 'fo... | [
"def",
"test_get_words_python",
"(",
")",
":",
"expected_words",
"=",
"[",
"'Apply'",
",",
"'Browser'",
",",
"'Count'",
",",
"'Garcia'",
",",
"'Juan'",
",",
"'Make'",
",",
"'Manuel'",
",",
"'N'",
",",
"'N_'",
",",
"'Qt'",
",",
"'QtWebKit'",
",",
"'R'",
"... | test for get word from html file syntax . | train | false |
32,116 | def changeAllProjectVersions(root, versionTemplate, today=None):
if (not today):
today = date.today().strftime('%Y-%m-%d')
for project in findTwistedProjects(root):
if (project.directory.basename() == 'twisted'):
packageName = 'twisted'
else:
packageName = ('twisted.' + project.directory.basename())
old... | [
"def",
"changeAllProjectVersions",
"(",
"root",
",",
"versionTemplate",
",",
"today",
"=",
"None",
")",
":",
"if",
"(",
"not",
"today",
")",
":",
"today",
"=",
"date",
".",
"today",
"(",
")",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"for",
"project",
"... | change the version of all projects . | train | false |
32,117 | def question():
def prep(r):
record = r.record
if (record and (r.component_name == 'question_l10n')):
ttable = r.component.table
if (r.method != 'update'):
ttable.question.default = record.question
ttable.options.default = record.options
requires = ttable.language.requires
if isinstance(require... | [
"def",
"question",
"(",
")",
":",
"def",
"prep",
"(",
"r",
")",
":",
"record",
"=",
"r",
".",
"record",
"if",
"(",
"record",
"and",
"(",
"r",
".",
"component_name",
"==",
"'question_l10n'",
")",
")",
":",
"ttable",
"=",
"r",
".",
"component",
".",
... | launches a qmessagebox question with the provided title and message . | train | false |
32,118 | def test_with_appcontext():
@click.command()
@with_appcontext
def testcmd():
click.echo(current_app.name)
obj = ScriptInfo(create_app=(lambda info: Flask('testapp')))
runner = CliRunner()
result = runner.invoke(testcmd, obj=obj)
assert (result.exit_code == 0)
assert (result.output == 'testapp\n')
| [
"def",
"test_with_appcontext",
"(",
")",
":",
"@",
"click",
".",
"command",
"(",
")",
"@",
"with_appcontext",
"def",
"testcmd",
"(",
")",
":",
"click",
".",
"echo",
"(",
"current_app",
".",
"name",
")",
"obj",
"=",
"ScriptInfo",
"(",
"create_app",
"=",
... | test of with_appcontext . | train | false |
32,119 | def get_processtree_pids(pid, include_parent=True):
parents = get_all_processes_pids()
all_pids = parents.keys()
pids = set([pid])
while True:
pids_new = pids.copy()
for _pid in all_pids:
if (parents[_pid] in pids):
pids_new.add(_pid)
if (pids_new == pids):
break
pids = pids_new.copy()
if (not in... | [
"def",
"get_processtree_pids",
"(",
"pid",
",",
"include_parent",
"=",
"True",
")",
":",
"parents",
"=",
"get_all_processes_pids",
"(",
")",
"all_pids",
"=",
"parents",
".",
"keys",
"(",
")",
"pids",
"=",
"set",
"(",
"[",
"pid",
"]",
")",
"while",
"True"... | return a list with all the pids of a process tree . | train | false |
32,120 | def validate_scatterplotmatrix(df, index, diag, colormap_type, **kwargs):
if (not pd):
raise ImportError('FigureFactory.scatterplotmatrix requires a pandas DataFrame.')
if (not isinstance(df, pd.core.frame.DataFrame)):
raise exceptions.PlotlyError('Dataframe not inputed. Please use a pandas dataframe to produce a... | [
"def",
"validate_scatterplotmatrix",
"(",
"df",
",",
"index",
",",
"diag",
",",
"colormap_type",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"not",
"pd",
")",
":",
"raise",
"ImportError",
"(",
"'FigureFactory.scatterplotmatrix requires a pandas DataFrame.'",
")",
"i... | validates basic inputs for figurefactory . | train | false |
32,121 | def place_order(creator, **kwargs):
if ('shipping_method' not in kwargs):
kwargs['shipping_method'] = Free()
shipping_charge = kwargs['shipping_method'].calculate(kwargs['basket'])
kwargs['total'] = calculators.OrderTotalCalculator().calculate(basket=kwargs['basket'], shipping_charge=shipping_charge)
kwargs['ship... | [
"def",
"place_order",
"(",
"creator",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"'shipping_method'",
"not",
"in",
"kwargs",
")",
":",
"kwargs",
"[",
"'shipping_method'",
"]",
"=",
"Free",
"(",
")",
"shipping_charge",
"=",
"kwargs",
"[",
"'shipping_method'",
... | helper function to place an order without the boilerplate . | train | false |
32,123 | def to_simple_filter(bool_or_filter):
if (not isinstance(bool_or_filter, (bool, SimpleFilter))):
raise TypeError((u'Expecting a bool or a SimpleFilter instance. Got %r' % bool_or_filter))
return {True: _always, False: _never}.get(bool_or_filter, bool_or_filter)
| [
"def",
"to_simple_filter",
"(",
"bool_or_filter",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"bool_or_filter",
",",
"(",
"bool",
",",
"SimpleFilter",
")",
")",
")",
":",
"raise",
"TypeError",
"(",
"(",
"u'Expecting a bool or a SimpleFilter instance. Got %r'",
... | accept both booleans and clifilters as input and turn it into a simplefilter . | train | true |
32,124 | def forbid_command(command_obj, cc_list=None, config=None):
if (cc_list is None):
cc_list = command_obj.COMMAND_SECURITY
if cc_list:
for cc in cc_list:
forbid = cc((config or command_obj.session.config))
if forbid:
return forbid
return False
| [
"def",
"forbid_command",
"(",
"command_obj",
",",
"cc_list",
"=",
"None",
",",
"config",
"=",
"None",
")",
":",
"if",
"(",
"cc_list",
"is",
"None",
")",
":",
"cc_list",
"=",
"command_obj",
".",
"COMMAND_SECURITY",
"if",
"cc_list",
":",
"for",
"cc",
"in",... | determine whether to block a command or not . | train | false |
32,125 | @oslo_db_api.wrap_db_retry(max_retries=5, retry_on_deadlock=True, retry_on_request=True)
@pick_context_manager_writer
def fixed_ip_associate(context, address, instance_uuid, network_id=None, reserved=False, virtual_interface_id=None):
if (not uuidutils.is_uuid_like(instance_uuid)):
raise exception.InvalidUUID(uuid=i... | [
"@",
"oslo_db_api",
".",
"wrap_db_retry",
"(",
"max_retries",
"=",
"5",
",",
"retry_on_deadlock",
"=",
"True",
",",
"retry_on_request",
"=",
"True",
")",
"@",
"pick_context_manager_writer",
"def",
"fixed_ip_associate",
"(",
"context",
",",
"address",
",",
"instanc... | associate fixed ip to instance . | train | false |
32,126 | def test_composite_unit_get_format_name():
unit1 = u.Unit(u'nrad/s')
unit2 = u.Unit(u'Hz(1/2)')
assert (str(u.CompositeUnit(1, [unit1, unit2], [1, (-1)])) == u'nrad / (Hz(1/2) s)')
| [
"def",
"test_composite_unit_get_format_name",
"(",
")",
":",
"unit1",
"=",
"u",
".",
"Unit",
"(",
"u'nrad/s'",
")",
"unit2",
"=",
"u",
".",
"Unit",
"(",
"u'Hz(1/2)'",
")",
"assert",
"(",
"str",
"(",
"u",
".",
"CompositeUnit",
"(",
"1",
",",
"[",
"unit1... | see #1576 . | train | false |
32,127 | def setRepositoryToLine(lineIndex, lines, shortDictionary):
line = lines[lineIndex]
splitLine = line.split(globalSpreadsheetSeparator)
if (len(splitLine) < 2):
return
fileSettingName = splitLine[0]
for shortDictionaryKey in shortDictionary:
if (fileSettingName[:len(shortDictionaryKey)] == shortDictionaryKey):
... | [
"def",
"setRepositoryToLine",
"(",
"lineIndex",
",",
"lines",
",",
"shortDictionary",
")",
":",
"line",
"=",
"lines",
"[",
"lineIndex",
"]",
"splitLine",
"=",
"line",
".",
"split",
"(",
"globalSpreadsheetSeparator",
")",
"if",
"(",
"len",
"(",
"splitLine",
"... | set setting dictionary to a setting line . | train | false |
32,129 | def is_clique(graph):
return (graph.density == 1.0)
| [
"def",
"is_clique",
"(",
"graph",
")",
":",
"return",
"(",
"graph",
".",
"density",
"==",
"1.0",
")"
] | a clique is a set of nodes in which each node is connected to all other nodes . | train | false |
32,130 | def sort_resources(resources):
for resource in resources:
resource.library.init_library_nr()
def key(resource):
return (resource.order, resource.library.library_nr, resource.library.name, resource.custom_order, resource.dependency_nr, resource.relpath)
return sorted(resources, key=key)
| [
"def",
"sort_resources",
"(",
"resources",
")",
":",
"for",
"resource",
"in",
"resources",
":",
"resource",
".",
"library",
".",
"init_library_nr",
"(",
")",
"def",
"key",
"(",
"resource",
")",
":",
"return",
"(",
"resource",
".",
"order",
",",
"resource",... | sort resources for inclusion on web page . | train | false |
32,134 | def prep_case_insensitive(value):
value = re.sub('\\s+', ' ', value.strip().lower())
return value
| [
"def",
"prep_case_insensitive",
"(",
"value",
")",
":",
"value",
"=",
"re",
".",
"sub",
"(",
"'\\\\s+'",
",",
"' '",
",",
"value",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
")",
"return",
"value"
] | prepare a string for case-insensitive comparison . | train | false |
32,135 | def is_cased(info, char):
return (len(_regex.get_all_cases(info.flags, char)) > 1)
| [
"def",
"is_cased",
"(",
"info",
",",
"char",
")",
":",
"return",
"(",
"len",
"(",
"_regex",
".",
"get_all_cases",
"(",
"info",
".",
"flags",
",",
"char",
")",
")",
">",
"1",
")"
] | checks whether a character is cased . | train | false |
32,136 | def replace_ids(container, id_map):
changed = False
for (name, media_type) in container.mime_map.iteritems():
repl = IdReplacer(name, container, id_map)
container.replace_links(name, repl)
if (name == container.opf_name):
imap = id_map.get(name, {})
for item in container.opf_xpath(u'//*[@idref]'):
old... | [
"def",
"replace_ids",
"(",
"container",
",",
"id_map",
")",
":",
"changed",
"=",
"False",
"for",
"(",
"name",
",",
"media_type",
")",
"in",
"container",
".",
"mime_map",
".",
"iteritems",
"(",
")",
":",
"repl",
"=",
"IdReplacer",
"(",
"name",
",",
"con... | replace all links in the container that pointed to the changed ids . | train | false |
32,137 | def build_instance_groups(parsed_instance_groups):
instance_groups = []
for instance_group in parsed_instance_groups:
ig_config = {}
keys = instance_group.keys()
if ('Name' in keys):
ig_config['Name'] = instance_group['Name']
else:
ig_config['Name'] = instance_group['InstanceGroupType']
ig_config['Ins... | [
"def",
"build_instance_groups",
"(",
"parsed_instance_groups",
")",
":",
"instance_groups",
"=",
"[",
"]",
"for",
"instance_group",
"in",
"parsed_instance_groups",
":",
"ig_config",
"=",
"{",
"}",
"keys",
"=",
"instance_group",
".",
"keys",
"(",
")",
"if",
"(",
... | helper method that converts --instance-groups option value in create-cluster and add-instance-groups to amazon elastic mapreduce instancegroupconfig data type . | train | false |
32,139 | @pytest.mark.svn
def test_install_editable_from_svn(script):
checkout_path = _create_test_package(script)
repo_url = _create_svn_repo(script, checkout_path)
result = script.pip('install', '-e', (('svn+' + repo_url) + '#egg=version-pkg'))
result.assert_installed('version-pkg', with_files=['.svn'])
| [
"@",
"pytest",
".",
"mark",
".",
"svn",
"def",
"test_install_editable_from_svn",
"(",
"script",
")",
":",
"checkout_path",
"=",
"_create_test_package",
"(",
"script",
")",
"repo_url",
"=",
"_create_svn_repo",
"(",
"script",
",",
"checkout_path",
")",
"result",
"... | test checking out from svn . | train | false |
32,140 | def json(text):
if r_json.match(r_string.sub('', text)):
text = r_string.sub((lambda m: ('u' + m.group(1))), text)
return eval(text.strip(' DCTB \r\n'), env, {})
raise ValueError('Input must be serialised JSON.')
| [
"def",
"json",
"(",
"text",
")",
":",
"if",
"r_json",
".",
"match",
"(",
"r_string",
".",
"sub",
"(",
"''",
",",
"text",
")",
")",
":",
"text",
"=",
"r_string",
".",
"sub",
"(",
"(",
"lambda",
"m",
":",
"(",
"'u'",
"+",
"m",
".",
"group",
"("... | takes json formatted data . | train | false |
32,141 | def get_collection_rights(collection_id, strict=True):
model = collection_models.CollectionRightsModel.get(collection_id, strict=strict)
if (model is None):
return None
return _get_activity_rights_from_model(model, feconf.ACTIVITY_TYPE_COLLECTION)
| [
"def",
"get_collection_rights",
"(",
"collection_id",
",",
"strict",
"=",
"True",
")",
":",
"model",
"=",
"collection_models",
".",
"CollectionRightsModel",
".",
"get",
"(",
"collection_id",
",",
"strict",
"=",
"strict",
")",
"if",
"(",
"model",
"is",
"None",
... | retrieves the rights for this collection from the datastore . | train | false |
32,142 | def validate_boolean_or_string(option, value):
if isinstance(value, string_type):
if (value not in ('true', 'false')):
raise ValueError(("The value of %s must be 'true' or 'false'" % (option,)))
return (value == 'true')
return validate_boolean(option, value)
| [
"def",
"validate_boolean_or_string",
"(",
"option",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"string_type",
")",
":",
"if",
"(",
"value",
"not",
"in",
"(",
"'true'",
",",
"'false'",
")",
")",
":",
"raise",
"ValueError",
"(",
"(",
... | validates that value is true . | train | true |
32,143 | def has_man_pages(build):
return bool(build.distribution.man_pages)
| [
"def",
"has_man_pages",
"(",
"build",
")",
":",
"return",
"bool",
"(",
"build",
".",
"distribution",
".",
"man_pages",
")"
] | check if the distribution has configuration files to work on . | train | false |
32,144 | @task.task(ignore_result=True)
def store_friends(user, friends):
converter_class = get_class_for('user_conversion')
logger.info(('celery is storing %s friends' % len(friends)))
converter_class._store_friends(user, friends)
return friends
| [
"@",
"task",
".",
"task",
"(",
"ignore_result",
"=",
"True",
")",
"def",
"store_friends",
"(",
"user",
",",
"friends",
")",
":",
"converter_class",
"=",
"get_class_for",
"(",
"'user_conversion'",
")",
"logger",
".",
"info",
"(",
"(",
"'celery is storing %s fri... | inserting again will not cause any errors . | train | false |
32,145 | def fixed_ip_get_by_floating_address(context, floating_address):
return IMPL.fixed_ip_get_by_floating_address(context, floating_address)
| [
"def",
"fixed_ip_get_by_floating_address",
"(",
"context",
",",
"floating_address",
")",
":",
"return",
"IMPL",
".",
"fixed_ip_get_by_floating_address",
"(",
"context",
",",
"floating_address",
")"
] | get a fixed ip by a floating address . | train | false |
32,146 | def report_messages_stats(sect, stats, _):
if (not stats['by_msg']):
raise utils.EmptyReport()
in_order = sorted([(value, msg_id) for (msg_id, value) in six.iteritems(stats['by_msg']) if (not msg_id.startswith('I'))])
in_order.reverse()
lines = ('message id', 'occurrences')
for (value, msg_id) in in_order:
lin... | [
"def",
"report_messages_stats",
"(",
"sect",
",",
"stats",
",",
"_",
")",
":",
"if",
"(",
"not",
"stats",
"[",
"'by_msg'",
"]",
")",
":",
"raise",
"utils",
".",
"EmptyReport",
"(",
")",
"in_order",
"=",
"sorted",
"(",
"[",
"(",
"value",
",",
"msg_id"... | make messages type report . | train | false |
32,147 | def services_required(*req_services):
def actual_decoration(obj):
skip_method = _get_skip_method(obj)
avail_services = config.get_config().service_available
for req_service in req_services:
if (not getattr(avail_services, req_service, False)):
obj = skip_method(obj, ('%s service is required for this test ... | [
"def",
"services_required",
"(",
"*",
"req_services",
")",
":",
"def",
"actual_decoration",
"(",
"obj",
")",
":",
"skip_method",
"=",
"_get_skip_method",
"(",
"obj",
")",
"avail_services",
"=",
"config",
".",
"get_config",
"(",
")",
".",
"service_available",
"... | decorator for marking tests service requirements . | train | false |
32,148 | def _apply_rules(name, rules):
if ('nofqdn' in rules):
name = name.split('.', 1)[0]
if ('lower' in rules):
name = name.lower()
return name
| [
"def",
"_apply_rules",
"(",
"name",
",",
"rules",
")",
":",
"if",
"(",
"'nofqdn'",
"in",
"rules",
")",
":",
"name",
"=",
"name",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"[",
"0",
"]",
"if",
"(",
"'lower'",
"in",
"rules",
")",
":",
"name",
"=",... | apply rules on the objects names . | train | false |
32,149 | def test_strict_exeggcute(session, media_root):
with pytest.raises(ValueError):
exeggcute = session.query(tables.PokemonSpecies).filter_by(identifier=u'exeggcute').one()
accessor = media.PokemonSpeciesMedia(media_root, exeggcute)
accessor.sprite(female=True, strict=True)
| [
"def",
"test_strict_exeggcute",
"(",
"session",
",",
"media_root",
")",
":",
"with",
"pytest",
".",
"raises",
"(",
"ValueError",
")",
":",
"exeggcute",
"=",
"session",
".",
"query",
"(",
"tables",
".",
"PokemonSpecies",
")",
".",
"filter_by",
"(",
"identifie... | exeggcutess female backsprite . | train | false |
32,151 | def _get_fill_value(dtype, fill_value=None, fill_value_typ=None):
if (fill_value is not None):
return fill_value
if _na_ok_dtype(dtype):
if (fill_value_typ is None):
return np.nan
elif (fill_value_typ == '+inf'):
return np.inf
else:
return (- np.inf)
elif (fill_value_typ is None):
return tslib.iNa... | [
"def",
"_get_fill_value",
"(",
"dtype",
",",
"fill_value",
"=",
"None",
",",
"fill_value_typ",
"=",
"None",
")",
":",
"if",
"(",
"fill_value",
"is",
"not",
"None",
")",
":",
"return",
"fill_value",
"if",
"_na_ok_dtype",
"(",
"dtype",
")",
":",
"if",
"(",... | return the correct fill value for the dtype of the values . | train | true |
32,153 | def GetWSAActionOutput(operation):
attr = operation.output.action
if (attr is not None):
return attr
targetNamespace = operation.getPortType().getTargetNamespace()
ptName = operation.getPortType().name
msgName = operation.output.name
if (not msgName):
msgName = (operation.name + 'Response')
if targetNamespac... | [
"def",
"GetWSAActionOutput",
"(",
"operation",
")",
":",
"attr",
"=",
"operation",
".",
"output",
".",
"action",
"if",
"(",
"attr",
"is",
"not",
"None",
")",
":",
"return",
"attr",
"targetNamespace",
"=",
"operation",
".",
"getPortType",
"(",
")",
".",
"... | find wsa:action attribute . | train | true |
32,154 | def testparagraph():
testpara = paragraph('paratext', style='BodyText')
assert (testpara.tag == '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}p')
pass
| [
"def",
"testparagraph",
"(",
")",
":",
"testpara",
"=",
"paragraph",
"(",
"'paratext'",
",",
"style",
"=",
"'BodyText'",
")",
"assert",
"(",
"testpara",
".",
"tag",
"==",
"'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}p'",
")",
"pass"
] | ensure paragraph creates p elements . | train | false |
32,156 | def _double_as_bytes(dval):
tmp = list(struct.unpack('8B', struct.pack('d', dval)))
if (not _big_endian):
tmp.reverse()
return tmp
| [
"def",
"_double_as_bytes",
"(",
"dval",
")",
":",
"tmp",
"=",
"list",
"(",
"struct",
".",
"unpack",
"(",
"'8B'",
",",
"struct",
".",
"pack",
"(",
"'d'",
",",
"dval",
")",
")",
")",
"if",
"(",
"not",
"_big_endian",
")",
":",
"tmp",
".",
"reverse",
... | use struct . | train | true |
32,157 | def str2pyval(string):
try:
return ast.literal_eval(string)
except (ValueError, SyntaxError):
return _PYVALS.get(string, string)
| [
"def",
"str2pyval",
"(",
"string",
")",
":",
"try",
":",
"return",
"ast",
".",
"literal_eval",
"(",
"string",
")",
"except",
"(",
"ValueError",
",",
"SyntaxError",
")",
":",
"return",
"_PYVALS",
".",
"get",
"(",
"string",
",",
"string",
")"
] | this function takes a string and returns a python object . | train | false |
32,158 | def copy2(src, dst):
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
copyfile(src, dst)
copystat(src, dst)
| [
"def",
"copy2",
"(",
"src",
",",
"dst",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dst",
")",
":",
"dst",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst",
",",
"os",
".",
"path",
".",
"basename",
"(",
"src",
")",
")",
"copyfile",
... | copy data and all stat info . | train | true |
32,159 | @_restore_ownership
def create_key(key_type='RSA', key_length=1024, name_real='Autogenerated Key', name_comment='Generated by SaltStack', name_email=None, subkey_type=None, subkey_length=None, expire_date=None, use_passphrase=False, user=None, gnupghome=None):
ret = {'res': True, 'fingerprint': '', 'message': ''}
cre... | [
"@",
"_restore_ownership",
"def",
"create_key",
"(",
"key_type",
"=",
"'RSA'",
",",
"key_length",
"=",
"1024",
",",
"name_real",
"=",
"'Autogenerated Key'",
",",
"name_comment",
"=",
"'Generated by SaltStack'",
",",
"name_email",
"=",
"None",
",",
"subkey_type",
"... | creates a master key . | train | true |
32,160 | def default_representer(dumper, data):
return dumper.represent_str(str(data))
| [
"def",
"default_representer",
"(",
"dumper",
",",
"data",
")",
":",
"return",
"dumper",
".",
"represent_str",
"(",
"str",
"(",
"data",
")",
")"
] | default representer . | train | false |
32,161 | def commit():
connection._commit()
set_clean()
| [
"def",
"commit",
"(",
")",
":",
"connection",
".",
"_commit",
"(",
")",
"set_clean",
"(",
")"
] | commits a transaction and resets the dirty flag . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.