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
16,432
def notepadplusplus(exe=u'notepad++'): install_editor((exe + u' -n{line} {filename}'))
[ "def", "notepadplusplus", "(", "exe", "=", "u'notepad++'", ")", ":", "install_editor", "(", "(", "exe", "+", "u' -n{line} {filename}'", ")", ")" ]
notepad++ URL .
train
false
16,434
def _divide_side(lobe, x): lobe = np.asarray(lobe) median = np.median(x[lobe]) left = lobe[np.where((x[lobe] < median))[0]] right = lobe[np.where((x[lobe] > median))[0]] medians = np.where((x[lobe] == median))[0] left = np.sort(np.concatenate([left, lobe[medians[1::2]]])) right = np.sort(np.concatenate([right, lobe[medians[::2]]])) return (list(left), list(right))
[ "def", "_divide_side", "(", "lobe", ",", "x", ")", ":", "lobe", "=", "np", ".", "asarray", "(", "lobe", ")", "median", "=", "np", ".", "median", "(", "x", "[", "lobe", "]", ")", "left", "=", "lobe", "[", "np", ".", "where", "(", "(", "x", "[", "lobe", "]", "<", "median", ")", ")", "[", "0", "]", "]", "right", "=", "lobe", "[", "np", ".", "where", "(", "(", "x", "[", "lobe", "]", ">", "median", ")", ")", "[", "0", "]", "]", "medians", "=", "np", ".", "where", "(", "(", "x", "[", "lobe", "]", "==", "median", ")", ")", "[", "0", "]", "left", "=", "np", ".", "sort", "(", "np", ".", "concatenate", "(", "[", "left", ",", "lobe", "[", "medians", "[", "1", ":", ":", "2", "]", "]", "]", ")", ")", "right", "=", "np", ".", "sort", "(", "np", ".", "concatenate", "(", "[", "right", ",", "lobe", "[", "medians", "[", ":", ":", "2", "]", "]", "]", ")", ")", "return", "(", "list", "(", "left", ")", ",", "list", "(", "right", ")", ")" ]
helper for making a separation between left and right lobe evenly .
train
false
16,436
def resolve_cert_reqs(candidate): if (candidate is None): return CERT_NONE if isinstance(candidate, str): res = getattr(ssl, candidate, None) if (res is None): res = getattr(ssl, ('CERT_' + candidate)) return res return candidate
[ "def", "resolve_cert_reqs", "(", "candidate", ")", ":", "if", "(", "candidate", "is", "None", ")", ":", "return", "CERT_NONE", "if", "isinstance", "(", "candidate", ",", "str", ")", ":", "res", "=", "getattr", "(", "ssl", ",", "candidate", ",", "None", ")", "if", "(", "res", "is", "None", ")", ":", "res", "=", "getattr", "(", "ssl", ",", "(", "'CERT_'", "+", "candidate", ")", ")", "return", "res", "return", "candidate" ]
resolves the argument to a numeric constant .
train
true
16,437
def UploadUnconvertedFileSample(): client = CreateClient() doc = gdata.docs.data.Resource(type='document', title='My Sample Raw Doc') path = _GetDataFilePath('test.0.doc') media = gdata.data.MediaSource() media.SetFileHandle(path, 'application/msword') create_uri = (gdata.docs.client.RESOURCE_UPLOAD_URI + '?convert=false') doc = client.CreateResource(doc, create_uri=create_uri, media=media) print 'Created, and uploaded:', doc.title.text, doc.resource_id.text
[ "def", "UploadUnconvertedFileSample", "(", ")", ":", "client", "=", "CreateClient", "(", ")", "doc", "=", "gdata", ".", "docs", ".", "data", ".", "Resource", "(", "type", "=", "'document'", ",", "title", "=", "'My Sample Raw Doc'", ")", "path", "=", "_GetDataFilePath", "(", "'test.0.doc'", ")", "media", "=", "gdata", ".", "data", ".", "MediaSource", "(", ")", "media", ".", "SetFileHandle", "(", "path", ",", "'application/msword'", ")", "create_uri", "=", "(", "gdata", ".", "docs", ".", "client", ".", "RESOURCE_UPLOAD_URI", "+", "'?convert=false'", ")", "doc", "=", "client", ".", "CreateResource", "(", "doc", ",", "create_uri", "=", "create_uri", ",", "media", "=", "media", ")", "print", "'Created, and uploaded:'", ",", "doc", ".", "title", ".", "text", ",", "doc", ".", "resource_id", ".", "text" ]
upload a document .
train
false
16,440
def sync_languages(): with open(frappe.get_app_path(u'frappe', u'geo', u'languages.json'), u'r') as f: data = json.loads(f.read()) for l in data: if (not frappe.db.exists(u'Language', l[u'code'])): frappe.get_doc({u'doctype': u'Language', u'language_code': l[u'code'], u'language_name': l[u'name']}).insert()
[ "def", "sync_languages", "(", ")", ":", "with", "open", "(", "frappe", ".", "get_app_path", "(", "u'frappe'", ",", "u'geo'", ",", "u'languages.json'", ")", ",", "u'r'", ")", "as", "f", ":", "data", "=", "json", ".", "loads", "(", "f", ".", "read", "(", ")", ")", "for", "l", "in", "data", ":", "if", "(", "not", "frappe", ".", "db", ".", "exists", "(", "u'Language'", ",", "l", "[", "u'code'", "]", ")", ")", ":", "frappe", ".", "get_doc", "(", "{", "u'doctype'", ":", "u'Language'", ",", "u'language_code'", ":", "l", "[", "u'code'", "]", ",", "u'language_name'", ":", "l", "[", "u'name'", "]", "}", ")", ".", "insert", "(", ")" ]
sync frappe/geo/languages .
train
false
16,443
def _AddIOSDeviceConfigurations(targets): for target_dict in targets.itervalues(): toolset = target_dict['toolset'] configs = target_dict['configurations'] for (config_name, config_dict) in dict(configs).iteritems(): iphoneos_config_dict = copy.deepcopy(config_dict) configs[(config_name + '-iphoneos')] = iphoneos_config_dict configs[(config_name + '-iphonesimulator')] = config_dict if (toolset == 'target'): iphoneos_config_dict['xcode_settings']['SDKROOT'] = 'iphoneos' return targets
[ "def", "_AddIOSDeviceConfigurations", "(", "targets", ")", ":", "for", "target_dict", "in", "targets", ".", "itervalues", "(", ")", ":", "toolset", "=", "target_dict", "[", "'toolset'", "]", "configs", "=", "target_dict", "[", "'configurations'", "]", "for", "(", "config_name", ",", "config_dict", ")", "in", "dict", "(", "configs", ")", ".", "iteritems", "(", ")", ":", "iphoneos_config_dict", "=", "copy", ".", "deepcopy", "(", "config_dict", ")", "configs", "[", "(", "config_name", "+", "'-iphoneos'", ")", "]", "=", "iphoneos_config_dict", "configs", "[", "(", "config_name", "+", "'-iphonesimulator'", ")", "]", "=", "config_dict", "if", "(", "toolset", "==", "'target'", ")", ":", "iphoneos_config_dict", "[", "'xcode_settings'", "]", "[", "'SDKROOT'", "]", "=", "'iphoneos'", "return", "targets" ]
clone all targets and append -iphoneos to the name .
train
false
16,444
def test_error_handling(): class TestException(Exception, ): pass try: with cd('somewhere'): raise TestException('Houston, we have a problem.') except TestException: pass finally: with cd('else'): eq_(env.cwd, 'else')
[ "def", "test_error_handling", "(", ")", ":", "class", "TestException", "(", "Exception", ",", ")", ":", "pass", "try", ":", "with", "cd", "(", "'somewhere'", ")", ":", "raise", "TestException", "(", "'Houston, we have a problem.'", ")", "except", "TestException", ":", "pass", "finally", ":", "with", "cd", "(", "'else'", ")", ":", "eq_", "(", "env", ".", "cwd", ",", "'else'", ")" ]
cd cleans up after itself even in case of an exception .
train
false
16,447
def GetIndexedTimeZoneNames(index_key='Index'): for timeZoneName in GetTimeZoneNames(): tzRegKeyPath = os.path.join(TimeZoneInfo.tzRegKey, timeZoneName) key = _winreg.OpenKeyEx(_winreg.HKEY_LOCAL_MACHINE, tzRegKeyPath) (tzIndex, type) = _winreg.QueryValueEx(key, index_key) (yield (tzIndex, timeZoneName))
[ "def", "GetIndexedTimeZoneNames", "(", "index_key", "=", "'Index'", ")", ":", "for", "timeZoneName", "in", "GetTimeZoneNames", "(", ")", ":", "tzRegKeyPath", "=", "os", ".", "path", ".", "join", "(", "TimeZoneInfo", ".", "tzRegKey", ",", "timeZoneName", ")", "key", "=", "_winreg", ".", "OpenKeyEx", "(", "_winreg", ".", "HKEY_LOCAL_MACHINE", ",", "tzRegKeyPath", ")", "(", "tzIndex", ",", "type", ")", "=", "_winreg", ".", "QueryValueEx", "(", "key", ",", "index_key", ")", "(", "yield", "(", "tzIndex", ",", "timeZoneName", ")", ")" ]
returns the names of the time zones as defined in the registry .
train
false
16,448
def styleof(expr, styles=default_styles): style = dict() for (typ, sty) in styles: if isinstance(expr, typ): style.update(sty) return style
[ "def", "styleof", "(", "expr", ",", "styles", "=", "default_styles", ")", ":", "style", "=", "dict", "(", ")", "for", "(", "typ", ",", "sty", ")", "in", "styles", ":", "if", "isinstance", "(", "expr", ",", "typ", ")", ":", "style", ".", "update", "(", "sty", ")", "return", "style" ]
merge style dictionaries in order .
train
false
16,449
def setup_students_and_grades(context): if context.course: context.student = student = UserFactory.create() CourseEnrollmentFactory.create(user=student, course_id=context.course.id) context.student2 = student2 = UserFactory.create() CourseEnrollmentFactory.create(user=student2, course_id=context.course.id) for chapter in context.course.get_children(): for (i, section) in enumerate(chapter.get_children()): for (j, problem) in enumerate(section.get_children()): StudentModuleFactory.create(grade=(1 if (i < j) else 0), max_grade=1, student=context.student, course_id=context.course.id, module_state_key=problem.location) StudentModuleFactory.create(grade=(1 if (i > j) else 0), max_grade=1, student=context.student2, course_id=context.course.id, module_state_key=problem.location)
[ "def", "setup_students_and_grades", "(", "context", ")", ":", "if", "context", ".", "course", ":", "context", ".", "student", "=", "student", "=", "UserFactory", ".", "create", "(", ")", "CourseEnrollmentFactory", ".", "create", "(", "user", "=", "student", ",", "course_id", "=", "context", ".", "course", ".", "id", ")", "context", ".", "student2", "=", "student2", "=", "UserFactory", ".", "create", "(", ")", "CourseEnrollmentFactory", ".", "create", "(", "user", "=", "student2", ",", "course_id", "=", "context", ".", "course", ".", "id", ")", "for", "chapter", "in", "context", ".", "course", ".", "get_children", "(", ")", ":", "for", "(", "i", ",", "section", ")", "in", "enumerate", "(", "chapter", ".", "get_children", "(", ")", ")", ":", "for", "(", "j", ",", "problem", ")", "in", "enumerate", "(", "section", ".", "get_children", "(", ")", ")", ":", "StudentModuleFactory", ".", "create", "(", "grade", "=", "(", "1", "if", "(", "i", "<", "j", ")", "else", "0", ")", ",", "max_grade", "=", "1", ",", "student", "=", "context", ".", "student", ",", "course_id", "=", "context", ".", "course", ".", "id", ",", "module_state_key", "=", "problem", ".", "location", ")", "StudentModuleFactory", ".", "create", "(", "grade", "=", "(", "1", "if", "(", "i", ">", "j", ")", "else", "0", ")", ",", "max_grade", "=", "1", ",", "student", "=", "context", ".", "student2", ",", "course_id", "=", "context", ".", "course", ".", "id", ",", "module_state_key", "=", "problem", ".", "location", ")" ]
create students and set their grades .
train
false
16,450
@db_api.api_context_manager.reader def _refresh_from_db(ctx, cache): with db_api.api_context_manager.reader.connection.using(ctx) as conn: sel = sa.select([_RC_TBL.c.id, _RC_TBL.c.name]) res = conn.execute(sel).fetchall() cache.id_cache = {r[1]: r[0] for r in res} cache.str_cache = {r[0]: r[1] for r in res}
[ "@", "db_api", ".", "api_context_manager", ".", "reader", "def", "_refresh_from_db", "(", "ctx", ",", "cache", ")", ":", "with", "db_api", ".", "api_context_manager", ".", "reader", ".", "connection", ".", "using", "(", "ctx", ")", "as", "conn", ":", "sel", "=", "sa", ".", "select", "(", "[", "_RC_TBL", ".", "c", ".", "id", ",", "_RC_TBL", ".", "c", ".", "name", "]", ")", "res", "=", "conn", ".", "execute", "(", "sel", ")", ".", "fetchall", "(", ")", "cache", ".", "id_cache", "=", "{", "r", "[", "1", "]", ":", "r", "[", "0", "]", "for", "r", "in", "res", "}", "cache", ".", "str_cache", "=", "{", "r", "[", "0", "]", ":", "r", "[", "1", "]", "for", "r", "in", "res", "}" ]
grabs all custom resource classes from the db table and populates the supplied cache objects internal integer and string identifier dicts .
train
false
16,451
def get_image_dimensions(file_or_path, close=False): from PIL import ImageFile as PillowImageFile p = PillowImageFile.Parser() if hasattr(file_or_path, 'read'): file = file_or_path file_pos = file.tell() file.seek(0) else: file = open(file_or_path, 'rb') close = True try: chunk_size = 1024 while 1: data = file.read(chunk_size) if (not data): break try: p.feed(data) except zlib.error as e: if e.args[0].startswith('Error -5'): pass else: raise except struct.error: pass if p.image: return p.image.size chunk_size *= 2 return (None, None) finally: if close: file.close() else: file.seek(file_pos)
[ "def", "get_image_dimensions", "(", "file_or_path", ",", "close", "=", "False", ")", ":", "from", "PIL", "import", "ImageFile", "as", "PillowImageFile", "p", "=", "PillowImageFile", ".", "Parser", "(", ")", "if", "hasattr", "(", "file_or_path", ",", "'read'", ")", ":", "file", "=", "file_or_path", "file_pos", "=", "file", ".", "tell", "(", ")", "file", ".", "seek", "(", "0", ")", "else", ":", "file", "=", "open", "(", "file_or_path", ",", "'rb'", ")", "close", "=", "True", "try", ":", "chunk_size", "=", "1024", "while", "1", ":", "data", "=", "file", ".", "read", "(", "chunk_size", ")", "if", "(", "not", "data", ")", ":", "break", "try", ":", "p", ".", "feed", "(", "data", ")", "except", "zlib", ".", "error", "as", "e", ":", "if", "e", ".", "args", "[", "0", "]", ".", "startswith", "(", "'Error -5'", ")", ":", "pass", "else", ":", "raise", "except", "struct", ".", "error", ":", "pass", "if", "p", ".", "image", ":", "return", "p", ".", "image", ".", "size", "chunk_size", "*=", "2", "return", "(", "None", ",", "None", ")", "finally", ":", "if", "close", ":", "file", ".", "close", "(", ")", "else", ":", "file", ".", "seek", "(", "file_pos", ")" ]
returns the of an image .
train
false
16,452
@task @needs(['reset_test_database', 'clear_mongo', 'load_bok_choy_data', 'load_courses']) @might_call('start_servers') @cmdopts([BOKCHOY_FASTTEST], share_with=['start_servers']) @timed def prepare_bokchoy_run(options): if (not options.get('fasttest', False)): print colorize('green', 'Generating optimized static assets...') if (options.get('log_dir') is None): call_task('update_assets', args=['--settings', 'test_static_optimized']) else: call_task('update_assets', args=['--settings', 'test_static_optimized', '--collect-log', options.log_dir]) msg = colorize('green', 'Confirming servers are running...') print msg start_servers()
[ "@", "task", "@", "needs", "(", "[", "'reset_test_database'", ",", "'clear_mongo'", ",", "'load_bok_choy_data'", ",", "'load_courses'", "]", ")", "@", "might_call", "(", "'start_servers'", ")", "@", "cmdopts", "(", "[", "BOKCHOY_FASTTEST", "]", ",", "share_with", "=", "[", "'start_servers'", "]", ")", "@", "timed", "def", "prepare_bokchoy_run", "(", "options", ")", ":", "if", "(", "not", "options", ".", "get", "(", "'fasttest'", ",", "False", ")", ")", ":", "print", "colorize", "(", "'green'", ",", "'Generating optimized static assets...'", ")", "if", "(", "options", ".", "get", "(", "'log_dir'", ")", "is", "None", ")", ":", "call_task", "(", "'update_assets'", ",", "args", "=", "[", "'--settings'", ",", "'test_static_optimized'", "]", ")", "else", ":", "call_task", "(", "'update_assets'", ",", "args", "=", "[", "'--settings'", ",", "'test_static_optimized'", ",", "'--collect-log'", ",", "options", ".", "log_dir", "]", ")", "msg", "=", "colorize", "(", "'green'", ",", "'Confirming servers are running...'", ")", "print", "msg", "start_servers", "(", ")" ]
sets up and starts servers for a bok choy run .
train
false
16,453
def current_env(): if (config.default_prefix == config.root_dir): name = config.root_env_name else: name = basename(config.default_prefix) return name
[ "def", "current_env", "(", ")", ":", "if", "(", "config", ".", "default_prefix", "==", "config", ".", "root_dir", ")", ":", "name", "=", "config", ".", "root_env_name", "else", ":", "name", "=", "basename", "(", "config", ".", "default_prefix", ")", "return", "name" ]
retrieves dictionary with current environments name and prefix .
train
false
16,454
def read_fixture_lines(filename): lines = [] for line in codecs.open(filename, u'rb', encoding=u'utf-8'): lines.append(line.strip()) return lines
[ "def", "read_fixture_lines", "(", "filename", ")", ":", "lines", "=", "[", "]", "for", "line", "in", "codecs", ".", "open", "(", "filename", ",", "u'rb'", ",", "encoding", "=", "u'utf-8'", ")", ":", "lines", ".", "append", "(", "line", ".", "strip", "(", ")", ")", "return", "lines" ]
read lines of text from file .
train
false
16,455
def safe_concurrent_rename(src, dst): if os.path.isdir(src): safe_rmtree(dst) else: safe_delete(dst) try: shutil.move(src, dst) except IOError as e: if (e.errno != errno.EEXIST): raise
[ "def", "safe_concurrent_rename", "(", "src", ",", "dst", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "src", ")", ":", "safe_rmtree", "(", "dst", ")", "else", ":", "safe_delete", "(", "dst", ")", "try", ":", "shutil", ".", "move", "(", "src", ",", "dst", ")", "except", "IOError", "as", "e", ":", "if", "(", "e", ".", "errno", "!=", "errno", ".", "EEXIST", ")", ":", "raise" ]
rename src to dst .
train
true
16,459
def cnv_date(attribute, arg, element): return str(arg)
[ "def", "cnv_date", "(", "attribute", ",", "arg", ",", "element", ")", ":", "return", "str", "(", "arg", ")" ]
a dateordatetime value is either an [xmlschema-2] date value or an [xmlschema-2] datetime value .
train
false
16,460
def get_active_streams(realm): return Stream.objects.filter(realm=realm, deactivated=False)
[ "def", "get_active_streams", "(", "realm", ")", ":", "return", "Stream", ".", "objects", ".", "filter", "(", "realm", "=", "realm", ",", "deactivated", "=", "False", ")" ]
return all streams that have not been deactivated .
train
false
16,461
def _get_pretty_string(obj): sio = StringIO() pprint.pprint(obj, stream=sio) return sio.getvalue()
[ "def", "_get_pretty_string", "(", "obj", ")", ":", "sio", "=", "StringIO", "(", ")", "pprint", ".", "pprint", "(", "obj", ",", "stream", "=", "sio", ")", "return", "sio", ".", "getvalue", "(", ")" ]
return a prettier version of obj parameters obj : object object to pretty print returns s : str pretty print object repr .
train
true
16,462
def imview(*args, **kwargs): if ('figure' not in kwargs): f = plt.figure() else: f = kwargs['figure'] new_ax = matplotlib.axes.Axes(f, [0, 0, 1, 1], xticks=[], yticks=[], frame_on=False) f.delaxes(f.gca()) f.add_axes(new_ax) if ((len(args) < 5) and ('interpolation' not in kwargs)): kwargs['interpolation'] = 'nearest' plt.imshow(*args, **kwargs)
[ "def", "imview", "(", "*", "args", ",", "**", "kwargs", ")", ":", "if", "(", "'figure'", "not", "in", "kwargs", ")", ":", "f", "=", "plt", ".", "figure", "(", ")", "else", ":", "f", "=", "kwargs", "[", "'figure'", "]", "new_ax", "=", "matplotlib", ".", "axes", ".", "Axes", "(", "f", ",", "[", "0", ",", "0", ",", "1", ",", "1", "]", ",", "xticks", "=", "[", "]", ",", "yticks", "=", "[", "]", ",", "frame_on", "=", "False", ")", "f", ".", "delaxes", "(", "f", ".", "gca", "(", ")", ")", "f", ".", "add_axes", "(", "new_ax", ")", "if", "(", "(", "len", "(", "args", ")", "<", "5", ")", "and", "(", "'interpolation'", "not", "in", "kwargs", ")", ")", ":", "kwargs", "[", "'interpolation'", "]", "=", "'nearest'", "plt", ".", "imshow", "(", "*", "args", ",", "**", "kwargs", ")" ]
a matplotlib-based image viewer command .
train
false
16,464
def _build_tag_param_list(params, tags): keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if (value is not None): params['Tags.member.{0}.Value'.format(i)] = value i += 1
[ "def", "_build_tag_param_list", "(", "params", ",", "tags", ")", ":", "keys", "=", "sorted", "(", "tags", ".", "keys", "(", ")", ")", "i", "=", "1", "for", "key", "in", "keys", ":", "value", "=", "tags", "[", "key", "]", "params", "[", "'Tags.member.{0}.Key'", ".", "format", "(", "i", ")", "]", "=", "key", "if", "(", "value", "is", "not", "None", ")", ":", "params", "[", "'Tags.member.{0}.Value'", ".", "format", "(", "i", ")", "]", "=", "value", "i", "+=", "1" ]
helper function to build a tag parameter list to send .
train
true
16,465
def call_xenhost(session, method, arg_dict): try: result = session.call_plugin('xenhost.py', method, args=arg_dict) if (not result): return '' return jsonutils.loads(result) except ValueError: LOG.exception(_LE('Unable to get updated status')) return None except session.XenAPI.Failure as e: LOG.error(_LE('The call to %(method)s returned an error: %(e)s.'), {'method': method, 'e': e}) return e.details[1]
[ "def", "call_xenhost", "(", "session", ",", "method", ",", "arg_dict", ")", ":", "try", ":", "result", "=", "session", ".", "call_plugin", "(", "'xenhost.py'", ",", "method", ",", "args", "=", "arg_dict", ")", "if", "(", "not", "result", ")", ":", "return", "''", "return", "jsonutils", ".", "loads", "(", "result", ")", "except", "ValueError", ":", "LOG", ".", "exception", "(", "_LE", "(", "'Unable to get updated status'", ")", ")", "return", "None", "except", "session", ".", "XenAPI", ".", "Failure", "as", "e", ":", "LOG", ".", "error", "(", "_LE", "(", "'The call to %(method)s returned an error: %(e)s.'", ")", ",", "{", "'method'", ":", "method", ",", "'e'", ":", "e", "}", ")", "return", "e", ".", "details", "[", "1", "]" ]
there will be several methods that will need this general handling for interacting with the xenhost plugin .
train
false
16,466
def bump_shop_product_signal_handler(sender, instance, **kwargs): bump_cache_for_shop_product(instance)
[ "def", "bump_shop_product_signal_handler", "(", "sender", ",", "instance", ",", "**", "kwargs", ")", ":", "bump_cache_for_shop_product", "(", "instance", ")" ]
signal handler for clearing shop product cache .
train
false
16,467
def merge_geometries(geometries_str, sep='$'): geometries = geometries_str.split(sep) if (len(geometries) == 1): return geometries_str else: pool = OGRGeometry(geometries[0]) for geom in geometries: pool = pool.union(OGRGeometry(geom)) return pool.wkt
[ "def", "merge_geometries", "(", "geometries_str", ",", "sep", "=", "'$'", ")", ":", "geometries", "=", "geometries_str", ".", "split", "(", "sep", ")", "if", "(", "len", "(", "geometries", ")", "==", "1", ")", ":", "return", "geometries_str", "else", ":", "pool", "=", "OGRGeometry", "(", "geometries", "[", "0", "]", ")", "for", "geom", "in", "geometries", ":", "pool", "=", "pool", ".", "union", "(", "OGRGeometry", "(", "geom", ")", ")", "return", "pool", ".", "wkt" ]
take a list of geometries in a string .
train
false
16,468
@validator def app(environ, start_response): if (environ['REQUEST_METHOD'].upper() != 'POST'): data = 'Hello, World!\n' else: data = environ['wsgi.input'].read() status = '200 OK' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(data))), ('X-Gunicorn-Version', __version__), ('Test', 'test \xd1\x82\xd0\xb5\xd1\x81\xd1\x82')] start_response(status, response_headers) return iter([data])
[ "@", "validator", "def", "app", "(", "environ", ",", "start_response", ")", ":", "if", "(", "environ", "[", "'REQUEST_METHOD'", "]", ".", "upper", "(", ")", "!=", "'POST'", ")", ":", "data", "=", "'Hello, World!\\n'", "else", ":", "data", "=", "environ", "[", "'wsgi.input'", "]", ".", "read", "(", ")", "status", "=", "'200 OK'", "response_headers", "=", "[", "(", "'Content-type'", ",", "'text/plain'", ")", ",", "(", "'Content-Length'", ",", "str", "(", "len", "(", "data", ")", ")", ")", ",", "(", "'X-Gunicorn-Version'", ",", "__version__", ")", ",", "(", "'Test'", ",", "'test \\xd1\\x82\\xd0\\xb5\\xd1\\x81\\xd1\\x82'", ")", "]", "start_response", "(", "status", ",", "response_headers", ")", "return", "iter", "(", "[", "data", "]", ")" ]
simplest possible application object .
train
false
16,469
def safe_izip(*args): assert all([(len(arg) == len(args[0])) for arg in args]) return izip(*args)
[ "def", "safe_izip", "(", "*", "args", ")", ":", "assert", "all", "(", "[", "(", "len", "(", "arg", ")", "==", "len", "(", "args", "[", "0", "]", ")", ")", "for", "arg", "in", "args", "]", ")", "return", "izip", "(", "*", "args", ")" ]
like izip .
train
false
16,470
def _pragma_foreign_keys(connection, on): connection.execute(('PRAGMA foreign_keys=%s' % ('ON' if on else 'OFF')))
[ "def", "_pragma_foreign_keys", "(", "connection", ",", "on", ")", ":", "connection", ".", "execute", "(", "(", "'PRAGMA foreign_keys=%s'", "%", "(", "'ON'", "if", "on", "else", "'OFF'", ")", ")", ")" ]
sets the pragma foreign_keys state of the sqlite database .
train
false
16,471
def hyperfocal_distance(f, N, c): f = sympify(f) N = sympify(N) c = sympify(c) return ((1 / (N * c)) * (f ** 2))
[ "def", "hyperfocal_distance", "(", "f", ",", "N", ",", "c", ")", ":", "f", "=", "sympify", "(", "f", ")", "N", "=", "sympify", "(", "N", ")", "c", "=", "sympify", "(", "c", ")", "return", "(", "(", "1", "/", "(", "N", "*", "c", ")", ")", "*", "(", "f", "**", "2", ")", ")" ]
parameters f: sympifiable focal length of a given lens n: sympifiable f-number of a given lens c: sympifiable circle of confusion of a given image format example .
train
false
16,473
def cycle_colors(chunk, palette=DEFAULT_PALETTE): colors = [] g = itertools.cycle(palette) for i in range(len(chunk)): colors.append(next(g)) return colors
[ "def", "cycle_colors", "(", "chunk", ",", "palette", "=", "DEFAULT_PALETTE", ")", ":", "colors", "=", "[", "]", "g", "=", "itertools", ".", "cycle", "(", "palette", ")", "for", "i", "in", "range", "(", "len", "(", "chunk", ")", ")", ":", "colors", ".", "append", "(", "next", "(", "g", ")", ")", "return", "colors" ]
build a color list just cycling through a given palette .
train
false
16,474
def fetch_snippets_from_dir(path): rv = [] for filename in glob.glob(os.path.join(path, '*.tmSnippet')): print ('Reading file %s' % filename) f = open(filename) content = f.read() cont = parse_content(content) if cont: name = os.path.splitext(os.path.basename(filename))[0] rv.append((name, cont)) return rv
[ "def", "fetch_snippets_from_dir", "(", "path", ")", ":", "rv", "=", "[", "]", "for", "filename", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'*.tmSnippet'", ")", ")", ":", "print", "(", "'Reading file %s'", "%", "filename", ")", "f", "=", "open", "(", "filename", ")", "content", "=", "f", ".", "read", "(", ")", "cont", "=", "parse_content", "(", "content", ")", "if", "cont", ":", "name", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "filename", ")", ")", "[", "0", "]", "rv", ".", "append", "(", "(", "name", ",", "cont", ")", ")", "return", "rv" ]
fetch snippets from a given path .
train
false
16,475
def _oldGiInit(): _glibbase.ensureNotImported(_PYGTK_MODULES, "Introspected and static glib/gtk bindings must not be mixed; can't import gireactor since pygtk2 module is already imported.") global GLib from gi.repository import GLib if (getattr(GLib, 'threads_init', None) is not None): GLib.threads_init() _glibbase.ensureNotImported([], '', preventImports=_PYGTK_MODULES)
[ "def", "_oldGiInit", "(", ")", ":", "_glibbase", ".", "ensureNotImported", "(", "_PYGTK_MODULES", ",", "\"Introspected and static glib/gtk bindings must not be mixed; can't import gireactor since pygtk2 module is already imported.\"", ")", "global", "GLib", "from", "gi", ".", "repository", "import", "GLib", "if", "(", "getattr", "(", "GLib", ",", "'threads_init'", ",", "None", ")", "is", "not", "None", ")", ":", "GLib", ".", "threads_init", "(", ")", "_glibbase", ".", "ensureNotImported", "(", "[", "]", ",", "''", ",", "preventImports", "=", "_PYGTK_MODULES", ")" ]
make sure pygtk and gi arent loaded at the same time .
train
false
16,476
def get_model_name(model): return model._meta.model_name
[ "def", "get_model_name", "(", "model", ")", ":", "return", "model", ".", "_meta", ".", "model_name" ]
returns the name of the model .
train
false
16,477
def parse_CPS_file(lines): chimeras = [] for line in lines: record = line.split() try: id = record[1] parent1 = record[2] parent2 = record[3] verdict = record[10] except IndexError: raise ValueError('Error parsing ChimeraSlayer CPS file.') if (verdict == 'YES'): chimeras.append((id, [parent1, parent2])) return chimeras
[ "def", "parse_CPS_file", "(", "lines", ")", ":", "chimeras", "=", "[", "]", "for", "line", "in", "lines", ":", "record", "=", "line", ".", "split", "(", ")", "try", ":", "id", "=", "record", "[", "1", "]", "parent1", "=", "record", "[", "2", "]", "parent2", "=", "record", "[", "3", "]", "verdict", "=", "record", "[", "10", "]", "except", "IndexError", ":", "raise", "ValueError", "(", "'Error parsing ChimeraSlayer CPS file.'", ")", "if", "(", "verdict", "==", "'YES'", ")", ":", "chimeras", ".", "append", "(", "(", "id", ",", "[", "parent1", ",", "parent2", "]", ")", ")", "return", "chimeras" ]
parse the cps file from chimeraslayer .
train
false
16,478
def mime_to_document_iters(input_file, boundary, read_chunk_size=4096): doc_files = iter_multipart_mime_documents(input_file, boundary, read_chunk_size) for (i, doc_file) in enumerate(doc_files): headers = parse_mime_headers(doc_file) (yield (headers, doc_file))
[ "def", "mime_to_document_iters", "(", "input_file", ",", "boundary", ",", "read_chunk_size", "=", "4096", ")", ":", "doc_files", "=", "iter_multipart_mime_documents", "(", "input_file", ",", "boundary", ",", "read_chunk_size", ")", "for", "(", "i", ",", "doc_file", ")", "in", "enumerate", "(", "doc_files", ")", ":", "headers", "=", "parse_mime_headers", "(", "doc_file", ")", "(", "yield", "(", "headers", ",", "doc_file", ")", ")" ]
takes a file-like object containing a multipart mime document and returns an iterator of tuples .
train
false
16,479
def get_field_data_type(field): return (field.description % field.__dict__)
[ "def", "get_field_data_type", "(", "field", ")", ":", "return", "(", "field", ".", "description", "%", "field", ".", "__dict__", ")" ]
returns the description for a given field type .
train
false
16,480
def flex_loader(alias): if (not alias.startswith('flex.')): return try: if alias.startswith('flex.messaging.messages'): import pyamf.flex.messaging elif alias.startswith('flex.messaging.io'): import pyamf.flex elif alias.startswith('flex.data.messages'): import pyamf.flex.data return CLASS_CACHE[alias] except KeyError: raise UnknownClassAlias(alias)
[ "def", "flex_loader", "(", "alias", ")", ":", "if", "(", "not", "alias", ".", "startswith", "(", "'flex.'", ")", ")", ":", "return", "try", ":", "if", "alias", ".", "startswith", "(", "'flex.messaging.messages'", ")", ":", "import", "pyamf", ".", "flex", ".", "messaging", "elif", "alias", ".", "startswith", "(", "'flex.messaging.io'", ")", ":", "import", "pyamf", ".", "flex", "elif", "alias", ".", "startswith", "(", "'flex.data.messages'", ")", ":", "import", "pyamf", ".", "flex", ".", "data", "return", "CLASS_CACHE", "[", "alias", "]", "except", "KeyError", ":", "raise", "UnknownClassAlias", "(", "alias", ")" ]
loader for l{flex<pyamf .
train
true
16,481
@receiver(models.signals.post_save, sender=CreditCourse) @receiver(models.signals.post_delete, sender=CreditCourse) def invalidate_credit_courses_cache(sender, **kwargs): cache.delete(CreditCourse.CREDIT_COURSES_CACHE_KEY)
[ "@", "receiver", "(", "models", ".", "signals", ".", "post_save", ",", "sender", "=", "CreditCourse", ")", "@", "receiver", "(", "models", ".", "signals", ".", "post_delete", ",", "sender", "=", "CreditCourse", ")", "def", "invalidate_credit_courses_cache", "(", "sender", ",", "**", "kwargs", ")", ":", "cache", ".", "delete", "(", "CreditCourse", ".", "CREDIT_COURSES_CACHE_KEY", ")" ]
invalidate the cache of credit courses .
train
false
16,482
def make_otu_labels(otu_ids, lineages, n_levels=1): if (len(lineages[0]) > 0): otu_labels = [] for (i, lineage) in enumerate(lineages): if (n_levels > len(lineage)): otu_label = ('%s (%s)' % (';'.join(lineage), otu_ids[i])) else: otu_label = ('%s (%s)' % (';'.join(lineage[(- n_levels):]), otu_ids[i])) otu_labels.append(otu_label) otu_labels = [lab.replace('"', '') for lab in otu_labels] else: otu_labels = otu_ids return otu_labels
[ "def", "make_otu_labels", "(", "otu_ids", ",", "lineages", ",", "n_levels", "=", "1", ")", ":", "if", "(", "len", "(", "lineages", "[", "0", "]", ")", ">", "0", ")", ":", "otu_labels", "=", "[", "]", "for", "(", "i", ",", "lineage", ")", "in", "enumerate", "(", "lineages", ")", ":", "if", "(", "n_levels", ">", "len", "(", "lineage", ")", ")", ":", "otu_label", "=", "(", "'%s (%s)'", "%", "(", "';'", ".", "join", "(", "lineage", ")", ",", "otu_ids", "[", "i", "]", ")", ")", "else", ":", "otu_label", "=", "(", "'%s (%s)'", "%", "(", "';'", ".", "join", "(", "lineage", "[", "(", "-", "n_levels", ")", ":", "]", ")", ",", "otu_ids", "[", "i", "]", ")", ")", "otu_labels", ".", "append", "(", "otu_label", ")", "otu_labels", "=", "[", "lab", ".", "replace", "(", "'\"'", ",", "''", ")", "for", "lab", "in", "otu_labels", "]", "else", ":", "otu_labels", "=", "otu_ids", "return", "otu_labels" ]
returns pretty otu labels: lineage substring lineage substring includes the last n_levels lineage levels .
train
false
16,483
def delete_quantum_ports(ports, root_helper): for port in ports: if ip_lib.device_exists(port): device = ip_lib.IPDevice(port, root_helper) device.link.delete() LOG.info(_('Delete %s'), port)
[ "def", "delete_quantum_ports", "(", "ports", ",", "root_helper", ")", ":", "for", "port", "in", "ports", ":", "if", "ip_lib", ".", "device_exists", "(", "port", ")", ":", "device", "=", "ip_lib", ".", "IPDevice", "(", "port", ",", "root_helper", ")", "device", ".", "link", ".", "delete", "(", ")", "LOG", ".", "info", "(", "_", "(", "'Delete %s'", ")", ",", "port", ")" ]
delete non-internal ports created by quantum non-internal ovs ports need to be removed manually .
train
false
16,486
@requires_application() def test_capability(): non_default_vals = dict(title='foo', size=[100, 100], position=[0, 0], show=True, decorate=False, resizable=False, vsync=True) good_kwargs = dict() bad_kwargs = dict() with Canvas() as c: for (key, val) in c.app.backend_module.capability.items(): if (key in non_default_vals): if val: good_kwargs[key] = non_default_vals[key] else: bad_kwargs[key] = non_default_vals[key] with Canvas(**good_kwargs): pass for (key, val) in bad_kwargs.items(): assert_raises(RuntimeError, Canvas, **{key: val})
[ "@", "requires_application", "(", ")", "def", "test_capability", "(", ")", ":", "non_default_vals", "=", "dict", "(", "title", "=", "'foo'", ",", "size", "=", "[", "100", ",", "100", "]", ",", "position", "=", "[", "0", ",", "0", "]", ",", "show", "=", "True", ",", "decorate", "=", "False", ",", "resizable", "=", "False", ",", "vsync", "=", "True", ")", "good_kwargs", "=", "dict", "(", ")", "bad_kwargs", "=", "dict", "(", ")", "with", "Canvas", "(", ")", "as", "c", ":", "for", "(", "key", ",", "val", ")", "in", "c", ".", "app", ".", "backend_module", ".", "capability", ".", "items", "(", ")", ":", "if", "(", "key", "in", "non_default_vals", ")", ":", "if", "val", ":", "good_kwargs", "[", "key", "]", "=", "non_default_vals", "[", "key", "]", "else", ":", "bad_kwargs", "[", "key", "]", "=", "non_default_vals", "[", "key", "]", "with", "Canvas", "(", "**", "good_kwargs", ")", ":", "pass", "for", "(", "key", ",", "val", ")", "in", "bad_kwargs", ".", "items", "(", ")", ":", "assert_raises", "(", "RuntimeError", ",", "Canvas", ",", "**", "{", "key", ":", "val", "}", ")" ]
test application capability enumeration .
train
false
16,487
def service_update(context, service_id, values): return IMPL.service_update(context, service_id, values)
[ "def", "service_update", "(", "context", ",", "service_id", ",", "values", ")", ":", "return", "IMPL", ".", "service_update", "(", "context", ",", "service_id", ",", "values", ")" ]
set the given properties on an service and update it .
train
false
16,488
def is_rel(s): if (len(s) == 0): return True elif (all((isinstance(el, tuple) for el in s)) and (len(max(s)) == len(min(s)))): return True else: raise ValueError((u'Set %r contains sequences of different lengths' % s))
[ "def", "is_rel", "(", "s", ")", ":", "if", "(", "len", "(", "s", ")", "==", "0", ")", ":", "return", "True", "elif", "(", "all", "(", "(", "isinstance", "(", "el", ",", "tuple", ")", "for", "el", "in", "s", ")", ")", "and", "(", "len", "(", "max", "(", "s", ")", ")", "==", "len", "(", "min", "(", "s", ")", ")", ")", ")", ":", "return", "True", "else", ":", "raise", "ValueError", "(", "(", "u'Set %r contains sequences of different lengths'", "%", "s", ")", ")" ]
check whether a set represents a relation .
train
false
16,490
def sameopenfile(fp1, fp2): s1 = os.fstat(fp1) s2 = os.fstat(fp2) return samestat(s1, s2)
[ "def", "sameopenfile", "(", "fp1", ",", "fp2", ")", ":", "s1", "=", "os", ".", "fstat", "(", "fp1", ")", "s2", "=", "os", ".", "fstat", "(", "fp2", ")", "return", "samestat", "(", "s1", ",", "s2", ")" ]
test whether two open file objects reference the same file .
train
false
16,491
def make_decreasing_ohlc(open, high, low, close, dates, **kwargs): (flat_decrease_x, flat_decrease_y, text_decrease) = _OHLC(open, high, low, close, dates).get_decrease() kwargs.setdefault('line', dict(color=_DEFAULT_DECREASING_COLOR, width=1)) kwargs.setdefault('text', text_decrease) kwargs.setdefault('showlegend', False) kwargs.setdefault('name', 'Decreasing') ohlc_decr = dict(type='scatter', x=flat_decrease_x, y=flat_decrease_y, mode='lines', **kwargs) return ohlc_decr
[ "def", "make_decreasing_ohlc", "(", "open", ",", "high", ",", "low", ",", "close", ",", "dates", ",", "**", "kwargs", ")", ":", "(", "flat_decrease_x", ",", "flat_decrease_y", ",", "text_decrease", ")", "=", "_OHLC", "(", "open", ",", "high", ",", "low", ",", "close", ",", "dates", ")", ".", "get_decrease", "(", ")", "kwargs", ".", "setdefault", "(", "'line'", ",", "dict", "(", "color", "=", "_DEFAULT_DECREASING_COLOR", ",", "width", "=", "1", ")", ")", "kwargs", ".", "setdefault", "(", "'text'", ",", "text_decrease", ")", "kwargs", ".", "setdefault", "(", "'showlegend'", ",", "False", ")", "kwargs", ".", "setdefault", "(", "'name'", ",", "'Decreasing'", ")", "ohlc_decr", "=", "dict", "(", "type", "=", "'scatter'", ",", "x", "=", "flat_decrease_x", ",", "y", "=", "flat_decrease_y", ",", "mode", "=", "'lines'", ",", "**", "kwargs", ")", "return", "ohlc_decr" ]
makes decreasing ohlc sticks .
train
false
16,492
def unsubscribe_from_basket_action(newsletter): def unsubscribe_from_basket(modeladmin, request, queryset): 'Unsubscribe from Basket.' ts = [unsubscribe_from_basket_task.subtask(args=[userprofile.user.email, [newsletter]]) for userprofile in queryset] TaskSet(ts).apply_async() messages.success(request, 'Basket update started.') unsubscribe_from_basket.short_description = 'Unsubscribe from {0}'.format(newsletter) func_name = 'unsubscribe_from_basket_{0}'.format(newsletter.replace('-', '_')) unsubscribe_from_basket.__name__ = func_name return unsubscribe_from_basket
[ "def", "unsubscribe_from_basket_action", "(", "newsletter", ")", ":", "def", "unsubscribe_from_basket", "(", "modeladmin", ",", "request", ",", "queryset", ")", ":", "ts", "=", "[", "unsubscribe_from_basket_task", ".", "subtask", "(", "args", "=", "[", "userprofile", ".", "user", ".", "email", ",", "[", "newsletter", "]", "]", ")", "for", "userprofile", "in", "queryset", "]", "TaskSet", "(", "ts", ")", ".", "apply_async", "(", ")", "messages", ".", "success", "(", "request", ",", "'Basket update started.'", ")", "unsubscribe_from_basket", ".", "short_description", "=", "'Unsubscribe from {0}'", ".", "format", "(", "newsletter", ")", "func_name", "=", "'unsubscribe_from_basket_{0}'", ".", "format", "(", "newsletter", ".", "replace", "(", "'-'", ",", "'_'", ")", ")", "unsubscribe_from_basket", ".", "__name__", "=", "func_name", "return", "unsubscribe_from_basket" ]
unsubscribe from basket action .
train
false
16,493
def get_response_stream(response): try: getheader = response.headers.getheader except AttributeError: getheader = response.getheader if (getheader('content-encoding') == 'gzip'): return GzipDecodedResponse(response) return response
[ "def", "get_response_stream", "(", "response", ")", ":", "try", ":", "getheader", "=", "response", ".", "headers", ".", "getheader", "except", "AttributeError", ":", "getheader", "=", "response", ".", "getheader", "if", "(", "getheader", "(", "'content-encoding'", ")", "==", "'gzip'", ")", ":", "return", "GzipDecodedResponse", "(", "response", ")", "return", "response" ]
helper function to return either a gzip reader if content-encoding is gzip otherwise the response itself .
train
false
16,494
def deltaE_ciede94(lab1, lab2, kH=1, kC=1, kL=1, k1=0.045, k2=0.015): (L1, C1) = np.rollaxis(lab2lch(lab1), (-1))[:2] (L2, C2) = np.rollaxis(lab2lch(lab2), (-1))[:2] dL = (L1 - L2) dC = (C1 - C2) dH2 = get_dH2(lab1, lab2) SL = 1 SC = (1 + (k1 * C1)) SH = (1 + (k2 * C1)) dE2 = ((dL / (kL * SL)) ** 2) dE2 += ((dC / (kC * SC)) ** 2) dE2 += (dH2 / ((kH * SH) ** 2)) return np.sqrt(dE2)
[ "def", "deltaE_ciede94", "(", "lab1", ",", "lab2", ",", "kH", "=", "1", ",", "kC", "=", "1", ",", "kL", "=", "1", ",", "k1", "=", "0.045", ",", "k2", "=", "0.015", ")", ":", "(", "L1", ",", "C1", ")", "=", "np", ".", "rollaxis", "(", "lab2lch", "(", "lab1", ")", ",", "(", "-", "1", ")", ")", "[", ":", "2", "]", "(", "L2", ",", "C2", ")", "=", "np", ".", "rollaxis", "(", "lab2lch", "(", "lab2", ")", ",", "(", "-", "1", ")", ")", "[", ":", "2", "]", "dL", "=", "(", "L1", "-", "L2", ")", "dC", "=", "(", "C1", "-", "C2", ")", "dH2", "=", "get_dH2", "(", "lab1", ",", "lab2", ")", "SL", "=", "1", "SC", "=", "(", "1", "+", "(", "k1", "*", "C1", ")", ")", "SH", "=", "(", "1", "+", "(", "k2", "*", "C1", ")", ")", "dE2", "=", "(", "(", "dL", "/", "(", "kL", "*", "SL", ")", ")", "**", "2", ")", "dE2", "+=", "(", "(", "dC", "/", "(", "kC", "*", "SC", ")", ")", "**", "2", ")", "dE2", "+=", "(", "dH2", "/", "(", "(", "kH", "*", "SH", ")", "**", "2", ")", ")", "return", "np", ".", "sqrt", "(", "dE2", ")" ]
color difference according to ciede 94 standard accommodates perceptual non-uniformities through the use of application specific scale factors .
train
false
16,496
def create_access_port(network_switch, port_name, vlan): debug = False new_port = SwitchPort.objects.get_or_create(port_name=port_name, mode='access', access_vlan=vlan, network_switch=network_switch) if debug: print new_port
[ "def", "create_access_port", "(", "network_switch", ",", "port_name", ",", "vlan", ")", ":", "debug", "=", "False", "new_port", "=", "SwitchPort", ".", "objects", ".", "get_or_create", "(", "port_name", "=", "port_name", ",", "mode", "=", "'access'", ",", "access_vlan", "=", "vlan", ",", "network_switch", "=", "network_switch", ")", "if", "debug", ":", "print", "new_port" ]
create a switchport object - access port .
train
false
16,497
def run_scripts(package_location, scripts): path = os.path.join(package_location, 'scripts/') cwd = os.getcwd() os.chdir(path) for script in scripts: if os.path.exists(script): try: subprocess.check_call(script, stdout=sys.stdout, stderr=sys.stderr) except Exception: os.chdir(cwd) raise os.chdir(cwd)
[ "def", "run_scripts", "(", "package_location", ",", "scripts", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "package_location", ",", "'scripts/'", ")", "cwd", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "path", ")", "for", "script", "in", "scripts", ":", "if", "os", ".", "path", ".", "exists", "(", "script", ")", ":", "try", ":", "subprocess", ".", "check_call", "(", "script", ",", "stdout", "=", "sys", ".", "stdout", ",", "stderr", "=", "sys", ".", "stderr", ")", "except", "Exception", ":", "os", ".", "chdir", "(", "cwd", ")", "raise", "os", ".", "chdir", "(", "cwd", ")" ]
search for installation scripts speficied by the scripts list .
train
false
16,498
def delete_branch(pr, session): refs_url = pr['head']['repo']['git_refs_url'] branch_url = refs_url.replace('{/sha}', ('/heads/' + pr['head']['ref'])) return session.delete(branch_url)
[ "def", "delete_branch", "(", "pr", ",", "session", ")", ":", "refs_url", "=", "pr", "[", "'head'", "]", "[", "'repo'", "]", "[", "'git_refs_url'", "]", "branch_url", "=", "refs_url", ".", "replace", "(", "'{/sha}'", ",", "(", "'/heads/'", "+", "pr", "[", "'head'", "]", "[", "'ref'", "]", ")", ")", "return", "session", ".", "delete", "(", "branch_url", ")" ]
launch the delete branch dialog .
train
false
16,500
def find_hessian(point, vars=None, model=None): model = modelcontext(model) H = model.fastd2logp(vars) return H(Point(point, model=model))
[ "def", "find_hessian", "(", "point", ",", "vars", "=", "None", ",", "model", "=", "None", ")", ":", "model", "=", "modelcontext", "(", "model", ")", "H", "=", "model", ".", "fastd2logp", "(", "vars", ")", "return", "H", "(", "Point", "(", "point", ",", "model", "=", "model", ")", ")" ]
returns hessian of logp at the point passed .
train
false
16,501
def project_activity_postprocess(form): form_vars = form.vars project_id = form_vars.get('project_id', None) if project_id: s3db = current.s3db db = current.db activity_id = form_vars.get('id', None) ltable = s3db.project_activity_organisation org = db((ltable.activity_id == activity_id)).select(ltable.organisation_id, limitby=(0, 1)).first() if org: return ptable = s3db.project_project project = db((ptable.id == project_id)).select(ptable.organisation_id, limitby=(0, 1)).first() try: organisation_id = project.organisation_id except: return ltable.insert(activity_id=activity_id, organisation_id=organisation_id)
[ "def", "project_activity_postprocess", "(", "form", ")", ":", "form_vars", "=", "form", ".", "vars", "project_id", "=", "form_vars", ".", "get", "(", "'project_id'", ",", "None", ")", "if", "project_id", ":", "s3db", "=", "current", ".", "s3db", "db", "=", "current", ".", "db", "activity_id", "=", "form_vars", ".", "get", "(", "'id'", ",", "None", ")", "ltable", "=", "s3db", ".", "project_activity_organisation", "org", "=", "db", "(", "(", "ltable", ".", "activity_id", "==", "activity_id", ")", ")", ".", "select", "(", "ltable", ".", "organisation_id", ",", "limitby", "=", "(", "0", ",", "1", ")", ")", ".", "first", "(", ")", "if", "org", ":", "return", "ptable", "=", "s3db", ".", "project_project", "project", "=", "db", "(", "(", "ptable", ".", "id", "==", "project_id", ")", ")", ".", "select", "(", "ptable", ".", "organisation_id", ",", "limitby", "=", "(", "0", ",", "1", ")", ")", ".", "first", "(", ")", "try", ":", "organisation_id", "=", "project", ".", "organisation_id", "except", ":", "return", "ltable", ".", "insert", "(", "activity_id", "=", "activity_id", ",", "organisation_id", "=", "organisation_id", ")" ]
default the activitys organisation to that of the project .
train
false
16,502
@given(u'a new working directory') def step_a_new_working_directory(context): command_util.ensure_context_attribute_exists(context, 'workdir', None) command_util.ensure_workdir_exists(context) shutil.rmtree(context.workdir, ignore_errors=True) command_util.ensure_workdir_exists(context)
[ "@", "given", "(", "u'a new working directory'", ")", "def", "step_a_new_working_directory", "(", "context", ")", ":", "command_util", ".", "ensure_context_attribute_exists", "(", "context", ",", "'workdir'", ",", "None", ")", "command_util", ".", "ensure_workdir_exists", "(", "context", ")", "shutil", ".", "rmtree", "(", "context", ".", "workdir", ",", "ignore_errors", "=", "True", ")", "command_util", ".", "ensure_workdir_exists", "(", "context", ")" ]
creates a new .
train
true
16,503
def copy_file_from_manifest(repo, ctx, filename, dir): for changeset in reversed_upper_bounded_changelog(repo, ctx): changeset_ctx = repo.changectx(changeset) fctx = get_file_context_from_ctx(changeset_ctx, filename) if (fctx and (fctx not in ['DELETED'])): file_path = os.path.join(dir, filename) fh = open(file_path, 'wb') fh.write(fctx.data()) fh.close() return file_path return None
[ "def", "copy_file_from_manifest", "(", "repo", ",", "ctx", ",", "filename", ",", "dir", ")", ":", "for", "changeset", "in", "reversed_upper_bounded_changelog", "(", "repo", ",", "ctx", ")", ":", "changeset_ctx", "=", "repo", ".", "changectx", "(", "changeset", ")", "fctx", "=", "get_file_context_from_ctx", "(", "changeset_ctx", ",", "filename", ")", "if", "(", "fctx", "and", "(", "fctx", "not", "in", "[", "'DELETED'", "]", ")", ")", ":", "file_path", "=", "os", ".", "path", ".", "join", "(", "dir", ",", "filename", ")", "fh", "=", "open", "(", "file_path", ",", "'wb'", ")", "fh", ".", "write", "(", "fctx", ".", "data", "(", ")", ")", "fh", ".", "close", "(", ")", "return", "file_path", "return", "None" ]
copy the latest version of the file named filename from the repository manifest to the directory to which dir refers .
train
false
16,504
def deeper2net_conv2d(teacher_w): (nb_filter, nb_channel, kh, kw) = teacher_w.shape student_w = np.zeros((nb_filter, nb_filter, kh, kw)) for i in xrange(nb_filter): student_w[(i, i, ((kh - 1) / 2), ((kw - 1) / 2))] = 1.0 student_b = np.zeros(nb_filter) return (student_w, student_b)
[ "def", "deeper2net_conv2d", "(", "teacher_w", ")", ":", "(", "nb_filter", ",", "nb_channel", ",", "kh", ",", "kw", ")", "=", "teacher_w", ".", "shape", "student_w", "=", "np", ".", "zeros", "(", "(", "nb_filter", ",", "nb_filter", ",", "kh", ",", "kw", ")", ")", "for", "i", "in", "xrange", "(", "nb_filter", ")", ":", "student_w", "[", "(", "i", ",", "i", ",", "(", "(", "kh", "-", "1", ")", "/", "2", ")", ",", "(", "(", "kw", "-", "1", ")", "/", "2", ")", ")", "]", "=", "1.0", "student_b", "=", "np", ".", "zeros", "(", "nb_filter", ")", "return", "(", "student_w", ",", "student_b", ")" ]
get initial weights for a deeper conv2d layer by net2deeper .
train
false
16,505
def get_alembic_version(meta): try: a_ver = sa.Table('alembic_version', meta, autoload=True) return sa.select([a_ver.c.version_num]).scalar() except sa.exc.NoSuchTableError: return None
[ "def", "get_alembic_version", "(", "meta", ")", ":", "try", ":", "a_ver", "=", "sa", ".", "Table", "(", "'alembic_version'", ",", "meta", ",", "autoload", "=", "True", ")", "return", "sa", ".", "select", "(", "[", "a_ver", ".", "c", ".", "version_num", "]", ")", ".", "scalar", "(", ")", "except", "sa", ".", "exc", ".", "NoSuchTableError", ":", "return", "None" ]
return alembic version or none if no alembic table exists .
train
false
16,506
def _parse_global_variables(user_cidr, inventory, user_defined_config): if ('all' not in inventory): inventory['all'] = {} if ('vars' not in inventory['all']): inventory['all']['vars'] = {} inventory['all']['vars']['container_cidr'] = user_cidr if ('global_overrides' in user_defined_config): if isinstance(user_defined_config['global_overrides'], dict): inventory['all']['vars'].update(user_defined_config['global_overrides']) logger.debug('Applied global_overrides') kept_vars = user_defined_config['global_overrides'].keys() kept_vars.append('container_cidr') for key in inventory['all']['vars'].keys(): if (key not in kept_vars): logger.debug('Deleting key %s from inventory', key) del inventory['all']['vars'][key]
[ "def", "_parse_global_variables", "(", "user_cidr", ",", "inventory", ",", "user_defined_config", ")", ":", "if", "(", "'all'", "not", "in", "inventory", ")", ":", "inventory", "[", "'all'", "]", "=", "{", "}", "if", "(", "'vars'", "not", "in", "inventory", "[", "'all'", "]", ")", ":", "inventory", "[", "'all'", "]", "[", "'vars'", "]", "=", "{", "}", "inventory", "[", "'all'", "]", "[", "'vars'", "]", "[", "'container_cidr'", "]", "=", "user_cidr", "if", "(", "'global_overrides'", "in", "user_defined_config", ")", ":", "if", "isinstance", "(", "user_defined_config", "[", "'global_overrides'", "]", ",", "dict", ")", ":", "inventory", "[", "'all'", "]", "[", "'vars'", "]", ".", "update", "(", "user_defined_config", "[", "'global_overrides'", "]", ")", "logger", ".", "debug", "(", "'Applied global_overrides'", ")", "kept_vars", "=", "user_defined_config", "[", "'global_overrides'", "]", ".", "keys", "(", ")", "kept_vars", ".", "append", "(", "'container_cidr'", ")", "for", "key", "in", "inventory", "[", "'all'", "]", "[", "'vars'", "]", ".", "keys", "(", ")", ":", "if", "(", "key", "not", "in", "kept_vars", ")", ":", "logger", ".", "debug", "(", "'Deleting key %s from inventory'", ",", "key", ")", "del", "inventory", "[", "'all'", "]", "[", "'vars'", "]", "[", "key", "]" ]
add any extra variables that may have been set in config .
train
false
16,507
def topic_rule_exists(ruleName, region=None, key=None, keyid=None, profile=None): try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) rule = conn.get_topic_rule(ruleName=ruleName) return {'exists': True} except ClientError as e: err = salt.utils.boto3.get_error(e) if (e.response.get('Error', {}).get('Code') == 'UnauthorizedException'): return {'exists': False} return {'error': salt.utils.boto3.get_error(e)}
[ "def", "topic_rule_exists", "(", "ruleName", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "rule", "=", "conn", ".", "get_topic_rule", "(", "ruleName", "=", "ruleName", ")", "return", "{", "'exists'", ":", "True", "}", "except", "ClientError", "as", "e", ":", "err", "=", "salt", ".", "utils", ".", "boto3", ".", "get_error", "(", "e", ")", "if", "(", "e", ".", "response", ".", "get", "(", "'Error'", ",", "{", "}", ")", ".", "get", "(", "'Code'", ")", "==", "'UnauthorizedException'", ")", ":", "return", "{", "'exists'", ":", "False", "}", "return", "{", "'error'", ":", "salt", ".", "utils", ".", "boto3", ".", "get_error", "(", "e", ")", "}" ]
given a rule name .
train
false
16,508
def bind_floating_ip(floating_ip, device): _execute('ip', 'addr', 'add', (str(floating_ip) + '/32'), 'dev', device, run_as_root=True, check_exit_code=[0, 2, 254]) if (CONF.send_arp_for_ha and (CONF.send_arp_for_ha_count > 0)): send_arp_for_ip(floating_ip, device, CONF.send_arp_for_ha_count)
[ "def", "bind_floating_ip", "(", "floating_ip", ",", "device", ")", ":", "_execute", "(", "'ip'", ",", "'addr'", ",", "'add'", ",", "(", "str", "(", "floating_ip", ")", "+", "'/32'", ")", ",", "'dev'", ",", "device", ",", "run_as_root", "=", "True", ",", "check_exit_code", "=", "[", "0", ",", "2", ",", "254", "]", ")", "if", "(", "CONF", ".", "send_arp_for_ha", "and", "(", "CONF", ".", "send_arp_for_ha_count", ">", "0", ")", ")", ":", "send_arp_for_ip", "(", "floating_ip", ",", "device", ",", "CONF", ".", "send_arp_for_ha_count", ")" ]
bind ip to public interface .
train
false
16,509
def splrep(x, y, w=None, xb=None, xe=None, k=3, task=0, s=None, t=None, full_output=0, per=0, quiet=1): if (task <= 0): _curfit_cache = {} (x, y) = map(atleast_1d, [x, y]) m = len(x) if (w is None): w = ones(m, float) if (s is None): s = 0.0 else: w = atleast_1d(w) if (s is None): s = (m - sqrt((2 * m))) if (not (len(w) == m)): raise TypeError(('len(w)=%d is not equal to m=%d' % (len(w), m))) if ((m != len(y)) or (m != len(w))): raise TypeError('Lengths of the first three arguments (x,y,w) must be equal') if (not (1 <= k <= 5)): raise TypeError(('Given degree of the spline (k=%d) is not supported. (1<=k<=5)' % k)) if (m <= k): raise TypeError('m > k must hold') if (xb is None): xb = x[0] if (xe is None): xe = x[(-1)] if (not ((-1) <= task <= 1)): raise TypeError('task must be -1, 0 or 1') if (t is not None): task = (-1) if (task == (-1)): if (t is None): raise TypeError('Knots must be given for task=-1') numknots = len(t) _curfit_cache['t'] = empty((((numknots + (2 * k)) + 2),), float) _curfit_cache['t'][(k + 1):((- k) - 1)] = t nest = len(_curfit_cache['t']) elif (task == 0): if per: nest = max((m + (2 * k)), ((2 * k) + 3)) else: nest = max(((m + k) + 1), ((2 * k) + 3)) t = empty((nest,), float) _curfit_cache['t'] = t if (task <= 0): if per: _curfit_cache['wrk'] = empty((((m * (k + 1)) + (nest * (8 + (5 * k)))),), float) else: _curfit_cache['wrk'] = empty((((m * (k + 1)) + (nest * (7 + (3 * k)))),), float) _curfit_cache['iwrk'] = empty((nest,), intc) try: t = _curfit_cache['t'] wrk = _curfit_cache['wrk'] iwrk = _curfit_cache['iwrk'] except KeyError: raise TypeError('must call with task=1 only after call with task=0,-1') if (not per): (n, c, fp, ier) = dfitpack.curfit(task, x, y, w, t, wrk, iwrk, xb, xe, k, s) else: (n, c, fp, ier) = dfitpack.percur(task, x, y, w, t, wrk, iwrk, k, s) tck = (t[:n], c[:n], k) if ((ier <= 0) and (not quiet)): _mess = (_iermess[ier][0] + (' DCTB k=%d n=%d m=%d fp=%f s=%f' % (k, len(t), m, fp, s))) warnings.warn(RuntimeWarning(_mess)) if ((ier > 0) and (not full_output)): if (ier in [1, 2, 3]): warnings.warn(RuntimeWarning(_iermess[ier][0])) else: try: raise _iermess[ier][1](_iermess[ier][0]) except KeyError: raise _iermess['unknown'][1](_iermess['unknown'][0]) if full_output: try: return (tck, fp, ier, _iermess[ier][0]) except KeyError: return (tck, fp, ier, _iermess['unknown'][0]) else: return tck
[ "def", "splrep", "(", "x", ",", "y", ",", "w", "=", "None", ",", "xb", "=", "None", ",", "xe", "=", "None", ",", "k", "=", "3", ",", "task", "=", "0", ",", "s", "=", "None", ",", "t", "=", "None", ",", "full_output", "=", "0", ",", "per", "=", "0", ",", "quiet", "=", "1", ")", ":", "if", "(", "task", "<=", "0", ")", ":", "_curfit_cache", "=", "{", "}", "(", "x", ",", "y", ")", "=", "map", "(", "atleast_1d", ",", "[", "x", ",", "y", "]", ")", "m", "=", "len", "(", "x", ")", "if", "(", "w", "is", "None", ")", ":", "w", "=", "ones", "(", "m", ",", "float", ")", "if", "(", "s", "is", "None", ")", ":", "s", "=", "0.0", "else", ":", "w", "=", "atleast_1d", "(", "w", ")", "if", "(", "s", "is", "None", ")", ":", "s", "=", "(", "m", "-", "sqrt", "(", "(", "2", "*", "m", ")", ")", ")", "if", "(", "not", "(", "len", "(", "w", ")", "==", "m", ")", ")", ":", "raise", "TypeError", "(", "(", "'len(w)=%d is not equal to m=%d'", "%", "(", "len", "(", "w", ")", ",", "m", ")", ")", ")", "if", "(", "(", "m", "!=", "len", "(", "y", ")", ")", "or", "(", "m", "!=", "len", "(", "w", ")", ")", ")", ":", "raise", "TypeError", "(", "'Lengths of the first three arguments (x,y,w) must be equal'", ")", "if", "(", "not", "(", "1", "<=", "k", "<=", "5", ")", ")", ":", "raise", "TypeError", "(", "(", "'Given degree of the spline (k=%d) is not supported. (1<=k<=5)'", "%", "k", ")", ")", "if", "(", "m", "<=", "k", ")", ":", "raise", "TypeError", "(", "'m > k must hold'", ")", "if", "(", "xb", "is", "None", ")", ":", "xb", "=", "x", "[", "0", "]", "if", "(", "xe", "is", "None", ")", ":", "xe", "=", "x", "[", "(", "-", "1", ")", "]", "if", "(", "not", "(", "(", "-", "1", ")", "<=", "task", "<=", "1", ")", ")", ":", "raise", "TypeError", "(", "'task must be -1, 0 or 1'", ")", "if", "(", "t", "is", "not", "None", ")", ":", "task", "=", "(", "-", "1", ")", "if", "(", "task", "==", "(", "-", "1", ")", ")", ":", "if", "(", "t", "is", "None", ")", ":", "raise", "TypeError", "(", "'Knots must be given for task=-1'", ")", "numknots", "=", "len", "(", "t", ")", "_curfit_cache", "[", "'t'", "]", "=", "empty", "(", "(", "(", "(", "numknots", "+", "(", "2", "*", "k", ")", ")", "+", "2", ")", ",", ")", ",", "float", ")", "_curfit_cache", "[", "'t'", "]", "[", "(", "k", "+", "1", ")", ":", "(", "(", "-", "k", ")", "-", "1", ")", "]", "=", "t", "nest", "=", "len", "(", "_curfit_cache", "[", "'t'", "]", ")", "elif", "(", "task", "==", "0", ")", ":", "if", "per", ":", "nest", "=", "max", "(", "(", "m", "+", "(", "2", "*", "k", ")", ")", ",", "(", "(", "2", "*", "k", ")", "+", "3", ")", ")", "else", ":", "nest", "=", "max", "(", "(", "(", "m", "+", "k", ")", "+", "1", ")", ",", "(", "(", "2", "*", "k", ")", "+", "3", ")", ")", "t", "=", "empty", "(", "(", "nest", ",", ")", ",", "float", ")", "_curfit_cache", "[", "'t'", "]", "=", "t", "if", "(", "task", "<=", "0", ")", ":", "if", "per", ":", "_curfit_cache", "[", "'wrk'", "]", "=", "empty", "(", "(", "(", "(", "m", "*", "(", "k", "+", "1", ")", ")", "+", "(", "nest", "*", "(", "8", "+", "(", "5", "*", "k", ")", ")", ")", ")", ",", ")", ",", "float", ")", "else", ":", "_curfit_cache", "[", "'wrk'", "]", "=", "empty", "(", "(", "(", "(", "m", "*", "(", "k", "+", "1", ")", ")", "+", "(", "nest", "*", "(", "7", "+", "(", "3", "*", "k", ")", ")", ")", ")", ",", ")", ",", "float", ")", "_curfit_cache", "[", "'iwrk'", "]", "=", "empty", "(", "(", "nest", ",", ")", ",", "intc", ")", "try", ":", "t", "=", "_curfit_cache", "[", "'t'", "]", "wrk", "=", "_curfit_cache", "[", "'wrk'", "]", "iwrk", "=", "_curfit_cache", "[", "'iwrk'", "]", "except", "KeyError", ":", "raise", "TypeError", "(", "'must call with task=1 only after call with task=0,-1'", ")", "if", "(", "not", "per", ")", ":", "(", "n", ",", "c", ",", "fp", ",", "ier", ")", "=", "dfitpack", ".", "curfit", "(", "task", ",", "x", ",", "y", ",", "w", ",", "t", ",", "wrk", ",", "iwrk", ",", "xb", ",", "xe", ",", "k", ",", "s", ")", "else", ":", "(", "n", ",", "c", ",", "fp", ",", "ier", ")", "=", "dfitpack", ".", "percur", "(", "task", ",", "x", ",", "y", ",", "w", ",", "t", ",", "wrk", ",", "iwrk", ",", "k", ",", "s", ")", "tck", "=", "(", "t", "[", ":", "n", "]", ",", "c", "[", ":", "n", "]", ",", "k", ")", "if", "(", "(", "ier", "<=", "0", ")", "and", "(", "not", "quiet", ")", ")", ":", "_mess", "=", "(", "_iermess", "[", "ier", "]", "[", "0", "]", "+", "(", "' DCTB k=%d n=%d m=%d fp=%f s=%f'", "%", "(", "k", ",", "len", "(", "t", ")", ",", "m", ",", "fp", ",", "s", ")", ")", ")", "warnings", ".", "warn", "(", "RuntimeWarning", "(", "_mess", ")", ")", "if", "(", "(", "ier", ">", "0", ")", "and", "(", "not", "full_output", ")", ")", ":", "if", "(", "ier", "in", "[", "1", ",", "2", ",", "3", "]", ")", ":", "warnings", ".", "warn", "(", "RuntimeWarning", "(", "_iermess", "[", "ier", "]", "[", "0", "]", ")", ")", "else", ":", "try", ":", "raise", "_iermess", "[", "ier", "]", "[", "1", "]", "(", "_iermess", "[", "ier", "]", "[", "0", "]", ")", "except", "KeyError", ":", "raise", "_iermess", "[", "'unknown'", "]", "[", "1", "]", "(", "_iermess", "[", "'unknown'", "]", "[", "0", "]", ")", "if", "full_output", ":", "try", ":", "return", "(", "tck", ",", "fp", ",", "ier", ",", "_iermess", "[", "ier", "]", "[", "0", "]", ")", "except", "KeyError", ":", "return", "(", "tck", ",", "fp", ",", "ier", ",", "_iermess", "[", "'unknown'", "]", "[", "0", "]", ")", "else", ":", "return", "tck" ]
find the b-spline representation of 1-d curve .
train
false
16,510
def getAbridgedSettings(gcodeText): abridgedSettings = [] lines = archive.getTextLines(gcodeText) settingsStart = False for line in lines: splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) firstWord = gcodec.getFirstWord(splitLine) if ((firstWord == '(<setting>') and settingsStart): if (len(splitLine) > 4): abridgedSettings.append(AbridgedSetting(splitLine)) elif (firstWord == '(<settings>)'): settingsStart = True elif (firstWord == '(</settings>)'): return abridgedSettings return []
[ "def", "getAbridgedSettings", "(", "gcodeText", ")", ":", "abridgedSettings", "=", "[", "]", "lines", "=", "archive", ".", "getTextLines", "(", "gcodeText", ")", "settingsStart", "=", "False", "for", "line", "in", "lines", ":", "splitLine", "=", "gcodec", ".", "getSplitLineBeforeBracketSemicolon", "(", "line", ")", "firstWord", "=", "gcodec", ".", "getFirstWord", "(", "splitLine", ")", "if", "(", "(", "firstWord", "==", "'(<setting>'", ")", "and", "settingsStart", ")", ":", "if", "(", "len", "(", "splitLine", ")", ">", "4", ")", ":", "abridgedSettings", ".", "append", "(", "AbridgedSetting", "(", "splitLine", ")", ")", "elif", "(", "firstWord", "==", "'(<settings>)'", ")", ":", "settingsStart", "=", "True", "elif", "(", "firstWord", "==", "'(</settings>)'", ")", ":", "return", "abridgedSettings", "return", "[", "]" ]
get the abridged settings from the gcode text .
train
false
16,511
def tag_string_convert(key, data, errors, context): if isinstance(data[key], basestring): tags = [tag.strip() for tag in data[key].split(',') if tag.strip()] else: tags = data[key] current_index = max(([int(k[1]) for k in data.keys() if ((len(k) == 3) and (k[0] == 'tags'))] + [(-1)])) for (num, tag) in zip(count((current_index + 1)), tags): data[('tags', num, 'name')] = tag for tag in tags: tag_length_validator(tag, context) tag_name_validator(tag, context)
[ "def", "tag_string_convert", "(", "key", ",", "data", ",", "errors", ",", "context", ")", ":", "if", "isinstance", "(", "data", "[", "key", "]", ",", "basestring", ")", ":", "tags", "=", "[", "tag", ".", "strip", "(", ")", "for", "tag", "in", "data", "[", "key", "]", ".", "split", "(", "','", ")", "if", "tag", ".", "strip", "(", ")", "]", "else", ":", "tags", "=", "data", "[", "key", "]", "current_index", "=", "max", "(", "(", "[", "int", "(", "k", "[", "1", "]", ")", "for", "k", "in", "data", ".", "keys", "(", ")", "if", "(", "(", "len", "(", "k", ")", "==", "3", ")", "and", "(", "k", "[", "0", "]", "==", "'tags'", ")", ")", "]", "+", "[", "(", "-", "1", ")", "]", ")", ")", "for", "(", "num", ",", "tag", ")", "in", "zip", "(", "count", "(", "(", "current_index", "+", "1", ")", ")", ",", "tags", ")", ":", "data", "[", "(", "'tags'", ",", "num", ",", "'name'", ")", "]", "=", "tag", "for", "tag", "in", "tags", ":", "tag_length_validator", "(", "tag", ",", "context", ")", "tag_name_validator", "(", "tag", ",", "context", ")" ]
takes a list of tags that is a comma-separated string and parses tag names .
train
false
16,512
def list_cidr_ips_ipv6(cidr): ips = netaddr.IPNetwork(cidr) return [str(ip.ipv6()) for ip in list(ips)]
[ "def", "list_cidr_ips_ipv6", "(", "cidr", ")", ":", "ips", "=", "netaddr", ".", "IPNetwork", "(", "cidr", ")", "return", "[", "str", "(", "ip", ".", "ipv6", "(", ")", ")", "for", "ip", "in", "list", "(", "ips", ")", "]" ]
get a list of ipv6 addresses from a cidr .
train
false
16,515
def _render_configuration(): text_repr = _current_statement.build() _INDENT = '' return text_repr
[ "def", "_render_configuration", "(", ")", ":", "text_repr", "=", "_current_statement", ".", "build", "(", ")", "_INDENT", "=", "''", "return", "text_repr" ]
renders the configuration tree into syslog-ngs configuration syntax .
train
false
16,516
def get_secret(): return file_io.read(constants.SECRET_LOC).rstrip()
[ "def", "get_secret", "(", ")", ":", "return", "file_io", ".", "read", "(", "constants", ".", "SECRET_LOC", ")", ".", "rstrip", "(", ")" ]
reads a secret key string from the specified file and returns it .
train
false
16,517
@cwd_at('test/test_evaluate/not_in_sys_path/pkg') def test_import_not_in_sys_path(): a = jedi.Script(path='module.py', line=5).goto_definitions() assert (a[0].name == 'int') a = jedi.Script(path='module.py', line=6).goto_definitions() assert (a[0].name == 'str') a = jedi.Script(path='module.py', line=7).goto_definitions() assert (a[0].name == 'str')
[ "@", "cwd_at", "(", "'test/test_evaluate/not_in_sys_path/pkg'", ")", "def", "test_import_not_in_sys_path", "(", ")", ":", "a", "=", "jedi", ".", "Script", "(", "path", "=", "'module.py'", ",", "line", "=", "5", ")", ".", "goto_definitions", "(", ")", "assert", "(", "a", "[", "0", "]", ".", "name", "==", "'int'", ")", "a", "=", "jedi", ".", "Script", "(", "path", "=", "'module.py'", ",", "line", "=", "6", ")", ".", "goto_definitions", "(", ")", "assert", "(", "a", "[", "0", "]", ".", "name", "==", "'str'", ")", "a", "=", "jedi", ".", "Script", "(", "path", "=", "'module.py'", ",", "line", "=", "7", ")", ".", "goto_definitions", "(", ")", "assert", "(", "a", "[", "0", "]", ".", "name", "==", "'str'", ")" ]
non-direct imports .
train
false
16,520
def publish_msgstr(app, source, source_path, source_line, config, settings): from sphinx.io import SphinxI18nReader reader = SphinxI18nReader(app=app, parsers=config.source_parsers, parser_name='restructuredtext') reader.set_lineno_for_reporter(source_line) doc = reader.read(source=StringInput(source=source, source_path=source_path), parser=reader.parser, settings=settings) try: doc = doc[0] except IndexError: pass return doc
[ "def", "publish_msgstr", "(", "app", ",", "source", ",", "source_path", ",", "source_line", ",", "config", ",", "settings", ")", ":", "from", "sphinx", ".", "io", "import", "SphinxI18nReader", "reader", "=", "SphinxI18nReader", "(", "app", "=", "app", ",", "parsers", "=", "config", ".", "source_parsers", ",", "parser_name", "=", "'restructuredtext'", ")", "reader", ".", "set_lineno_for_reporter", "(", "source_line", ")", "doc", "=", "reader", ".", "read", "(", "source", "=", "StringInput", "(", "source", "=", "source", ",", "source_path", "=", "source_path", ")", ",", "parser", "=", "reader", ".", "parser", ",", "settings", "=", "settings", ")", "try", ":", "doc", "=", "doc", "[", "0", "]", "except", "IndexError", ":", "pass", "return", "doc" ]
publish msgstr into docutils document .
train
false
16,521
def ensure_bytes(s): if isinstance(s, bytes): return s if hasattr(s, 'encode'): return s.encode() msg = 'Object %s is neither a bytes object nor has an encode method' raise TypeError((msg % s))
[ "def", "ensure_bytes", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "bytes", ")", ":", "return", "s", "if", "hasattr", "(", "s", ",", "'encode'", ")", ":", "return", "s", ".", "encode", "(", ")", "msg", "=", "'Object %s is neither a bytes object nor has an encode method'", "raise", "TypeError", "(", "(", "msg", "%", "s", ")", ")" ]
turn string or bytes to bytes .
train
false
16,525
def b1282int(st): e = 1 i = 0 for char in iterbytes(st): n = ord(char) i += (n * e) e <<= 7 return i
[ "def", "b1282int", "(", "st", ")", ":", "e", "=", "1", "i", "=", "0", "for", "char", "in", "iterbytes", "(", "st", ")", ":", "n", "=", "ord", "(", "char", ")", "i", "+=", "(", "n", "*", "e", ")", "e", "<<=", "7", "return", "i" ]
convert an integer represented as a base 128 string into an c{int} or c{long} .
train
false
16,526
@profiler.trace def server_console_output(request, instance_id, tail_length=None): return novaclient(request).servers.get_console_output(instance_id, length=tail_length)
[ "@", "profiler", ".", "trace", "def", "server_console_output", "(", "request", ",", "instance_id", ",", "tail_length", "=", "None", ")", ":", "return", "novaclient", "(", "request", ")", ".", "servers", ".", "get_console_output", "(", "instance_id", ",", "length", "=", "tail_length", ")" ]
gets console output of an instance .
train
false
16,527
def user_config_dir(appname, roaming=True): if WINDOWS: path = user_data_dir(appname, roaming=roaming) elif (sys.platform == 'darwin'): path = user_data_dir(appname) else: path = os.getenv('XDG_CONFIG_HOME', expanduser('~/.config')) path = os.path.join(path, appname) return path
[ "def", "user_config_dir", "(", "appname", ",", "roaming", "=", "True", ")", ":", "if", "WINDOWS", ":", "path", "=", "user_data_dir", "(", "appname", ",", "roaming", "=", "roaming", ")", "elif", "(", "sys", ".", "platform", "==", "'darwin'", ")", ":", "path", "=", "user_data_dir", "(", "appname", ")", "else", ":", "path", "=", "os", ".", "getenv", "(", "'XDG_CONFIG_HOME'", ",", "expanduser", "(", "'~/.config'", ")", ")", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "appname", ")", "return", "path" ]
return full path to the user-specific config dir for this application .
train
true
16,531
def _serialize_inventories(inventories, generation): inventories_by_class = {inventory.resource_class: inventory for inventory in inventories} inventories_dict = {} for (resource_class, inventory) in inventories_by_class.items(): inventories_dict[resource_class] = _serialize_inventory(inventory, generation=None) return {'resource_provider_generation': generation, 'inventories': inventories_dict}
[ "def", "_serialize_inventories", "(", "inventories", ",", "generation", ")", ":", "inventories_by_class", "=", "{", "inventory", ".", "resource_class", ":", "inventory", "for", "inventory", "in", "inventories", "}", "inventories_dict", "=", "{", "}", "for", "(", "resource_class", ",", "inventory", ")", "in", "inventories_by_class", ".", "items", "(", ")", ":", "inventories_dict", "[", "resource_class", "]", "=", "_serialize_inventory", "(", "inventory", ",", "generation", "=", "None", ")", "return", "{", "'resource_provider_generation'", ":", "generation", ",", "'inventories'", ":", "inventories_dict", "}" ]
turn a list of inventories in a dict by resource class .
train
false
16,532
def render_to_response(renderer_name, value, request=None, package=None, response=None): try: registry = request.registry except AttributeError: registry = None if (package is None): package = caller_package() helper = RendererHelper(name=renderer_name, package=package, registry=registry) with hide_attrs(request, 'response'): if (response is not None): request.response = response result = helper.render_to_response(value, None, request=request) return result
[ "def", "render_to_response", "(", "renderer_name", ",", "value", ",", "request", "=", "None", ",", "package", "=", "None", ",", "response", "=", "None", ")", ":", "try", ":", "registry", "=", "request", ".", "registry", "except", "AttributeError", ":", "registry", "=", "None", "if", "(", "package", "is", "None", ")", ":", "package", "=", "caller_package", "(", ")", "helper", "=", "RendererHelper", "(", "name", "=", "renderer_name", ",", "package", "=", "package", ",", "registry", "=", "registry", ")", "with", "hide_attrs", "(", "request", ",", "'response'", ")", ":", "if", "(", "response", "is", "not", "None", ")", ":", "request", ".", "response", "=", "response", "result", "=", "helper", ".", "render_to_response", "(", "value", ",", "None", ",", "request", "=", "request", ")", "return", "result" ]
returns a httpresponse whose content is filled with the result of calling lookup .
train
false
16,533
def local_random(): global _local_random if (_local_random is None): _local_random = random.Random() return _local_random
[ "def", "local_random", "(", ")", ":", "global", "_local_random", "if", "(", "_local_random", "is", "None", ")", ":", "_local_random", "=", "random", ".", "Random", "(", ")", "return", "_local_random" ]
get the local random number generator .
train
false
16,534
def get_provider_metadata(metadata_url, supports_recursive=False, headers=None, expect_json=False): try: if supports_recursive: metadata = query_metadata(metadata_url, headers, expect_json) else: metadata = walk_metadata(metadata_url, headers, expect_json) except OpenShiftFactsMetadataUnavailableError: metadata = None return metadata
[ "def", "get_provider_metadata", "(", "metadata_url", ",", "supports_recursive", "=", "False", ",", "headers", "=", "None", ",", "expect_json", "=", "False", ")", ":", "try", ":", "if", "supports_recursive", ":", "metadata", "=", "query_metadata", "(", "metadata_url", ",", "headers", ",", "expect_json", ")", "else", ":", "metadata", "=", "walk_metadata", "(", "metadata_url", ",", "headers", ",", "expect_json", ")", "except", "OpenShiftFactsMetadataUnavailableError", ":", "metadata", "=", "None", "return", "metadata" ]
retrieve the provider metadata args: metadata_url : metadata url supports_recursive : does the provider metadata api support recursion headers : headers to set for metadata request expect_json : does the metadata_url return json returns: dict: the provider metadata .
train
false
16,535
def MakeCdfFromHist(hist, label=None): if (label is None): label = hist.label return Cdf(hist, label=label)
[ "def", "MakeCdfFromHist", "(", "hist", ",", "label", "=", "None", ")", ":", "if", "(", "label", "is", "None", ")", ":", "label", "=", "hist", ".", "label", "return", "Cdf", "(", "hist", ",", "label", "=", "label", ")" ]
makes a cdf from a hist object .
train
false
16,536
def systemInformationType2ter(): a = L2PseudoLength(l2pLength=18) b = TpPd(pd=6) c = MessageType(mesType=3) d = NeighbourCellsDescription2() e = Si2terRestOctets() packet = ((((a / b) / c) / d) / e) return packet
[ "def", "systemInformationType2ter", "(", ")", ":", "a", "=", "L2PseudoLength", "(", "l2pLength", "=", "18", ")", "b", "=", "TpPd", "(", "pd", "=", "6", ")", "c", "=", "MessageType", "(", "mesType", "=", "3", ")", "d", "=", "NeighbourCellsDescription2", "(", ")", "e", "=", "Si2terRestOctets", "(", ")", "packet", "=", "(", "(", "(", "(", "a", "/", "b", ")", "/", "c", ")", "/", "d", ")", "/", "e", ")", "return", "packet" ]
system information type 2ter section 9 .
train
true
16,537
def int_divmod(context, builder, ty, x, y): if ty.signed: return int_divmod_signed(context, builder, ty, x, y) else: return (builder.udiv(x, y), builder.urem(x, y))
[ "def", "int_divmod", "(", "context", ",", "builder", ",", "ty", ",", "x", ",", "y", ")", ":", "if", "ty", ".", "signed", ":", "return", "int_divmod_signed", "(", "context", ",", "builder", ",", "ty", ",", "x", ",", "y", ")", "else", ":", "return", "(", "builder", ".", "udiv", "(", "x", ",", "y", ")", ",", "builder", ".", "urem", "(", "x", ",", "y", ")", ")" ]
integer divmod .
train
false
16,540
def qnwbeta(n, a=1.0, b=1.0): return _make_multidim_func(_qnwbeta1, n, a, b)
[ "def", "qnwbeta", "(", "n", ",", "a", "=", "1.0", ",", "b", "=", "1.0", ")", ":", "return", "_make_multidim_func", "(", "_qnwbeta1", ",", "n", ",", "a", ",", "b", ")" ]
computes nodes and weights for beta distribution parameters n : int or array_like a length-d iterable of the number of nodes in each dimension a : scalar or array_like .
train
false
16,541
def test_text(): test_data = BytesIO('{"a": "b"}') assert (hug.input_format.text(test_data) == '{"a": "b"}')
[ "def", "test_text", "(", ")", ":", "test_data", "=", "BytesIO", "(", "'{\"a\": \"b\"}'", ")", "assert", "(", "hug", ".", "input_format", ".", "text", "(", "test_data", ")", "==", "'{\"a\": \"b\"}'", ")" ]
test that "text" image can be loaded .
train
false
16,542
def test_iszero_substitution(): m = Matrix([[0.9, (-0.1), (-0.2), 0], [(-0.8), 0.9, (-0.4), 0], [(-0.1), (-0.8), 0.6, 0]]) m_rref = m.rref(iszerofunc=(lambda x: (abs(x) < 6e-15)))[0] m_correct = Matrix([[1.0, 0, (-0.301369863013699), 0], [0, 1.0, (-0.712328767123288), 0], [0, 0, 0, 0]]) m_diff = (m_rref - m_correct) assert (m_diff.norm() < 1e-15) assert (m_rref[(2, 2)] == 0)
[ "def", "test_iszero_substitution", "(", ")", ":", "m", "=", "Matrix", "(", "[", "[", "0.9", ",", "(", "-", "0.1", ")", ",", "(", "-", "0.2", ")", ",", "0", "]", ",", "[", "(", "-", "0.8", ")", ",", "0.9", ",", "(", "-", "0.4", ")", ",", "0", "]", ",", "[", "(", "-", "0.1", ")", ",", "(", "-", "0.8", ")", ",", "0.6", ",", "0", "]", "]", ")", "m_rref", "=", "m", ".", "rref", "(", "iszerofunc", "=", "(", "lambda", "x", ":", "(", "abs", "(", "x", ")", "<", "6e-15", ")", ")", ")", "[", "0", "]", "m_correct", "=", "Matrix", "(", "[", "[", "1.0", ",", "0", ",", "(", "-", "0.301369863013699", ")", ",", "0", "]", ",", "[", "0", ",", "1.0", ",", "(", "-", "0.712328767123288", ")", ",", "0", "]", ",", "[", "0", ",", "0", ",", "0", ",", "0", "]", "]", ")", "m_diff", "=", "(", "m_rref", "-", "m_correct", ")", "assert", "(", "m_diff", ".", "norm", "(", ")", "<", "1e-15", ")", "assert", "(", "m_rref", "[", "(", "2", ",", "2", ")", "]", "==", "0", ")" ]
when doing numerical computations .
train
false
16,543
def net_send_object(sock, obj): data = pickle.dumps(obj, pickle.HIGHEST_PROTOCOL) sock.sendall(('%10d' % len(data))) sock.sendall(data)
[ "def", "net_send_object", "(", "sock", ",", "obj", ")", ":", "data", "=", "pickle", ".", "dumps", "(", "obj", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", "sock", ".", "sendall", "(", "(", "'%10d'", "%", "len", "(", "data", ")", ")", ")", "sock", ".", "sendall", "(", "data", ")" ]
send python object over network .
train
false
16,546
def _define_nrt_meminfo_data(module): fn = module.get_or_insert_function(meminfo_data_ty, name='NRT_MemInfo_data_fast') builder = ir.IRBuilder(fn.append_basic_block()) [ptr] = fn.args struct_ptr = builder.bitcast(ptr, _meminfo_struct_type.as_pointer()) data_ptr = builder.load(cgutils.gep(builder, struct_ptr, 0, 3)) builder.ret(data_ptr)
[ "def", "_define_nrt_meminfo_data", "(", "module", ")", ":", "fn", "=", "module", ".", "get_or_insert_function", "(", "meminfo_data_ty", ",", "name", "=", "'NRT_MemInfo_data_fast'", ")", "builder", "=", "ir", ".", "IRBuilder", "(", "fn", ".", "append_basic_block", "(", ")", ")", "[", "ptr", "]", "=", "fn", ".", "args", "struct_ptr", "=", "builder", ".", "bitcast", "(", "ptr", ",", "_meminfo_struct_type", ".", "as_pointer", "(", ")", ")", "data_ptr", "=", "builder", ".", "load", "(", "cgutils", ".", "gep", "(", "builder", ",", "struct_ptr", ",", "0", ",", "3", ")", ")", "builder", ".", "ret", "(", "data_ptr", ")" ]
implement nrt_meminfo_data_fast in the module .
train
false
16,547
@task @write def calc_checksum(theme_id, **kw): lfs = LocalFileStorage() theme = Persona.objects.get(id=theme_id) header = theme.header_path footer = theme.footer_path try: Image.open(header) Image.open(footer) except IOError: log.info(('Deleting invalid theme [%s] (header: %s) (footer: %s)' % (theme.addon.id, header, footer))) theme.addon.delete() theme.delete() rm_stored_dir(header.replace('header.png', ''), storage=lfs) return try: theme.checksum = make_checksum(header, footer) theme.save() except IOError as e: log.error(str(e))
[ "@", "task", "@", "write", "def", "calc_checksum", "(", "theme_id", ",", "**", "kw", ")", ":", "lfs", "=", "LocalFileStorage", "(", ")", "theme", "=", "Persona", ".", "objects", ".", "get", "(", "id", "=", "theme_id", ")", "header", "=", "theme", ".", "header_path", "footer", "=", "theme", ".", "footer_path", "try", ":", "Image", ".", "open", "(", "header", ")", "Image", ".", "open", "(", "footer", ")", "except", "IOError", ":", "log", ".", "info", "(", "(", "'Deleting invalid theme [%s] (header: %s) (footer: %s)'", "%", "(", "theme", ".", "addon", ".", "id", ",", "header", ",", "footer", ")", ")", ")", "theme", ".", "addon", ".", "delete", "(", ")", "theme", ".", "delete", "(", ")", "rm_stored_dir", "(", "header", ".", "replace", "(", "'header.png'", ",", "''", ")", ",", "storage", "=", "lfs", ")", "return", "try", ":", "theme", ".", "checksum", "=", "make_checksum", "(", "header", ",", "footer", ")", "theme", ".", "save", "(", ")", "except", "IOError", "as", "e", ":", "log", ".", "error", "(", "str", "(", "e", ")", ")" ]
for migration 596 .
train
false
16,549
def test_get_syslog_facility_empty(monkeypatch): assert (os.getenv('WALE_SYSLOG_FACILITY') is None) (out, valid_facility) = log_help.get_syslog_facility() assert (valid_facility is True) assert (out == handlers.SysLogHandler.LOG_USER)
[ "def", "test_get_syslog_facility_empty", "(", "monkeypatch", ")", ":", "assert", "(", "os", ".", "getenv", "(", "'WALE_SYSLOG_FACILITY'", ")", "is", "None", ")", "(", "out", ",", "valid_facility", ")", "=", "log_help", ".", "get_syslog_facility", "(", ")", "assert", "(", "valid_facility", "is", "True", ")", "assert", "(", "out", "==", "handlers", ".", "SysLogHandler", ".", "LOG_USER", ")" ]
wale_syslog_facility is not set .
train
false
16,551
def predict_help_ver(args): (ns, _) = HELP_VER_PREDICTOR_PARSER.parse_known_args(args) pred = ((ns.help is not None) or (ns.version is not None)) return pred
[ "def", "predict_help_ver", "(", "args", ")", ":", "(", "ns", ",", "_", ")", "=", "HELP_VER_PREDICTOR_PARSER", ".", "parse_known_args", "(", "args", ")", "pred", "=", "(", "(", "ns", ".", "help", "is", "not", "None", ")", "or", "(", "ns", ".", "version", "is", "not", "None", ")", ")", "return", "pred" ]
precict the backgroundability of commands that have help & version switches: -h .
train
false
16,552
def ensure_arg(args, arg, param=None): found = False for (idx, found_arg) in enumerate(args): if (found_arg == arg): if (param is not None): args[(idx + 1)] = param return args if (not found): args += [arg] if (param is not None): args += [param] return args
[ "def", "ensure_arg", "(", "args", ",", "arg", ",", "param", "=", "None", ")", ":", "found", "=", "False", "for", "(", "idx", ",", "found_arg", ")", "in", "enumerate", "(", "args", ")", ":", "if", "(", "found_arg", "==", "arg", ")", ":", "if", "(", "param", "is", "not", "None", ")", ":", "args", "[", "(", "idx", "+", "1", ")", "]", "=", "param", "return", "args", "if", "(", "not", "found", ")", ":", "args", "+=", "[", "arg", "]", "if", "(", "param", "is", "not", "None", ")", ":", "args", "+=", "[", "param", "]", "return", "args" ]
make sure the arg is present in the list of args .
train
false
16,553
def check_resolver(resolver): check_method = getattr(resolver, 'check', None) if (check_method is not None): return check_method() elif (not hasattr(resolver, 'resolve')): return get_warning_for_invalid_pattern(resolver) else: return []
[ "def", "check_resolver", "(", "resolver", ")", ":", "check_method", "=", "getattr", "(", "resolver", ",", "'check'", ",", "None", ")", "if", "(", "check_method", "is", "not", "None", ")", ":", "return", "check_method", "(", ")", "elif", "(", "not", "hasattr", "(", "resolver", ",", "'resolve'", ")", ")", ":", "return", "get_warning_for_invalid_pattern", "(", "resolver", ")", "else", ":", "return", "[", "]" ]
recursively check the resolver .
train
false
16,554
def _cannotInstallHandler(fd): raise RuntimeError('Cannot install a SIGCHLD handler')
[ "def", "_cannotInstallHandler", "(", "fd", ")", ":", "raise", "RuntimeError", "(", "'Cannot install a SIGCHLD handler'", ")" ]
fail to install a signal handler for i{sigchld} .
train
false
16,555
def is_dictlist(data): if isinstance(data, list): for element in data: if isinstance(element, dict): if (len(element) != 1): return False else: return False return True return False
[ "def", "is_dictlist", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "list", ")", ":", "for", "element", "in", "data", ":", "if", "isinstance", "(", "element", ",", "dict", ")", ":", "if", "(", "len", "(", "element", ")", "!=", "1", ")", ":", "return", "False", "else", ":", "return", "False", "return", "True", "return", "False" ]
returns true if data is a list of one-element dicts .
train
true
16,557
@requires_segment_info def capslock_indicator(pl, segment_info, text=u'CAPS'): if (not vim_func_exists(u'CapsLockStatusline')): return None return (text if vim.eval(u'CapsLockStatusline()') else None)
[ "@", "requires_segment_info", "def", "capslock_indicator", "(", "pl", ",", "segment_info", ",", "text", "=", "u'CAPS'", ")", ":", "if", "(", "not", "vim_func_exists", "(", "u'CapsLockStatusline'", ")", ")", ":", "return", "None", "return", "(", "text", "if", "vim", ".", "eval", "(", "u'CapsLockStatusline()'", ")", "else", "None", ")" ]
shows the indicator if tpope/vim-capslock plugin is enabled .
train
false
16,558
def reverse_cuthill_mckee_ordering(G, heuristic=None): return reversed(list(cuthill_mckee_ordering(G, heuristic=heuristic)))
[ "def", "reverse_cuthill_mckee_ordering", "(", "G", ",", "heuristic", "=", "None", ")", ":", "return", "reversed", "(", "list", "(", "cuthill_mckee_ordering", "(", "G", ",", "heuristic", "=", "heuristic", ")", ")", ")" ]
generate an ordering of the graph nodes to make a sparse matrix .
train
false
16,559
def get_flavor_access_by_flavor_id(flavorid, ctxt=None): if (ctxt is None): ctxt = context.get_admin_context() flavor = objects.Flavor.get_by_flavor_id(ctxt, flavorid) return flavor.projects
[ "def", "get_flavor_access_by_flavor_id", "(", "flavorid", ",", "ctxt", "=", "None", ")", ":", "if", "(", "ctxt", "is", "None", ")", ":", "ctxt", "=", "context", ".", "get_admin_context", "(", ")", "flavor", "=", "objects", ".", "Flavor", ".", "get_by_flavor_id", "(", "ctxt", ",", "flavorid", ")", "return", "flavor", ".", "projects" ]
retrieve flavor access list by flavor id .
train
false
16,562
def getFaceGivenLines(triangleMesh, vertexStartIndex, vertexIndexTable, vertexes): faceGivenLines = face.Face() faceGivenLines.index = len(triangleMesh.faces) for vertexIndex in xrange(vertexStartIndex, (vertexStartIndex + 3)): vertex = vertexes[vertexIndex] vertexUniqueIndex = len(vertexIndexTable) if (str(vertex) in vertexIndexTable): vertexUniqueIndex = vertexIndexTable[str(vertex)] else: vertexIndexTable[str(vertex)] = vertexUniqueIndex triangleMesh.vertexes.append(vertex) faceGivenLines.vertexIndexes.append(vertexUniqueIndex) return faceGivenLines
[ "def", "getFaceGivenLines", "(", "triangleMesh", ",", "vertexStartIndex", ",", "vertexIndexTable", ",", "vertexes", ")", ":", "faceGivenLines", "=", "face", ".", "Face", "(", ")", "faceGivenLines", ".", "index", "=", "len", "(", "triangleMesh", ".", "faces", ")", "for", "vertexIndex", "in", "xrange", "(", "vertexStartIndex", ",", "(", "vertexStartIndex", "+", "3", ")", ")", ":", "vertex", "=", "vertexes", "[", "vertexIndex", "]", "vertexUniqueIndex", "=", "len", "(", "vertexIndexTable", ")", "if", "(", "str", "(", "vertex", ")", "in", "vertexIndexTable", ")", ":", "vertexUniqueIndex", "=", "vertexIndexTable", "[", "str", "(", "vertex", ")", "]", "else", ":", "vertexIndexTable", "[", "str", "(", "vertex", ")", "]", "=", "vertexUniqueIndex", "triangleMesh", ".", "vertexes", ".", "append", "(", "vertex", ")", "faceGivenLines", ".", "vertexIndexes", ".", "append", "(", "vertexUniqueIndex", ")", "return", "faceGivenLines" ]
add face given line index and lines .
train
false
16,563
def jsmin(js): if (not is_3): if (cStringIO and (not isinstance(js, unicode))): klass = cStringIO.StringIO else: klass = StringIO.StringIO else: klass = io.StringIO ins = klass(js) outs = klass() JavascriptMinify(ins, outs).minify() return outs.getvalue()
[ "def", "jsmin", "(", "js", ")", ":", "if", "(", "not", "is_3", ")", ":", "if", "(", "cStringIO", "and", "(", "not", "isinstance", "(", "js", ",", "unicode", ")", ")", ")", ":", "klass", "=", "cStringIO", ".", "StringIO", "else", ":", "klass", "=", "StringIO", ".", "StringIO", "else", ":", "klass", "=", "io", ".", "StringIO", "ins", "=", "klass", "(", "js", ")", "outs", "=", "klass", "(", ")", "JavascriptMinify", "(", "ins", ",", "outs", ")", ".", "minify", "(", ")", "return", "outs", ".", "getvalue", "(", ")" ]
returns a minified version of the javascript string .
train
true
16,564
def libvlc_media_list_player_previous(p_mlp): f = (_Cfunctions.get('libvlc_media_list_player_previous', None) or _Cfunction('libvlc_media_list_player_previous', ((1,),), None, ctypes.c_int, MediaListPlayer)) return f(p_mlp)
[ "def", "libvlc_media_list_player_previous", "(", "p_mlp", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_media_list_player_previous'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_media_list_player_previous'", ",", "(", "(", "1", ",", ")", ",", ")", ",", "None", ",", "ctypes", ".", "c_int", ",", "MediaListPlayer", ")", ")", "return", "f", "(", "p_mlp", ")" ]
play previous item from media list .
train
true
16,565
def is_path_within_repo(app, path, repository_id): repo_path = os.path.abspath(repository_util.get_repository_by_id(app, repository_id).repo_path(app)) resolved_path = os.path.realpath(path) return (os.path.commonprefix([repo_path, resolved_path]) == repo_path)
[ "def", "is_path_within_repo", "(", "app", ",", "path", ",", "repository_id", ")", ":", "repo_path", "=", "os", ".", "path", ".", "abspath", "(", "repository_util", ".", "get_repository_by_id", "(", "app", ",", "repository_id", ")", ".", "repo_path", "(", "app", ")", ")", "resolved_path", "=", "os", ".", "path", ".", "realpath", "(", "path", ")", "return", "(", "os", ".", "path", ".", "commonprefix", "(", "[", "repo_path", ",", "resolved_path", "]", ")", "==", "repo_path", ")" ]
detect whether the given path is within the repository folder on the disk .
train
false
16,566
def _strip_schema(url): result = parse_url(url) return (result.netloc + result.path)
[ "def", "_strip_schema", "(", "url", ")", ":", "result", "=", "parse_url", "(", "url", ")", "return", "(", "result", ".", "netloc", "+", "result", ".", "path", ")" ]
returns the url without the s3:// part .
train
false
16,567
def test_settings_with_multiple_kwargs(): env.testval1 = 'outer 1' env.testval2 = 'outer 2' with settings(testval1='inner 1', testval2='inner 2'): eq_(env.testval1, 'inner 1') eq_(env.testval2, 'inner 2') eq_(env.testval1, 'outer 1') eq_(env.testval2, 'outer 2')
[ "def", "test_settings_with_multiple_kwargs", "(", ")", ":", "env", ".", "testval1", "=", "'outer 1'", "env", ".", "testval2", "=", "'outer 2'", "with", "settings", "(", "testval1", "=", "'inner 1'", ",", "testval2", "=", "'inner 2'", ")", ":", "eq_", "(", "env", ".", "testval1", ",", "'inner 1'", ")", "eq_", "(", "env", ".", "testval2", ",", "'inner 2'", ")", "eq_", "(", "env", ".", "testval1", ",", "'outer 1'", ")", "eq_", "(", "env", ".", "testval2", ",", "'outer 2'", ")" ]
settings() should temporarily override env dict with given key/value pairs .
train
false
16,568
def test_topic_tracker_needs_update_cleared(database, user, topic): forumsread = ForumsRead.query.filter((ForumsRead.user_id == user.id), (ForumsRead.forum_id == topic.forum_id)).first() topicsread = TopicsRead.query.filter((TopicsRead.user_id == user.id), (TopicsRead.topic_id == topic.id)).first() with current_app.test_request_context(): assert topic.tracker_needs_update(forumsread, topicsread) forumsread = ForumsRead() forumsread.user_id = user.id forumsread.forum_id = topic.forum_id forumsread.last_read = datetime.utcnow() forumsread.cleared = datetime.utcnow() forumsread.save() assert (not topic.tracker_needs_update(forumsread, topicsread))
[ "def", "test_topic_tracker_needs_update_cleared", "(", "database", ",", "user", ",", "topic", ")", ":", "forumsread", "=", "ForumsRead", ".", "query", ".", "filter", "(", "(", "ForumsRead", ".", "user_id", "==", "user", ".", "id", ")", ",", "(", "ForumsRead", ".", "forum_id", "==", "topic", ".", "forum_id", ")", ")", ".", "first", "(", ")", "topicsread", "=", "TopicsRead", ".", "query", ".", "filter", "(", "(", "TopicsRead", ".", "user_id", "==", "user", ".", "id", ")", ",", "(", "TopicsRead", ".", "topic_id", "==", "topic", ".", "id", ")", ")", ".", "first", "(", ")", "with", "current_app", ".", "test_request_context", "(", ")", ":", "assert", "topic", ".", "tracker_needs_update", "(", "forumsread", ",", "topicsread", ")", "forumsread", "=", "ForumsRead", "(", ")", "forumsread", ".", "user_id", "=", "user", ".", "id", "forumsread", ".", "forum_id", "=", "topic", ".", "forum_id", "forumsread", ".", "last_read", "=", "datetime", ".", "utcnow", "(", ")", "forumsread", ".", "cleared", "=", "datetime", ".", "utcnow", "(", ")", "forumsread", ".", "save", "(", ")", "assert", "(", "not", "topic", ".", "tracker_needs_update", "(", "forumsread", ",", "topicsread", ")", ")" ]
tests if the topicsread needs an update if the forum has been marked as cleared .
train
false