id_within_dataset
int64
1
55.5k
snippet
stringlengths
19
14.2k
tokens
listlengths
6
1.63k
nl
stringlengths
6
352
split_within_dataset
stringclasses
1 value
is_duplicated
bool
2 classes
26,497
def _build_units_list(units, reverse=False): return_units = [] for unit in iter(units): return_units.append(_prepare_unit(unit)) return return_units
[ "def", "_build_units_list", "(", "units", ",", "reverse", "=", "False", ")", ":", "return_units", "=", "[", "]", "for", "unit", "in", "iter", "(", "units", ")", ":", "return_units", ".", "append", "(", "_prepare_unit", "(", "unit", ")", ")", "return", ...
given a list/queryset of units .
train
false
26,498
def octagon(m, n, dtype=np.uint8): from . import convex_hull_image selem = np.zeros(((m + (2 * n)), (m + (2 * n)))) selem[(0, n)] = 1 selem[(n, 0)] = 1 selem[(0, ((m + n) - 1))] = 1 selem[(((m + n) - 1), 0)] = 1 selem[((-1), n)] = 1 selem[(n, (-1))] = 1 selem[((-1), ((m + n) - 1))] = 1 selem[(((m + n) - 1), (-1))] = 1 selem = convex_hull_image(selem).astype(dtype) return selem
[ "def", "octagon", "(", "m", ",", "n", ",", "dtype", "=", "np", ".", "uint8", ")", ":", "from", ".", "import", "convex_hull_image", "selem", "=", "np", ".", "zeros", "(", "(", "(", "m", "+", "(", "2", "*", "n", ")", ")", ",", "(", "m", "+", ...
generates an octagon shaped structuring element .
train
false
26,500
def find_pickleable_exception(exc, loads=pickle.loads, dumps=pickle.dumps): exc_args = getattr(exc, u'args', []) for supercls in itermro(exc.__class__, unwanted_base_classes): try: superexc = supercls(*exc_args) loads(dumps(superexc)) except Exception: pass else: return superexc
[ "def", "find_pickleable_exception", "(", "exc", ",", "loads", "=", "pickle", ".", "loads", ",", "dumps", "=", "pickle", ".", "dumps", ")", ":", "exc_args", "=", "getattr", "(", "exc", ",", "u'args'", ",", "[", "]", ")", "for", "supercls", "in", "itermr...
find first pickleable exception base class .
train
false
26,502
def RemoveLibrary(name): (installed_version, _) = installed[name] path = CreatePath(name, installed_version) try: sys.path.remove(path) except ValueError: pass del installed[name]
[ "def", "RemoveLibrary", "(", "name", ")", ":", "(", "installed_version", ",", "_", ")", "=", "installed", "[", "name", "]", "path", "=", "CreatePath", "(", "name", ",", "installed_version", ")", "try", ":", "sys", ".", "path", ".", "remove", "(", "path...
remove a library that has been installed .
train
false
26,503
def parse_page(dirpath): (filename, msg) = read_content_file(dirpath) content = msg.get_payload() content_type = determine_page_content_type(content) data = {'headers': dict(msg.items()), 'content': content, 'content_type': content_type, 'filename': filename} return data
[ "def", "parse_page", "(", "dirpath", ")", ":", "(", "filename", ",", "msg", ")", "=", "read_content_file", "(", "dirpath", ")", "content", "=", "msg", ".", "get_payload", "(", ")", "content_type", "=", "determine_page_content_type", "(", "content", ")", "dat...
parse a page given a relative file path .
train
false
26,506
def wrap_css_lines(css, line_length): lines = [] line_start = 0 for (i, char) in enumerate(css): if ((char == '}') and ((i - line_start) >= line_length)): lines.append(css[line_start:(i + 1)]) line_start = (i + 1) if (line_start < len(css)): lines.append(css[line_start:]) return '\n'.join(lines)
[ "def", "wrap_css_lines", "(", "css", ",", "line_length", ")", ":", "lines", "=", "[", "]", "line_start", "=", "0", "for", "(", "i", ",", "char", ")", "in", "enumerate", "(", "css", ")", ":", "if", "(", "(", "char", "==", "'}'", ")", "and", "(", ...
wrap the lines of the given css to an approximate length .
train
true
26,507
def rm_special(user, special, cmd): lst = list_tab(user) ret = 'absent' rm_ = None for ind in range(len(lst['special'])): if ((lst['special'][ind]['cmd'] == cmd) and (lst['special'][ind]['spec'] == special)): lst['special'].pop(ind) rm_ = ind if (rm_ is not None): ret = 'removed' comdat = _write_cron_lines(user, _render_tab(lst)) if comdat['retcode']: return comdat['stderr'] return ret
[ "def", "rm_special", "(", "user", ",", "special", ",", "cmd", ")", ":", "lst", "=", "list_tab", "(", "user", ")", "ret", "=", "'absent'", "rm_", "=", "None", "for", "ind", "in", "range", "(", "len", "(", "lst", "[", "'special'", "]", ")", ")", ":...
remove a special cron job for a specified user .
train
true
26,508
def is_certificate_invalid(student, course_key): is_invalid = False certificate = GeneratedCertificate.certificate_for_student(student, course_key) if (certificate is not None): is_invalid = CertificateInvalidation.has_certificate_invalidation(student, course_key) return is_invalid
[ "def", "is_certificate_invalid", "(", "student", ",", "course_key", ")", ":", "is_invalid", "=", "False", "certificate", "=", "GeneratedCertificate", ".", "certificate_for_student", "(", "student", ",", "course_key", ")", "if", "(", "certificate", "is", "not", "No...
check that whether the student in the course has been invalidated for receiving certificates .
train
false
26,510
def set_plugin_icon_resources(name, resources): global plugin_icon_resources, plugin_name plugin_name = name plugin_icon_resources = resources
[ "def", "set_plugin_icon_resources", "(", "name", ",", "resources", ")", ":", "global", "plugin_icon_resources", ",", "plugin_name", "plugin_name", "=", "name", "plugin_icon_resources", "=", "resources" ]
set our global store of plugin name and icon resources for sharing between the interfaceaction class which reads them and the configwidget if needed for use on the customization dialog for this plugin .
train
false
26,511
def _data_api(): api_path = getattr(settings, 'ENROLLMENT_DATA_API', DEFAULT_DATA_API) try: return importlib.import_module(api_path) except (ImportError, ValueError): log.exception(u"Could not load module at '{path}'".format(path=api_path)) raise errors.EnrollmentApiLoadError(api_path)
[ "def", "_data_api", "(", ")", ":", "api_path", "=", "getattr", "(", "settings", ",", "'ENROLLMENT_DATA_API'", ",", "DEFAULT_DATA_API", ")", "try", ":", "return", "importlib", ".", "import_module", "(", "api_path", ")", "except", "(", "ImportError", ",", "Value...
returns a data api .
train
false
26,512
def get_qos_policy_group_name(volume): if ('id' in volume): return (OPENSTACK_PREFIX + volume['id']) return None
[ "def", "get_qos_policy_group_name", "(", "volume", ")", ":", "if", "(", "'id'", "in", "volume", ")", ":", "return", "(", "OPENSTACK_PREFIX", "+", "volume", "[", "'id'", "]", ")", "return", "None" ]
return the name of backend qos policy group based on its volume id .
train
false
26,513
def wrap_http_for_jwt_access(credentials, http): orig_request_method = http.request wrap_http_for_auth(credentials, http) authenticated_request_method = http.request def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): if ('aud' in credentials._kwargs): if ((credentials.access_token is None) or credentials.access_token_expired): credentials.refresh(None) return request(authenticated_request_method, uri, method, body, headers, redirections, connection_type) else: headers = _initialize_headers(headers) _apply_user_agent(headers, credentials.user_agent) uri_root = uri.split('?', 1)[0] (token, unused_expiry) = credentials._create_token({'aud': uri_root}) headers['Authorization'] = ('Bearer ' + token) return request(orig_request_method, uri, method, body, clean_headers(headers), redirections, connection_type) http.request = new_request http.request.credentials = credentials
[ "def", "wrap_http_for_jwt_access", "(", "credentials", ",", "http", ")", ":", "orig_request_method", "=", "http", ".", "request", "wrap_http_for_auth", "(", "credentials", ",", "http", ")", "authenticated_request_method", "=", "http", ".", "request", "def", "new_req...
prepares an http objects request method for jwt access .
train
true
26,514
def p_unary_expression_2(t): pass
[ "def", "p_unary_expression_2", "(", "t", ")", ":", "pass" ]
unary_expression : plusplus unary_expression .
train
false
26,515
def oauth2_authorize(request): return_url = request.GET.get('return_url', None) if (not return_url): return_url = request.META.get('HTTP_REFERER', '/') scopes = request.GET.getlist('scopes', django_util.oauth2_settings.scopes) if django_util.oauth2_settings.storage_model: if (not request.user.is_authenticated()): return redirect('{0}?next={1}'.format(settings.LOGIN_URL, parse.quote(request.get_full_path()))) else: user_oauth = django_util.UserOAuth2(request, scopes, return_url) if user_oauth.has_credentials(): return redirect(return_url) flow = _make_flow(request=request, scopes=scopes, return_url=return_url) auth_url = flow.step1_get_authorize_url() return shortcuts.redirect(auth_url)
[ "def", "oauth2_authorize", "(", "request", ")", ":", "return_url", "=", "request", ".", "GET", ".", "get", "(", "'return_url'", ",", "None", ")", "if", "(", "not", "return_url", ")", ":", "return_url", "=", "request", ".", "META", ".", "get", "(", "'HT...
view to start the oauth2 authorization flow .
train
true
26,516
def assert_no_element_by_css_selector(context, css_value, wait_time=MAX_WAIT_FOR_UNEXPECTED_ELEMENT): _assert_no_element_by(context, By.CSS_SELECTOR, css_value, wait_time)
[ "def", "assert_no_element_by_css_selector", "(", "context", ",", "css_value", ",", "wait_time", "=", "MAX_WAIT_FOR_UNEXPECTED_ELEMENT", ")", ":", "_assert_no_element_by", "(", "context", ",", "By", ".", "CSS_SELECTOR", ",", "css_value", ",", "wait_time", ")" ]
assert that no element is found .
train
false
26,517
def _read_next_mpint(data): (mpint_data, rest) = _read_next_string(data) return (utils.int_from_bytes(mpint_data, byteorder='big', signed=False), rest)
[ "def", "_read_next_mpint", "(", "data", ")", ":", "(", "mpint_data", ",", "rest", ")", "=", "_read_next_string", "(", "data", ")", "return", "(", "utils", ".", "int_from_bytes", "(", "mpint_data", ",", "byteorder", "=", "'big'", ",", "signed", "=", "False"...
reads the next mpint from the data .
train
false
26,518
def register_public_extension(url_prefix, extension_data): PUBLIC_EXTENSIONS[url_prefix] = extension_data
[ "def", "register_public_extension", "(", "url_prefix", ",", "extension_data", ")", ":", "PUBLIC_EXTENSIONS", "[", "url_prefix", "]", "=", "extension_data" ]
same as register_admin_extension but for public extensions .
train
false
26,519
def f(t): s1 = np.cos(((2 * np.pi) * t)) e1 = np.exp((- t)) return (s1 * e1)
[ "def", "f", "(", "t", ")", ":", "s1", "=", "np", ".", "cos", "(", "(", "(", "2", "*", "np", ".", "pi", ")", "*", "t", ")", ")", "e1", "=", "np", ".", "exp", "(", "(", "-", "t", ")", ")", "return", "(", "s1", "*", "e1", ")" ]
very nice function .
train
false
26,520
def verify_certs(*args): msg = 'Could not find a certificate: {0}\nIf you want to quickly generate a self-signed certificate, use the tls.create_self_signed_cert function in Salt' for arg in args: if (not os.path.exists(arg)): raise Exception(msg.format(arg))
[ "def", "verify_certs", "(", "*", "args", ")", ":", "msg", "=", "'Could not find a certificate: {0}\\nIf you want to quickly generate a self-signed certificate, use the tls.create_self_signed_cert function in Salt'", "for", "arg", "in", "args", ":", "if", "(", "not", "os", ".", ...
sanity checking for the specified ssl certificates .
train
true
26,521
def _create_image_file(image, exif): string_io = StringIO() if (exif is None): image.save(string_io, format='JPEG') else: image.save(string_io, format='JPEG', exif=exif) image_file = ContentFile(string_io.getvalue()) return image_file
[ "def", "_create_image_file", "(", "image", ",", "exif", ")", ":", "string_io", "=", "StringIO", "(", ")", "if", "(", "exif", "is", "None", ")", ":", "image", ".", "save", "(", "string_io", ",", "format", "=", "'JPEG'", ")", "else", ":", "image", ".",...
given a pil .
train
false
26,522
def test_train_cmd(): train(os.path.join(pylearn2.__path__[0], 'scripts/autoencoder_example/dae.yaml'))
[ "def", "test_train_cmd", "(", ")", ":", "train", "(", "os", ".", "path", ".", "join", "(", "pylearn2", ".", "__path__", "[", "0", "]", ",", "'scripts/autoencoder_example/dae.yaml'", ")", ")" ]
calls the train .
train
false
26,523
def badParameterResponse(msg, ajax=None): if ajax: return sabnzbd.api.report('json', error=msg) else: return ('\n<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">\n<html>\n<head>\n <title>SABnzbd %s - %s</title>\n</head>\n<body>\n<h3>%s</h3>\n%s\n<br><br>\n<FORM><INPUT TYPE="BUTTON" VALUE="%s" ONCLICK="history.go(-1)"></FORM>\n</body>\n</html>\n' % (sabnzbd.__version__, T('ERROR:'), T('Incorrect parameter'), unicoder(msg), T('Back')))
[ "def", "badParameterResponse", "(", "msg", ",", "ajax", "=", "None", ")", ":", "if", "ajax", ":", "return", "sabnzbd", ".", "api", ".", "report", "(", "'json'", ",", "error", "=", "msg", ")", "else", ":", "return", "(", "'\\n<!DOCTYPE HTML PUBLIC \"-//W3C/...
return a html page with error message and a back button .
train
false
26,524
def smoothstep(edge0, edge1, x): x = np.clip(((x - edge0) / (edge1 - edge0)), 0.0, 1.0) return ((x * x) * (3 - (2 * x)))
[ "def", "smoothstep", "(", "edge0", ",", "edge1", ",", "x", ")", ":", "x", "=", "np", ".", "clip", "(", "(", "(", "x", "-", "edge0", ")", "/", "(", "edge1", "-", "edge0", ")", ")", ",", "0.0", ",", "1.0", ")", "return", "(", "(", "x", "*", ...
returns the hermite interpolation for x between a and b .
train
true
26,525
def skip_signing_warning(result): try: messages = result['messages'] except (KeyError, ValueError): return result messages = [m for m in messages if ('signed_xpi' not in m['id'])] diff = (len(result['messages']) - len(messages)) if diff: result['messages'] = messages result['warnings'] -= diff return result
[ "def", "skip_signing_warning", "(", "result", ")", ":", "try", ":", "messages", "=", "result", "[", "'messages'", "]", "except", "(", "KeyError", ",", "ValueError", ")", ":", "return", "result", "messages", "=", "[", "m", "for", "m", "in", "messages", "i...
remove the "package already signed" warning if were not signing .
train
false
26,526
def sanitise_json_error(error_dict): ret = copy.copy(error_dict) chop = len(JSON_ERROR) ret[u'detail'] = ret[u'detail'][:chop] return ret
[ "def", "sanitise_json_error", "(", "error_dict", ")", ":", "ret", "=", "copy", ".", "copy", "(", "error_dict", ")", "chop", "=", "len", "(", "JSON_ERROR", ")", "ret", "[", "u'detail'", "]", "=", "ret", "[", "u'detail'", "]", "[", ":", "chop", "]", "r...
exact contents of json error messages depend on the installed version of json .
train
false
26,530
def ensure_valid_course_key(view_func): @wraps(view_func) def inner(request, *args, **kwargs): course_key = (kwargs.get('course_key_string') or kwargs.get('course_id')) if (course_key is not None): try: CourseKey.from_string(course_key) except InvalidKeyError: raise Http404 response = view_func(request, *args, **kwargs) return response return inner
[ "def", "ensure_valid_course_key", "(", "view_func", ")", ":", "@", "wraps", "(", "view_func", ")", "def", "inner", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "course_key", "=", "(", "kwargs", ".", "get", "(", "'course_key_string'", ...
this decorator should only be used with views which have argument course_key_string or course_id .
train
false
26,531
def make_call_asserter(func=None): calls = [0] @contextmanager def asserter(count, msg=None): calls[0] = 0 (yield) assert (calls[0] == count) def wrapped(*args, **kwargs): calls[0] += 1 if (func is not None): return func(*args, **kwargs) return (asserter, wrapped)
[ "def", "make_call_asserter", "(", "func", "=", "None", ")", ":", "calls", "=", "[", "0", "]", "@", "contextmanager", "def", "asserter", "(", "count", ",", "msg", "=", "None", ")", ":", "calls", "[", "0", "]", "=", "0", "(", "yield", ")", "assert", ...
utility to assert a certain number of function calls .
train
false
26,532
@log_call def metadef_namespace_delete_content(context, namespace_name): global DATA namespace = metadef_namespace_get(context, namespace_name) namespace_id = namespace['id'] objects = [] for object in DATA['metadef_objects']: if (object['namespace_id'] != namespace_id): objects.append(object) DATA['metadef_objects'] = objects properties = [] for property in DATA['metadef_objects']: if (property['namespace_id'] != namespace_id): properties.append(object) DATA['metadef_objects'] = properties return namespace
[ "@", "log_call", "def", "metadef_namespace_delete_content", "(", "context", ",", "namespace_name", ")", ":", "global", "DATA", "namespace", "=", "metadef_namespace_get", "(", "context", ",", "namespace_name", ")", "namespace_id", "=", "namespace", "[", "'id'", "]", ...
delete a namespace content .
train
false
26,534
def view_with_header(request): response = HttpResponse() response['X-DJANGO-TEST'] = 'Slartibartfast' return response
[ "def", "view_with_header", "(", "request", ")", ":", "response", "=", "HttpResponse", "(", ")", "response", "[", "'X-DJANGO-TEST'", "]", "=", "'Slartibartfast'", "return", "response" ]
a view that has a custom header .
train
false
26,535
def setup_environ(settings_mod, original_settings_path=None): if ('__init__.py' in settings_mod.__file__): p = os.path.dirname(settings_mod.__file__) else: p = settings_mod.__file__ (project_directory, settings_filename) = os.path.split(p) if ((project_directory == os.curdir) or (not project_directory)): project_directory = os.getcwd() project_name = os.path.basename(project_directory) settings_name = os.path.splitext(settings_filename)[0] if settings_name.endswith('$py'): settings_name = settings_name[:(-3)] if original_settings_path: os.environ['DJANGO_SETTINGS_MODULE'] = original_settings_path else: os.environ['DJANGO_SETTINGS_MODULE'] = ('%s.%s' % (project_name, settings_name)) sys.path.append(os.path.join(project_directory, os.pardir)) project_module = import_module(project_name) sys.path.pop() return project_directory
[ "def", "setup_environ", "(", "settings_mod", ",", "original_settings_path", "=", "None", ")", ":", "if", "(", "'__init__.py'", "in", "settings_mod", ".", "__file__", ")", ":", "p", "=", "os", ".", "path", ".", "dirname", "(", "settings_mod", ".", "__file__",...
configure the runtime environment .
train
false
26,537
def _get_unpatched(cls): while cls.__module__.startswith('setuptools'): (cls,) = cls.__bases__ if (not cls.__module__.startswith('distutils')): raise AssertionError(('distutils has already been patched by %r' % cls)) return cls
[ "def", "_get_unpatched", "(", "cls", ")", ":", "while", "cls", ".", "__module__", ".", "startswith", "(", "'setuptools'", ")", ":", "(", "cls", ",", ")", "=", "cls", ".", "__bases__", "if", "(", "not", "cls", ".", "__module__", ".", "startswith", "(", ...
protect against re-patching the distutils if reloaded also ensures that no other distutils extension monkeypatched the distutils first .
train
true
26,540
def supply_item_controller(): s3 = current.response.s3 s3db = current.s3db def prep(r): if r.component: if (r.component_name == 'inv_item'): s3db.configure('inv_inv_item', listadd=False, deletable=False) inv_item_pack_requires = IS_ONE_OF(current.db, 'supply_item_pack.id', s3db.supply_item_pack_represent, sort=True, filterby='item_id', filter_opts=(r.record.id,)) s3db.inv_inv_item.item_pack_id.requires = inv_item_pack_requires elif (r.component_name == 'req_item'): s3db.configure('req_req_item', listadd=False, deletable=False) elif (r.representation == 'xls'): s3db.supply_item.item_category_id.represent = supply_ItemCategoryRepresent(use_code=False) return True s3.prep = prep return current.rest_controller('supply', 'item', rheader=supply_item_rheader)
[ "def", "supply_item_controller", "(", ")", ":", "s3", "=", "current", ".", "response", ".", "s3", "s3db", "=", "current", ".", "s3db", "def", "prep", "(", "r", ")", ":", "if", "r", ".", "component", ":", "if", "(", "r", ".", "component_name", "==", ...
restful crud controller .
train
false
26,541
def getVerbosityFormat(verbosity, fmt=' %(message)s'): if (verbosity > 1): if (verbosity > 3): fmt = (' | %(module)15.15s-%(levelno)-2d: %(funcName)-20.20s |' + fmt) if (verbosity > 2): fmt = (' +%(relativeCreated)5d %(thread)X %(name)-25.25s %(levelname)-5.5s' + fmt) else: fmt = (' %(asctime)-15s %(thread)X %(levelname)-5.5s' + fmt) return fmt
[ "def", "getVerbosityFormat", "(", "verbosity", ",", "fmt", "=", "' %(message)s'", ")", ":", "if", "(", "verbosity", ">", "1", ")", ":", "if", "(", "verbosity", ">", "3", ")", ":", "fmt", "=", "(", "' | %(module)15.15s-%(levelno)-2d: %(funcName)-20.20s |'", "+"...
custom log format for the verbose runs .
train
false
26,542
def getHostHeader(url): retVal = url if url: retVal = urlparse.urlparse(url).netloc if re.search('http(s)?://\\[.+\\]', url, re.I): retVal = extractRegexResult('http(s)?://\\[(?P<result>.+)\\]', url) elif any((retVal.endswith((':%d' % _)) for _ in (80, 443))): retVal = retVal.split(':')[0] return retVal
[ "def", "getHostHeader", "(", "url", ")", ":", "retVal", "=", "url", "if", "url", ":", "retVal", "=", "urlparse", ".", "urlparse", "(", "url", ")", ".", "netloc", "if", "re", ".", "search", "(", "'http(s)?://\\\\[.+\\\\]'", ",", "url", ",", "re", ".", ...
returns proper host header value for a given target url .
train
false
26,543
def ClosePreviewWindow(): vim.command(u'silent! pclose!')
[ "def", "ClosePreviewWindow", "(", ")", ":", "vim", ".", "command", "(", "u'silent! pclose!'", ")" ]
close the preview window if it is present .
train
false
26,545
def getNewRepository(): return ExportRepository()
[ "def", "getNewRepository", "(", ")", ":", "return", "ExportRepository", "(", ")" ]
get the repository constructor .
train
false
26,546
def _wrap_transport(method): @functools.wraps(method) def wrapper(self, *args, **kwargs): self._check_stream() self._stream.set_close_callback(functools.partial(self._on_close, gr=greenlet.getcurrent())) self._start_time = time.time() timeout = self._set_timeout() try: return method(self, *args, **kwargs) except TTransportException: self.close() raise finally: self._clear_timeout(timeout) if self._stream: self._stream.set_close_callback(functools.partial(self._on_close, gr=None)) return wrapper
[ "def", "_wrap_transport", "(", "method", ")", ":", "@", "functools", ".", "wraps", "(", "method", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "_check_stream", "(", ")", "self", ".", "_stream", "."...
decorator to consistently check the underlying stream .
train
false
26,548
def codename(): return _distro.codename()
[ "def", "codename", "(", ")", ":", "return", "_distro", ".", "codename", "(", ")" ]
return the codename for the release of the current linux distribution .
train
false
26,549
def extrudeText(gcodeText): skein = extrudeSkein() skein.parseText(gcodeText) return skein.output
[ "def", "extrudeText", "(", "gcodeText", ")", ":", "skein", "=", "extrudeSkein", "(", ")", "skein", ".", "parseText", "(", "gcodeText", ")", "return", "skein", ".", "output" ]
parse a gcode text and send the commands to the extruder .
train
false
26,550
def upload_stable(user='pandas'): if os.system('cd build/html; rsync -avz . {0}@pandas.pydata.org:/usr/share/nginx/pandas/pandas-docs/stable/ -essh'.format(user)): raise SystemExit('Upload to stable failed')
[ "def", "upload_stable", "(", "user", "=", "'pandas'", ")", ":", "if", "os", ".", "system", "(", "'cd build/html; rsync -avz . {0}@pandas.pydata.org:/usr/share/nginx/pandas/pandas-docs/stable/ -essh'", ".", "format", "(", "user", ")", ")", ":", "raise", "SystemExit", "("...
push a copy to the pydata stable directory .
train
false
26,552
def create_inline(project, resource, offset): pyname = _get_pyname(project, resource, offset) message = 'Inline refactoring should be performed on a method, local variable or parameter.' if (pyname is None): raise rope.base.exceptions.RefactoringError(message) if isinstance(pyname, pynames.ImportedName): pyname = pyname._get_imported_pyname() if isinstance(pyname, pynames.AssignedName): return InlineVariable(project, resource, offset) if isinstance(pyname, pynames.ParameterName): return InlineParameter(project, resource, offset) if isinstance(pyname.get_object(), pyobjects.PyFunction): return InlineMethod(project, resource, offset) else: raise rope.base.exceptions.RefactoringError(message)
[ "def", "create_inline", "(", "project", ",", "resource", ",", "offset", ")", ":", "pyname", "=", "_get_pyname", "(", "project", ",", "resource", ",", "offset", ")", "message", "=", "'Inline refactoring should be performed on a method, local variable or parameter.'", "if...
create a refactoring object for inlining based on resource and offset it returns an instance of inlinemethod .
train
true
26,553
def network_update(context, network_id, values): return IMPL.network_update(context, network_id, values)
[ "def", "network_update", "(", "context", ",", "network_id", ",", "values", ")", ":", "return", "IMPL", ".", "network_update", "(", "context", ",", "network_id", ",", "values", ")" ]
set the given properties on a network and update it .
train
false
26,554
def split_choices(choices, split): index = [idx for (idx, (key, title)) in enumerate(choices) if (key == split)] if index: index = (index[0] + 1) return (choices[:index], choices[index:]) else: return (choices, [])
[ "def", "split_choices", "(", "choices", ",", "split", ")", ":", "index", "=", "[", "idx", "for", "(", "idx", ",", "(", "key", ",", "title", ")", ")", "in", "enumerate", "(", "choices", ")", "if", "(", "key", "==", "split", ")", "]", "if", "index"...
split a list of [] pairs after key == split .
train
false
26,557
def _stripped(d): ret = {} for (k, v) in six.iteritems(d): if v: ret[k] = v return ret
[ "def", "_stripped", "(", "d", ")", ":", "ret", "=", "{", "}", "for", "(", "k", ",", "v", ")", "in", "six", ".", "iteritems", "(", "d", ")", ":", "if", "v", ":", "ret", "[", "k", "]", "=", "v", "return", "ret" ]
strip falsey entries .
train
true
26,558
def _task_soft_delete(context, session=None): expires_at = models.Task.expires_at session = (session or get_session()) query = session.query(models.Task) query = query.filter((models.Task.owner == context.owner)).filter_by(deleted=0).filter((expires_at <= timeutils.utcnow())) values = {'deleted': 1, 'deleted_at': timeutils.utcnow()} with session.begin(): query.update(values)
[ "def", "_task_soft_delete", "(", "context", ",", "session", "=", "None", ")", ":", "expires_at", "=", "models", ".", "Task", ".", "expires_at", "session", "=", "(", "session", "or", "get_session", "(", ")", ")", "query", "=", "session", ".", "query", "("...
scrub task entities which are expired .
train
false
26,561
def attrs_eq(received, **expected): for (k, v) in expected.iteritems(): eq_(v, getattr(received, k))
[ "def", "attrs_eq", "(", "received", ",", "**", "expected", ")", ":", "for", "(", "k", ",", "v", ")", "in", "expected", ".", "iteritems", "(", ")", ":", "eq_", "(", "v", ",", "getattr", "(", "received", ",", "k", ")", ")" ]
compares receiveds attributes with expecteds kwargs .
train
false
26,564
def _AddType(type): type.Array = CreateArrayType(type) typeNS = GetWsdlNamespace(type._version) newType = _SetWsdlType(typeNS, type._wsdlName, type) if (newType != type): raise RuntimeError(('Duplicate wsdl type %s (already in typemap)' % type._wsdlName)) return type
[ "def", "_AddType", "(", "type", ")", ":", "type", ".", "Array", "=", "CreateArrayType", "(", "type", ")", "typeNS", "=", "GetWsdlNamespace", "(", "type", ".", "_version", ")", "newType", "=", "_SetWsdlType", "(", "typeNS", ",", "type", ".", "_wsdlName", ...
note: must be holding the _lazylock .
train
true
26,565
def get_dicts(dict_path1, dict_path2): return (eval(open(dict_path1).read()), eval(open(dict_path2).read()))
[ "def", "get_dicts", "(", "dict_path1", ",", "dict_path2", ")", ":", "return", "(", "eval", "(", "open", "(", "dict_path1", ")", ".", "read", "(", ")", ")", ",", "eval", "(", "open", "(", "dict_path2", ")", ".", "read", "(", ")", ")", ")" ]
parse the dictionaries .
train
false
26,567
@register_canonicalize @gof.local_optimizer([T.int_div]) def local_intdiv_by_one(node): if (node.op in [T.int_div]): if (isinstance(node.inputs[1], T.TensorConstant) and numpy.all((node.inputs[1].value == 1))): return [node.inputs[0].astype(node.outputs[0].dtype)]
[ "@", "register_canonicalize", "@", "gof", ".", "local_optimizer", "(", "[", "T", ".", "int_div", "]", ")", "def", "local_intdiv_by_one", "(", "node", ")", ":", "if", "(", "node", ".", "op", "in", "[", "T", ".", "int_div", "]", ")", ":", "if", "(", ...
x // 1 -> x .
train
false
26,568
def get_exploration_summaries_matching_ids(exp_ids): return [(get_exploration_summary_from_model(model) if model else None) for model in exp_models.ExpSummaryModel.get_multi(exp_ids)]
[ "def", "get_exploration_summaries_matching_ids", "(", "exp_ids", ")", ":", "return", "[", "(", "get_exploration_summary_from_model", "(", "model", ")", "if", "model", "else", "None", ")", "for", "model", "in", "exp_models", ".", "ExpSummaryModel", ".", "get_multi", ...
given a list of exploration ids .
train
false
26,569
def test_no_active_item(): items = [Item(QUrl(), '')] with pytest.raises(ValueError): tabhistory.serialize(items)
[ "def", "test_no_active_item", "(", ")", ":", "items", "=", "[", "Item", "(", "QUrl", "(", ")", ",", "''", ")", "]", "with", "pytest", ".", "raises", "(", "ValueError", ")", ":", "tabhistory", ".", "serialize", "(", "items", ")" ]
check tabhistory .
train
false
26,570
def extract_config_changes(file_paths, compared_file_paths=[]): changes = {} for i in range(len(file_paths)): temp_file_path = get_temp_file_path(file_paths[i]) if (len(compared_file_paths) > i): command = ((('diff -U 0 -b ' + compared_file_paths[i]) + ' ') + file_paths[i]) else: command = ((('diff -U 0 -b ' + temp_file_path) + ' ') + file_paths[i]) (_, output) = commands.getstatusoutput(command) lines = output.split('\n') changes[file_paths[i]] = parse_unified_diff_output(lines) return changes
[ "def", "extract_config_changes", "(", "file_paths", ",", "compared_file_paths", "=", "[", "]", ")", ":", "changes", "=", "{", "}", "for", "i", "in", "range", "(", "len", "(", "file_paths", ")", ")", ":", "temp_file_path", "=", "get_temp_file_path", "(", "f...
extracts diff information based on the new and temporarily saved old config files returns a dictionary of file path and corresponding diff information key-value pairs .
train
false
26,571
def buildServiceManager(jid, password, strport): svc = ServiceManager(jid, password) client_svc = jstrports.client(strport, svc.getFactory()) client_svc.setServiceParent(svc) return svc
[ "def", "buildServiceManager", "(", "jid", ",", "password", ",", "strport", ")", ":", "svc", "=", "ServiceManager", "(", "jid", ",", "password", ")", "client_svc", "=", "jstrports", ".", "client", "(", "strport", ",", "svc", ".", "getFactory", "(", ")", "...
constructs a pre-built l{servicemanager} .
train
false
26,572
def extract_user_mentions(text): from r2.lib.validator import chkuser usernames = set() for url in extract_urls_from_markdown(text): if (not url.startswith('/u/')): continue username = url[len('/u/'):] if (not chkuser(username)): continue usernames.add(username.lower()) return usernames
[ "def", "extract_user_mentions", "(", "text", ")", ":", "from", "r2", ".", "lib", ".", "validator", "import", "chkuser", "usernames", "=", "set", "(", ")", "for", "url", "in", "extract_urls_from_markdown", "(", "text", ")", ":", "if", "(", "not", "url", "...
return a set of all usernames mentioned in markdown text .
train
false
26,573
@app.route('/auth/info/firebase', methods=['GET']) @cross_origin(send_wildcard=True) def auth_info_firebase(): return auth_info()
[ "@", "app", ".", "route", "(", "'/auth/info/firebase'", ",", "methods", "=", "[", "'GET'", "]", ")", "@", "cross_origin", "(", "send_wildcard", "=", "True", ")", "def", "auth_info_firebase", "(", ")", ":", "return", "auth_info", "(", ")" ]
auth info with firebase auth .
train
false
26,574
def blueprint_is_module(bp): return isinstance(bp, Module)
[ "def", "blueprint_is_module", "(", "bp", ")", ":", "return", "isinstance", "(", "bp", ",", "Module", ")" ]
used to figure out if something is actually a module .
train
false
26,575
def _GetMsbuildToolsetOfProject(proj_path, spec, version): default_config = _GetDefaultConfiguration(spec) toolset = default_config.get('msbuild_toolset') if ((not toolset) and version.DefaultToolset()): toolset = version.DefaultToolset() return toolset
[ "def", "_GetMsbuildToolsetOfProject", "(", "proj_path", ",", "spec", ",", "version", ")", ":", "default_config", "=", "_GetDefaultConfiguration", "(", "spec", ")", "toolset", "=", "default_config", ".", "get", "(", "'msbuild_toolset'", ")", "if", "(", "(", "not"...
get the platform toolset for the project .
train
false
26,576
def astimezone(obj): if isinstance(obj, six.string_types): return timezone(obj) if isinstance(obj, tzinfo): if ((not hasattr(obj, 'localize')) or (not hasattr(obj, 'normalize'))): raise TypeError('Only timezones from the pytz library are supported') if (obj.zone == 'local'): raise ValueError('Unable to determine the name of the local timezone -- use an explicit timezone instead') return obj if (obj is not None): raise TypeError(('Expected tzinfo, got %s instead' % obj.__class__.__name__))
[ "def", "astimezone", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "six", ".", "string_types", ")", ":", "return", "timezone", "(", "obj", ")", "if", "isinstance", "(", "obj", ",", "tzinfo", ")", ":", "if", "(", "(", "not", "hasattr", ...
interprets an object as a timezone .
train
false
26,577
def patch_ssl(): patch_module('ssl')
[ "def", "patch_ssl", "(", ")", ":", "patch_module", "(", "'ssl'", ")" ]
replace sslsocket object and socket wrapping functions in :mod:ssl with cooperative versions .
train
false
26,579
def bench(func): sys.stdout.write(('%44s ' % format_func(func))) sys.stdout.flush() for i in xrange(3, 10): rounds = (1 << i) t = timer() for x in xrange(rounds): func() if ((timer() - t) >= 0.2): break def _run(): gc.collect() gc.disable() try: t = timer() for x in xrange(rounds): func() return (((timer() - t) / rounds) * 1000) finally: gc.enable() delta = median((_run() for x in xrange(TEST_RUNS))) sys.stdout.write(('%.4f\n' % delta)) sys.stdout.flush() return delta
[ "def", "bench", "(", "func", ")", ":", "sys", ".", "stdout", ".", "write", "(", "(", "'%44s '", "%", "format_func", "(", "func", ")", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "for", "i", "in", "xrange", "(", "3", ",", "10", ")"...
times a single function .
train
true
26,580
def get_selections(pattern=None, state=None): ret = {} cmd = ['dpkg', '--get-selections'] cmd.append((pattern if pattern else '*')) stdout = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) ret = _parse_selections(stdout) if state: return {state: ret.get(state, [])} return ret
[ "def", "get_selections", "(", "pattern", "=", "None", ",", "state", "=", "None", ")", ":", "ret", "=", "{", "}", "cmd", "=", "[", "'dpkg'", ",", "'--get-selections'", "]", "cmd", ".", "append", "(", "(", "pattern", "if", "pattern", "else", "'*'", ")"...
answers to debconf questions for all packages in the following format:: {package: [[question .
train
true
26,581
def pow(x, a): return tf.pow(x, a)
[ "def", "pow", "(", "x", ",", "a", ")", ":", "return", "tf", ".", "pow", "(", "x", ",", "a", ")" ]
same as a ** b .
train
false
26,582
def zeros(shape, dtype=None, name=None): if (dtype is None): dtype = floatx() return variable(np.zeros(shape), dtype, name)
[ "def", "zeros", "(", "shape", ",", "dtype", "=", "None", ",", "name", "=", "None", ")", ":", "if", "(", "dtype", "is", "None", ")", ":", "dtype", "=", "floatx", "(", ")", "return", "variable", "(", "np", ".", "zeros", "(", "shape", ")", ",", "d...
creates a zero-filled :class:cupy .
train
false
26,583
def reg_info(user): if user: section = _winreg.HKEY_CURRENT_USER keypath = 'Software\\SABnzbd' else: section = _winreg.HKEY_LOCAL_MACHINE keypath = 'SYSTEM\\CurrentControlSet\\Services\\SABnzbd' return (section, keypath)
[ "def", "reg_info", "(", "user", ")", ":", "if", "user", ":", "section", "=", "_winreg", ".", "HKEY_CURRENT_USER", "keypath", "=", "'Software\\\\SABnzbd'", "else", ":", "section", "=", "_winreg", ".", "HKEY_LOCAL_MACHINE", "keypath", "=", "'SYSTEM\\\\CurrentControl...
return the reg key for api .
train
false
26,584
def get_functions(): ret = [] for group in __function_groups__: ret.extend(__function_groups__[group]) return ret
[ "def", "get_functions", "(", ")", ":", "ret", "=", "[", "]", "for", "group", "in", "__function_groups__", ":", "ret", ".", "extend", "(", "__function_groups__", "[", "group", "]", ")", "return", "ret" ]
returns a list of all the functions supported by talib .
train
false
26,585
def find_integrator_for(prior, posterior): for (name, obj) in inspect.getmembers(sys.modules[__name__]): if (inspect.isclass(obj) and issubclass(obj, KLIntegrator)): corresponds = (isinstance(prior, obj.prior_class) and isinstance(posterior, obj.posterior_class)) if corresponds: return obj() return None
[ "def", "find_integrator_for", "(", "prior", ",", "posterior", ")", ":", "for", "(", "name", ",", "obj", ")", "in", "inspect", ".", "getmembers", "(", "sys", ".", "modules", "[", "__name__", "]", ")", ":", "if", "(", "inspect", ".", "isclass", "(", "o...
returns a klintegrator instance compatible with prior and posterior .
train
false
26,587
def test_construction(): s3_deleter.Deleter()
[ "def", "test_construction", "(", ")", ":", "s3_deleter", ".", "Deleter", "(", ")" ]
the constructor basically works .
train
false
26,589
def clipConvex(poly0, poly1): res = poly0 for p1idx in xrange(0, len(poly1)): src = res res = [] p0 = poly1[(p1idx - 1)] p1 = poly1[p1idx] for n in xrange(0, len(src)): p = src[n] if (not _isLeft(p0, p1, p)): if _isLeft(p0, p1, src[(n - 1)]): res.append(lineLineIntersection(p0, p1, src[(n - 1)], p)) res.append(p) elif (not _isLeft(p0, p1, src[(n - 1)])): res.append(lineLineIntersection(p0, p1, src[(n - 1)], p)) return numpy.array(res, numpy.float32)
[ "def", "clipConvex", "(", "poly0", ",", "poly1", ")", ":", "res", "=", "poly0", "for", "p1idx", "in", "xrange", "(", "0", ",", "len", "(", "poly1", ")", ")", ":", "src", "=", "res", "res", "=", "[", "]", "p0", "=", "poly1", "[", "(", "p1idx", ...
cut the convex polygon 0 so that it completely fits in convex polygon 1 .
train
false
26,590
def select_ignore_interrupts(iwtd, owtd, ewtd, timeout=None): if (timeout is not None): end_time = (time.time() + timeout) while True: try: return select.select(iwtd, owtd, ewtd, timeout) except InterruptedError: err = sys.exc_info()[1] if (err.args[0] == errno.EINTR): if (timeout is not None): timeout = (end_time - time.time()) if (timeout < 0): return ([], [], []) else: raise
[ "def", "select_ignore_interrupts", "(", "iwtd", ",", "owtd", ",", "ewtd", ",", "timeout", "=", "None", ")", ":", "if", "(", "timeout", "is", "not", "None", ")", ":", "end_time", "=", "(", "time", ".", "time", "(", ")", "+", "timeout", ")", "while", ...
this is a wrapper around select .
train
true
26,591
def function_application(func): if (func not in NUMEXPR_MATH_FUNCS): raise ValueError(("Unsupported mathematical function '%s'" % func)) @with_name(func) def mathfunc(self): if isinstance(self, NumericalExpression): return NumExprFactor('{func}({expr})'.format(func=func, expr=self._expr), self.inputs, dtype=float64_dtype) else: return NumExprFactor('{func}(x_0)'.format(func=func), (self,), dtype=float64_dtype) return mathfunc
[ "def", "function_application", "(", "func", ")", ":", "if", "(", "func", "not", "in", "NUMEXPR_MATH_FUNCS", ")", ":", "raise", "ValueError", "(", "(", "\"Unsupported mathematical function '%s'\"", "%", "func", ")", ")", "@", "with_name", "(", "func", ")", "def...
factory function for producing function application methods for factor subclasses .
train
true
26,592
def snapshot_metadata_get(context, snapshot_id): return IMPL.snapshot_metadata_get(context, snapshot_id)
[ "def", "snapshot_metadata_get", "(", "context", ",", "snapshot_id", ")", ":", "return", "IMPL", ".", "snapshot_metadata_get", "(", "context", ",", "snapshot_id", ")" ]
get all metadata for a snapshot .
train
false
26,594
def make_generic_item(path_obj, **kwargs): return {'sort': kwargs.get('sort'), 'href': path_obj.get_absolute_url(), 'href_translate': path_obj.get_translate_url(), 'title': path_obj.name, 'code': path_obj.code, 'is_disabled': getattr(path_obj, 'disabled', False)}
[ "def", "make_generic_item", "(", "path_obj", ",", "**", "kwargs", ")", ":", "return", "{", "'sort'", ":", "kwargs", ".", "get", "(", "'sort'", ")", ",", "'href'", ":", "path_obj", ".", "get_absolute_url", "(", ")", ",", "'href_translate'", ":", "path_obj",...
template variables for each row in the table .
train
false
26,595
def create_user_preference_serializer(user, preference_key, preference_value): try: existing_user_preference = UserPreference.objects.get(user=user, key=preference_key) except ObjectDoesNotExist: existing_user_preference = None new_data = {'user': user.id, 'key': preference_key, 'value': preference_value} if existing_user_preference: serializer = RawUserPreferenceSerializer(existing_user_preference, data=new_data) else: serializer = RawUserPreferenceSerializer(data=new_data) return serializer
[ "def", "create_user_preference_serializer", "(", "user", ",", "preference_key", ",", "preference_value", ")", ":", "try", ":", "existing_user_preference", "=", "UserPreference", ".", "objects", ".", "get", "(", "user", "=", "user", ",", "key", "=", "preference_key...
creates a serializer for the specified user preference .
train
false
26,597
def ndarray_from_structure(items, fmt, t, flags=0): (memlen, itemsize, ndim, shape, strides, offset) = t return ndarray(items, shape=shape, strides=strides, format=fmt, offset=offset, flags=(ND_WRITABLE | flags))
[ "def", "ndarray_from_structure", "(", "items", ",", "fmt", ",", "t", ",", "flags", "=", "0", ")", ":", "(", "memlen", ",", "itemsize", ",", "ndim", ",", "shape", ",", "strides", ",", "offset", ")", "=", "t", "return", "ndarray", "(", "items", ",", ...
return ndarray from the tuple returned by rand_structure() .
train
false
26,598
def quaternion_real(quaternion): return float(quaternion[0])
[ "def", "quaternion_real", "(", "quaternion", ")", ":", "return", "float", "(", "quaternion", "[", "0", "]", ")" ]
return real part of quaternion .
train
false
26,599
def EncodeAndWriteToStdout(s, encoding='utf-8'): if PY3: sys.stdout.buffer.write(codecs.encode(s, encoding)) else: sys.stdout.write(s.encode(encoding))
[ "def", "EncodeAndWriteToStdout", "(", "s", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "PY3", ":", "sys", ".", "stdout", ".", "buffer", ".", "write", "(", "codecs", ".", "encode", "(", "s", ",", "encoding", ")", ")", "else", ":", "sys", ".", "...
encode the given string and emit to stdout .
train
false
26,600
def Beta(name, alpha, beta): return rv(name, BetaDistribution, (alpha, beta))
[ "def", "Beta", "(", "name", ",", "alpha", ",", "beta", ")", ":", "return", "rv", "(", "name", ",", "BetaDistribution", ",", "(", "alpha", ",", "beta", ")", ")" ]
create a continuous random variable with a beta distribution .
train
false
26,601
def find_conf_file(pid): try: fd = open(('/proc/%s/cmdline' % pid)) except IOError as e: utils.err(('Couchbase (pid %s) went away ? %s' % (pid, e))) return try: config = fd.read().split('config_path')[1].split('"')[1] return config finally: fd.close()
[ "def", "find_conf_file", "(", "pid", ")", ":", "try", ":", "fd", "=", "open", "(", "(", "'/proc/%s/cmdline'", "%", "pid", ")", ")", "except", "IOError", "as", "e", ":", "utils", ".", "err", "(", "(", "'Couchbase (pid %s) went away ? %s'", "%", "(", "pid"...
returns config file for couchbase-server .
train
false
26,602
def MakeExpressionGenerator(depth): if (depth == MAX_DEPTH): (yield '') else: for exprGen in expr_gens: for value in exprGen().generate(depth): (yield value)
[ "def", "MakeExpressionGenerator", "(", "depth", ")", ":", "if", "(", "depth", "==", "MAX_DEPTH", ")", ":", "(", "yield", "''", ")", "else", ":", "for", "exprGen", "in", "expr_gens", ":", "for", "value", "in", "exprGen", "(", ")", ".", "generate", "(", ...
yields all possible expressions .
train
false
26,603
def add_arg_scope(func): @functools.wraps(func) def func_with_args(*args, **kwargs): current_scope = _current_arg_scope() current_args = kwargs key_func = (func.__module__, func.__name__) if (key_func in current_scope): current_args = current_scope[key_func].copy() current_args.update(kwargs) return func(*args, **current_args) _add_op(func) return func_with_args
[ "def", "add_arg_scope", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "func_with_args", "(", "*", "args", ",", "**", "kwargs", ")", ":", "current_scope", "=", "_current_arg_scope", "(", ")", "current_args", "=", "kwargs", ...
decorates a function with args so it can be used within an arg_scope .
train
true
26,604
def sparse_grad(var): assert isinstance(var.owner.op, tensor.AdvancedSubtensor1) ret = var.owner.op.__class__(sparse_grad=True)(*var.owner.inputs) return ret
[ "def", "sparse_grad", "(", "var", ")", ":", "assert", "isinstance", "(", "var", ".", "owner", ".", "op", ",", "tensor", ".", "AdvancedSubtensor1", ")", "ret", "=", "var", ".", "owner", ".", "op", ".", "__class__", "(", "sparse_grad", "=", "True", ")", ...
this function return a new variable whose gradient will be stored in a sparse format instead of dense .
train
false
26,605
def _check_cmdline(data): if (not salt.utils.is_linux()): return True pid = data.get('pid') if (not pid): return False if (not os.path.isdir('/proc')): return True path = os.path.join('/proc/{0}/cmdline'.format(pid)) if (not os.path.isfile(path)): return False try: with salt.utils.fopen(path, 'rb') as fp_: if ('salt' in fp_.read()): return True except (OSError, IOError): return False
[ "def", "_check_cmdline", "(", "data", ")", ":", "if", "(", "not", "salt", ".", "utils", ".", "is_linux", "(", ")", ")", ":", "return", "True", "pid", "=", "data", ".", "get", "(", "'pid'", ")", "if", "(", "not", "pid", ")", ":", "return", "False"...
in some cases where there are an insane number of processes being created on a system a pid can get recycled or assigned to a non-salt process .
train
true
26,608
def get_lines(ex, index_type): def _join_lines(a): i = 0 while (i < len(a)): x = a[i] xend = x[(-1)] xstart = x[0] hit = True while hit: hit = False for j in range((i + 1), len(a)): if (j >= len(a)): break if (a[j][0] == xend): hit = True x.extend(a[j][1:]) xend = x[(-1)] a.pop(j) continue if (a[j][0] == xstart): hit = True a[i] = (reversed(a[j][1:]) + x) x = a[i] xstart = a[i][0] a.pop(j) continue if (a[j][(-1)] == xend): hit = True x.extend(reversed(a[j][:(-1)])) xend = x[(-1)] a.pop(j) continue if (a[j][(-1)] == xstart): hit = True a[i] = (a[j][:(-1)] + x) x = a[i] xstart = x[0] a.pop(j) continue i += 1 return a tids = ex._tids components = tids.components dt = {} for c in components: if (c in dt): continue index_types = c.index_types a = [] for i in range(len(index_types)): if (index_types[i] is index_type): a.append(i) if (len(a) > 2): raise ValueError(('at most two indices of type %s allowed' % index_type)) if (len(a) == 2): dt[c] = a dum = tids.dum lines = [] traces = [] traces1 = [] for (p0, p1, c0, c1) in dum: if (components[c0] not in dt): continue if (c0 == c1): traces.append([c0]) continue ta0 = dt[components[c0]] ta1 = dt[components[c1]] if (p0 not in ta0): continue if (ta0.index(p0) == ta1.index(p1)): raise NotImplementedError ta0 = dt[components[c0]] (b0, b1) = ((c0, c1) if (p0 == ta0[1]) else (c1, c0)) lines1 = lines[:] for line in lines: if (line[(-1)] == b0): if (line[0] == b1): n = line.index(min(line)) traces1.append(line) traces.append((line[n:] + line[:n])) else: line.append(b1) break elif (line[0] == b1): line.insert(0, b0) break else: lines1.append([b0, b1]) lines = [x for x in lines1 if (x not in traces1)] lines = _join_lines(lines) rest = [] for line in lines: for y in line: rest.append(y) for line in traces: for y in line: rest.append(y) rest = [x for x in range(len(components)) if (x not in rest)] return (lines, traces, rest)
[ "def", "get_lines", "(", "ex", ",", "index_type", ")", ":", "def", "_join_lines", "(", "a", ")", ":", "i", "=", "0", "while", "(", "i", "<", "len", "(", "a", ")", ")", ":", "x", "=", "a", "[", "i", "]", "xend", "=", "x", "[", "(", "-", "1...
return lines that begin with name .
train
false
26,609
def create_virtual_cdrom_spec(client_factory, datastore, controller_key, file_path, cdrom_unit_number): config_spec = client_factory.create('ns0:VirtualDeviceConfigSpec') config_spec.operation = 'add' cdrom = client_factory.create('ns0:VirtualCdrom') cdrom_device_backing = client_factory.create('ns0:VirtualCdromIsoBackingInfo') cdrom_device_backing.datastore = datastore cdrom_device_backing.fileName = file_path cdrom.backing = cdrom_device_backing cdrom.controllerKey = controller_key cdrom.unitNumber = cdrom_unit_number cdrom.key = (-1) connectable_spec = client_factory.create('ns0:VirtualDeviceConnectInfo') connectable_spec.startConnected = True connectable_spec.allowGuestControl = False connectable_spec.connected = True cdrom.connectable = connectable_spec config_spec.device = cdrom return config_spec
[ "def", "create_virtual_cdrom_spec", "(", "client_factory", ",", "datastore", ",", "controller_key", ",", "file_path", ",", "cdrom_unit_number", ")", ":", "config_spec", "=", "client_factory", ".", "create", "(", "'ns0:VirtualDeviceConfigSpec'", ")", "config_spec", ".", ...
builds spec for the creation of a new virtual cdrom to the vm .
train
false
26,611
@library.global_function def latest_announcement(): if Announcement.objects.published().count(): return Announcement.objects.published().latest() return None
[ "@", "library", ".", "global_function", "def", "latest_announcement", "(", ")", ":", "if", "Announcement", ".", "objects", ".", "published", "(", ")", ".", "count", "(", ")", ":", "return", "Announcement", ".", "objects", ".", "published", "(", ")", ".", ...
return the latest published announcement or none .
train
false
26,612
def reset(): _runtime.reset()
[ "def", "reset", "(", ")", ":", "_runtime", ".", "reset", "(", ")" ]
reset the cached conf .
train
false
26,613
def _resolve_name(val): return (val if isinstance(val, six.string_types) else val.name)
[ "def", "_resolve_name", "(", "val", ")", ":", "return", "(", "val", "if", "isinstance", "(", "val", ",", "six", ".", "string_types", ")", "else", "val", ".", "name", ")" ]
takes an object or a name and returns the name .
train
false
26,614
def FakeUnlink(path): if os.path.isdir(path): raise OSError(errno.ENOENT, 'Is a directory', path) else: raise OSError(errno.EPERM, 'Operation not permitted', path)
[ "def", "FakeUnlink", "(", "path", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "raise", "OSError", "(", "errno", ".", "ENOENT", ",", "'Is a directory'", ",", "path", ")", "else", ":", "raise", "OSError", "(", "errno", ".", ...
fake version of os .
train
false
26,615
def test_newstyle_unbound_inheritance(): class foo: def func(self): return self class bar(object, foo, ): def barfunc(self): return foo.func(self) a = bar() AreEqual(a.barfunc(), a)
[ "def", "test_newstyle_unbound_inheritance", "(", ")", ":", "class", "foo", ":", "def", "func", "(", "self", ")", ":", "return", "self", "class", "bar", "(", "object", ",", "foo", ",", ")", ":", "def", "barfunc", "(", "self", ")", ":", "return", "foo", ...
verify calling unbound method w/ new-style class on subclass which new-style also inherits from works .
train
false
26,616
def _validate_resource_type(resource_db): resource_type = resource_db.get_resource_type() valid_resource_types = ResourceType.get_valid_values() if (resource_type not in valid_resource_types): raise ValueError(('Permissions cannot be manipulated for a resource of type: %s' % resource_type)) return resource_db
[ "def", "_validate_resource_type", "(", "resource_db", ")", ":", "resource_type", "=", "resource_db", ".", "get_resource_type", "(", ")", "valid_resource_types", "=", "ResourceType", ".", "get_valid_values", "(", ")", "if", "(", "resource_type", "not", "in", "valid_r...
validate that the permissions can be manipulated for the provided resource type .
train
false
26,618
def unicode_ftw(val): val_list = [] for char in val: val_list.append('\x00') val_list.append(pack('B', ord(char))) ret = '' for char in val_list: ret += char return ret
[ "def", "unicode_ftw", "(", "val", ")", ":", "val_list", "=", "[", "]", "for", "char", "in", "val", ":", "val_list", ".", "append", "(", "'\\x00'", ")", "val_list", ".", "append", "(", "pack", "(", "'B'", ",", "ord", "(", "char", ")", ")", ")", "r...
simple unicode slicer .
train
false
26,619
def partition_entropy(subsets): total_count = sum((len(subset) for subset in subsets)) return sum((((data_entropy(subset) * len(subset)) / total_count) for subset in subsets))
[ "def", "partition_entropy", "(", "subsets", ")", ":", "total_count", "=", "sum", "(", "(", "len", "(", "subset", ")", "for", "subset", "in", "subsets", ")", ")", "return", "sum", "(", "(", "(", "(", "data_entropy", "(", "subset", ")", "*", "len", "("...
find the entropy from this partition of data into subsets .
train
false
26,620
def serialize_support_data(request=None, force_is_admin=False): siteconfig = SiteConfiguration.objects.get_current() is_admin = (force_is_admin or ((request is not None) and request.user.is_staff)) return base64.b64encode(u' DCTB '.join([get_install_key(), (u'%d' % is_admin), siteconfig.site.domain, _norm_siteconfig_value(siteconfig, u'site_admin_name'), _norm_siteconfig_value(siteconfig, u'site_admin_email'), get_package_version(), (u'%d' % User.objects.filter(is_active=True).count()), (u'%d' % int(time.mktime(datetime.now().timetuple()))), _norm_siteconfig_value(siteconfig, u'company'), (u'%s.%s.%s' % sys.version_info[:3])]))
[ "def", "serialize_support_data", "(", "request", "=", "None", ",", "force_is_admin", "=", "False", ")", ":", "siteconfig", "=", "SiteConfiguration", ".", "objects", ".", "get_current", "(", ")", "is_admin", "=", "(", "force_is_admin", "or", "(", "(", "request"...
serialize support data into a base64-encoded string .
train
false
26,621
def this_week(t): while 1: tm = time.localtime(t) if (tm.tm_wday == 0): break t -= DAY monday = (tm.tm_year, tm.tm_mon, tm.tm_mday, 0, 0, 0, 0, 0, tm.tm_isdst) return time.mktime(monday)
[ "def", "this_week", "(", "t", ")", ":", "while", "1", ":", "tm", "=", "time", ".", "localtime", "(", "t", ")", "if", "(", "tm", ".", "tm_wday", "==", "0", ")", ":", "break", "t", "-=", "DAY", "monday", "=", "(", "tm", ".", "tm_year", ",", "tm...
return timestamp for start of this week .
train
false
26,623
def DeleteCampaignFeed(client, campaign_feed): campaign_feed_service = client.GetService('CampaignFeedService', 'v201607') operation = {'operand': campaign_feed, 'operator': 'REMOVE'} campaign_feed_service.mutate([operation])
[ "def", "DeleteCampaignFeed", "(", "client", ",", "campaign_feed", ")", ":", "campaign_feed_service", "=", "client", ".", "GetService", "(", "'CampaignFeedService'", ",", "'v201607'", ")", "operation", "=", "{", "'operand'", ":", "campaign_feed", ",", "'operator'", ...
deletes a campaign feed .
train
true
26,624
def _get_line_indent(src, line, indent): if (not (indent or line)): return line idt = [] for c in src: if (c not in [' DCTB ', ' ']): break idt.append(c) return (''.join(idt) + line.strip())
[ "def", "_get_line_indent", "(", "src", ",", "line", ",", "indent", ")", ":", "if", "(", "not", "(", "indent", "or", "line", ")", ")", ":", "return", "line", "idt", "=", "[", "]", "for", "c", "in", "src", ":", "if", "(", "c", "not", "in", "[", ...
indent the line with the source line .
train
false
26,625
def _get_safecommit_count(filename): report_contents = _get_report_contents(filename) if ('No files linted' in report_contents): return 0 file_count_regex = re.compile('^(?P<count>\\d+) violations total', re.MULTILINE) try: validation_count = None for count_match in file_count_regex.finditer(report_contents): if (validation_count is None): validation_count = 0 validation_count += int(count_match.group('count')) return validation_count except ValueError: return None
[ "def", "_get_safecommit_count", "(", "filename", ")", ":", "report_contents", "=", "_get_report_contents", "(", "filename", ")", "if", "(", "'No files linted'", "in", "report_contents", ")", ":", "return", "0", "file_count_regex", "=", "re", ".", "compile", "(", ...
returns the violation count from the safecommit report .
train
false
26,626
def session_list(consul_url=None, return_list=False, **kwargs): ret = {} if (not consul_url): consul_url = _get_config() if (not consul_url): log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if ('dc' in kwargs): query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret
[ "def", "session_list", "(", "consul_url", "=", "None", ",", "return_list", "=", "False", ",", "**", "kwargs", ")", ":", "ret", "=", "{", "}", "if", "(", "not", "consul_url", ")", ":", "consul_url", "=", "_get_config", "(", ")", "if", "(", "not", "con...
used to list sessions .
train
true
26,627
@testing.requires_testing_data def test_io_dipoles(): tempdir = _TempDir() dipole = read_dipole(fname_dip) print dipole out_fname = op.join(tempdir, 'temp.dip') dipole.save(out_fname) dipole_new = read_dipole(out_fname) _compare_dipoles(dipole, dipole_new)
[ "@", "testing", ".", "requires_testing_data", "def", "test_io_dipoles", "(", ")", ":", "tempdir", "=", "_TempDir", "(", ")", "dipole", "=", "read_dipole", "(", "fname_dip", ")", "print", "dipole", "out_fname", "=", "op", ".", "join", "(", "tempdir", ",", "...
test io for .
train
false
26,628
def _rgba2img(rgba): assert (type(rgba) is list) return Image.merge('RGBA', [_arr2img(numpy.round((band * 255.0)).astype(numpy.ubyte)) for band in rgba])
[ "def", "_rgba2img", "(", "rgba", ")", ":", "assert", "(", "type", "(", "rgba", ")", "is", "list", ")", "return", "Image", ".", "merge", "(", "'RGBA'", ",", "[", "_arr2img", "(", "numpy", ".", "round", "(", "(", "band", "*", "255.0", ")", ")", "."...
convert four numeric array objects to pil image .
train
false