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
36,759
def list_formatter(view, values): return u', '.join((text_type(v) for v in values))
[ "def", "list_formatter", "(", "view", ",", "values", ")", ":", "return", "u', '", ".", "join", "(", "(", "text_type", "(", "v", ")", "for", "v", "in", "values", ")", ")" ]
return string with comma separated values .
train
false
36,760
def GetNextResult(Handle): if (os.name == 'nt'): staticLib = ctypes.windll.LoadLibrary('labjackud') pio = ctypes.c_long() pchan = ctypes.c_long() pv = ctypes.c_double() px = ctypes.c_long() pud = ctypes.c_double() ec = staticLib.GetNextResult(Handle, ctypes.byref(pio), ctypes.byref(pchan), ctypes.byref(pv), ctypes.byref(px), ctypes.byref(pud)) if (ec != 0): raise LabJackException(ec) return (pio.value, pchan.value, pv.value, px.value, pud.value) else: raise LabJackException(0, 'Function only supported for Windows')
[ "def", "GetNextResult", "(", "Handle", ")", ":", "if", "(", "os", ".", "name", "==", "'nt'", ")", ":", "staticLib", "=", "ctypes", ".", "windll", ".", "LoadLibrary", "(", "'labjackud'", ")", "pio", "=", "ctypes", ".", "c_long", "(", ")", "pchan", "="...
list all labjack devices of a specific type over a specific connection type .
train
false
36,761
def get_all_volumes(volume_ids=None, filters=None, return_objs=False, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_all_volumes(volume_ids=volume_ids, filters=filters) return (ret if return_objs else [r.id for r in ret]) except boto.exception.BotoServerError as e: log.error(e) return []
[ "def", "get_all_volumes", "(", "volume_ids", "=", "None", ",", "filters", "=", "None", ",", "return_objs", "=", "False", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=...
get a list of all ebs volumes .
train
true
36,762
def output_thread(log, stdout, stderr, timeout_event, is_alive, quit, stop_output_event): readers = [] errors = [] if (stdout is not None): readers.append(stdout) errors.append(stdout) if (stderr is not None): readers.append(stderr) errors.append(stderr) while readers: (outputs, inputs, err) = no_interrupt(select.select, readers, [], errors, 1) for stream in outputs: log.debug('%r ready to be read from', stream) done = stream.read() if done: readers.remove(stream) for stream in err: pass if (timeout_event and timeout_event.is_set()): break if stop_output_event.is_set(): break alive = True while alive: quit.wait(1) (alive, _) = is_alive() if stdout: stdout.close() if stderr: stderr.close()
[ "def", "output_thread", "(", "log", ",", "stdout", ",", "stderr", ",", "timeout_event", ",", "is_alive", ",", "quit", ",", "stop_output_event", ")", ":", "readers", "=", "[", "]", "errors", "=", "[", "]", "if", "(", "stdout", "is", "not", "None", ")", ...
this function is run in a separate thread .
train
false
36,763
@pytest.fixture def webview(qtbot, webpage): QtWebKitWidgets = pytest.importorskip('PyQt5.QtWebKitWidgets') view = QtWebKitWidgets.QWebView() qtbot.add_widget(view) view.page().deleteLater() view.setPage(webpage) view.resize(640, 480) return view
[ "@", "pytest", ".", "fixture", "def", "webview", "(", "qtbot", ",", "webpage", ")", ":", "QtWebKitWidgets", "=", "pytest", ".", "importorskip", "(", "'PyQt5.QtWebKitWidgets'", ")", "view", "=", "QtWebKitWidgets", ".", "QWebView", "(", ")", "qtbot", ".", "add...
get a new qwebview object .
train
false
36,764
def get_random_state(): global _random_states dev = cuda.Device() rs = _random_states.get(dev.id, None) if (rs is None): rs = RandomState(os.getenv('CHAINER_SEED')) _random_states[dev.id] = rs return rs
[ "def", "get_random_state", "(", ")", ":", "global", "_random_states", "dev", "=", "cuda", ".", "Device", "(", ")", "rs", "=", "_random_states", ".", "get", "(", "dev", ".", "id", ",", "None", ")", "if", "(", "rs", "is", "None", ")", ":", "rs", "=",...
gets the state of the random number generator for the current device .
train
false
36,765
def walk_python_files(): def _is_dir_ignored(root, d): if d.startswith(u'.'): return True return (os.path.join(rel_root, d) in IGNORED_DIRS) for (abs_root, dirnames, filenames) in os.walk(PROJECT_ROOT): rel_root = os.path.relpath(abs_root, PROJECT_ROOT) if (rel_root == u'.'): rel_root = u'' dirnames[:] = [d for d in dirnames if (not _is_dir_ignored(rel_root, d))] for filename in filenames: if (not filename.endswith(u'.py')): continue abs_name = os.path.join(abs_root, filename) rel_name = os.path.join(rel_root, filename) (yield (abs_name, rel_name))
[ "def", "walk_python_files", "(", ")", ":", "def", "_is_dir_ignored", "(", "root", ",", "d", ")", ":", "if", "d", ".", "startswith", "(", "u'.'", ")", ":", "return", "True", "return", "(", "os", ".", "path", ".", "join", "(", "rel_root", ",", "d", "...
generator that yields all ckan python source files .
train
false
36,766
def get_fontsize(numrows): thresholds = [25, 50, 75, 100, 125] sizes = [5, 4, 3, 2, 1.5, 1] i = 0 while (numrows > thresholds[i]): i += 1 if (i == len(thresholds)): break return sizes[i]
[ "def", "get_fontsize", "(", "numrows", ")", ":", "thresholds", "=", "[", "25", ",", "50", ",", "75", ",", "100", ",", "125", "]", "sizes", "=", "[", "5", ",", "4", ",", "3", ",", "2", ",", "1.5", ",", "1", "]", "i", "=", "0", "while", "(", ...
returns the fontsize needed to make text fit within each row .
train
false
36,768
def _find_human_readable_labels(synsets, synset_to_human): humans = [] for s in synsets: assert (s in synset_to_human), ('Failed to find: %s' % s) humans.append(synset_to_human[s]) return humans
[ "def", "_find_human_readable_labels", "(", "synsets", ",", "synset_to_human", ")", ":", "humans", "=", "[", "]", "for", "s", "in", "synsets", ":", "assert", "(", "s", "in", "synset_to_human", ")", ",", "(", "'Failed to find: %s'", "%", "s", ")", "humans", ...
build a list of human-readable labels .
train
true
36,771
def _get_iface_info(iface): iface_info = interfaces() if (iface in iface_info.keys()): return (iface_info, False) else: error_msg = 'Interface "{0}" not in available interfaces: "{1}"'.format(iface, '", "'.join(iface_info.keys())) log.error(error_msg) return (None, error_msg)
[ "def", "_get_iface_info", "(", "iface", ")", ":", "iface_info", "=", "interfaces", "(", ")", "if", "(", "iface", "in", "iface_info", ".", "keys", "(", ")", ")", ":", "return", "(", "iface_info", ",", "False", ")", "else", ":", "error_msg", "=", "'Inter...
if iface is available .
train
true
36,772
def _verify_environment(): if (TEST_UUID_VARNAME not in os.environ): logging.error('Unique test ID is missing in env vars, aborting.') sys.exit(1)
[ "def", "_verify_environment", "(", ")", ":", "if", "(", "TEST_UUID_VARNAME", "not", "in", "os", ".", "environ", ")", ":", "logging", ".", "error", "(", "'Unique test ID is missing in env vars, aborting.'", ")", "sys", ".", "exit", "(", "1", ")" ]
verify that the environment is sane and can be used by the test_server .
train
false
36,773
def minkowskiHull(a, b): points = numpy.zeros(((len(a) * len(b)), 2)) for n in xrange(0, len(a)): for m in xrange(0, len(b)): points[((n * len(b)) + m)] = (a[n] + b[m]) return convexHull(points.copy())
[ "def", "minkowskiHull", "(", "a", ",", "b", ")", ":", "points", "=", "numpy", ".", "zeros", "(", "(", "(", "len", "(", "a", ")", "*", "len", "(", "b", ")", ")", ",", "2", ")", ")", "for", "n", "in", "xrange", "(", "0", ",", "len", "(", "a...
calculate the minkowski hull of 2 convex polygons .
train
false
36,775
def unwrap_suite(test): if isinstance(test, unittest.TestCase): (yield test) return subtests = list(test) if (not len(subtests)): (yield test) return for item in itertools.chain.from_iterable(itertools.imap(unwrap_suite, subtests)): (yield item)
[ "def", "unwrap_suite", "(", "test", ")", ":", "if", "isinstance", "(", "test", ",", "unittest", ".", "TestCase", ")", ":", "(", "yield", "test", ")", "return", "subtests", "=", "list", "(", "test", ")", "if", "(", "not", "len", "(", "subtests", ")", ...
attempts to unpack testsuites in order to generate a single stream of terminals .
train
false
36,776
def data2dummy(x, returnall=False): x = x.ravel() groups = np.unique(x) if returnall: return (x[:, None] == groups).astype(int) else: return (x[:, None] == groups).astype(int)[:, :(-1)]
[ "def", "data2dummy", "(", "x", ",", "returnall", "=", "False", ")", ":", "x", "=", "x", ".", "ravel", "(", ")", "groups", "=", "np", ".", "unique", "(", "x", ")", "if", "returnall", ":", "return", "(", "x", "[", ":", ",", "None", "]", "==", "...
convert array of categories to dummy variables by default drops dummy variable for last category uses ravel .
train
false
36,777
def enhance_contrast(image, selem, out=None, mask=None, shift_x=False, shift_y=False): return _apply_scalar_per_pixel(generic_cy._enhance_contrast, image, selem, out=out, mask=mask, shift_x=shift_x, shift_y=shift_y)
[ "def", "enhance_contrast", "(", "image", ",", "selem", ",", "out", "=", "None", ",", "mask", "=", "None", ",", "shift_x", "=", "False", ",", "shift_y", "=", "False", ")", ":", "return", "_apply_scalar_per_pixel", "(", "generic_cy", ".", "_enhance_contrast", ...
enhance contrast of an image .
train
false
36,779
def isotonic_regression(y, sample_weight=None, y_min=None, y_max=None, increasing=True): order = (np.s_[:] if increasing else np.s_[::(-1)]) y = np.array(y[order], dtype=np.float64) if (sample_weight is None): sample_weight = np.ones(len(y), dtype=np.float64) else: sample_weight = np.array(sample_weight[order], dtype=np.float64) _inplace_contiguous_isotonic_regression(y, sample_weight) if ((y_min is not None) or (y_max is not None)): if (y_min is None): y_min = (- np.inf) if (y_max is None): y_max = np.inf np.clip(y, y_min, y_max, y) return y[order]
[ "def", "isotonic_regression", "(", "y", ",", "sample_weight", "=", "None", ",", "y_min", "=", "None", ",", "y_max", "=", "None", ",", "increasing", "=", "True", ")", ":", "order", "=", "(", "np", ".", "s_", "[", ":", "]", "if", "increasing", "else", ...
solve the isotonic regression model:: min sum w[i] ** 2 subject to y_min = y_[1] <= y_[2] .
train
false
36,780
def _generate_property(field, template, fname): source = template.format(field) glbls = {} exec_(source, glbls) return njit(glbls[fname])
[ "def", "_generate_property", "(", "field", ",", "template", ",", "fname", ")", ":", "source", "=", "template", ".", "format", "(", "field", ")", "glbls", "=", "{", "}", "exec_", "(", "source", ",", "glbls", ")", "return", "njit", "(", "glbls", "[", "...
generate simple function that get/set a field of the instance .
train
false
36,781
def start_python_console(namespace=None, noipython=False): if (namespace is None): namespace = {} try: try: if noipython: raise ImportError import IPython try: IPython.embed(user_ns=namespace) except AttributeError: shell = IPython.Shell.IPShellEmbed(argv=[], user_ns=namespace) shell() except ImportError: import code try: import readline except ImportError: pass else: import rlcompleter readline.parse_and_bind('tab:complete') code.interact(banner='', local=namespace) except SystemExit: pass
[ "def", "start_python_console", "(", "namespace", "=", "None", ",", "noipython", "=", "False", ")", ":", "if", "(", "namespace", "is", "None", ")", ":", "namespace", "=", "{", "}", "try", ":", "try", ":", "if", "noipython", ":", "raise", "ImportError", ...
start python console binded to the given namespace .
train
false
36,782
def nameToLabel(mname): labelList = [] word = '' lastWasUpper = False for letter in mname: if (letter.isupper() == lastWasUpper): word += letter elif lastWasUpper: if (len(word) == 1): word += letter else: lastWord = word[:(-1)] firstLetter = word[(-1)] labelList.append(lastWord) word = (firstLetter + letter) else: labelList.append(word) word = letter lastWasUpper = letter.isupper() if labelList: labelList[0] = labelList[0].capitalize() else: return mname.capitalize() labelList.append(word) return ' '.join(labelList)
[ "def", "nameToLabel", "(", "mname", ")", ":", "labelList", "=", "[", "]", "word", "=", "''", "lastWasUpper", "=", "False", "for", "letter", "in", "mname", ":", "if", "(", "letter", ".", "isupper", "(", ")", "==", "lastWasUpper", ")", ":", "word", "+=...
convert a string like a variable name into a slightly more human-friendly string with spaces and capitalized letters .
train
false
36,783
@then('the file "{filename}" should not contain the log records') def step_file_should_not_contain_log_records(context, filename): assert context.table, 'REQUIRE: context.table' context.table.require_columns(['category', 'level', 'message']) format = getattr(context, 'log_record_format', context.config.logging_format) for row in context.table.rows: output = LogRecordTable.make_output_for_row(row, format) context.text = output step_file_should_not_contain_multiline_text(context, filename)
[ "@", "then", "(", "'the file \"{filename}\" should not contain the log records'", ")", "def", "step_file_should_not_contain_log_records", "(", "context", ",", "filename", ")", ":", "assert", "context", ".", "table", ",", "'REQUIRE: context.table'", "context", ".", "table", ...
verifies that the command output contains the specified log records .
train
true
36,785
def _is_viable_phone_number(number): if (len(number) < _MIN_LENGTH_FOR_NSN): return False match = fullmatch(_VALID_PHONE_NUMBER_PATTERN, number) return bool(match)
[ "def", "_is_viable_phone_number", "(", "number", ")", ":", "if", "(", "len", "(", "number", ")", "<", "_MIN_LENGTH_FOR_NSN", ")", ":", "return", "False", "match", "=", "fullmatch", "(", "_VALID_PHONE_NUMBER_PATTERN", ",", "number", ")", "return", "bool", "(", ...
checks to see if a string could possibly be a phone number .
train
true
36,786
def plot_figure(style_label=''): prng = np.random.RandomState(96917002) (fig_width, fig_height) = plt.rcParams['figure.figsize'] fig_size = [(fig_width * 2), (fig_height / 2)] (fig, axes) = plt.subplots(ncols=6, nrows=1, num=style_label, figsize=fig_size, squeeze=True) axes[0].set_ylabel(style_label) plot_scatter(axes[0], prng) plot_image_and_patch(axes[1], prng) plot_bar_graphs(axes[2], prng) plot_colored_circles(axes[3], prng) plot_colored_sinusoidal_lines(axes[4]) plot_histograms(axes[5], prng) fig.tight_layout() return fig
[ "def", "plot_figure", "(", "style_label", "=", "''", ")", ":", "prng", "=", "np", ".", "random", ".", "RandomState", "(", "96917002", ")", "(", "fig_width", ",", "fig_height", ")", "=", "plt", ".", "rcParams", "[", "'figure.figsize'", "]", "fig_size", "=...
setup and plot the demonstration figure with a given style .
train
false
36,789
def equateY(point, returnValue): point.y = returnValue
[ "def", "equateY", "(", "point", ",", "returnValue", ")", ":", "point", ".", "y", "=", "returnValue" ]
get equation for rectangular y .
train
false
36,790
def resource_provider_url(environ, resource_provider): prefix = environ.get('SCRIPT_NAME', '') return ('%s/resource_providers/%s' % (prefix, resource_provider.uuid))
[ "def", "resource_provider_url", "(", "environ", ",", "resource_provider", ")", ":", "prefix", "=", "environ", ".", "get", "(", "'SCRIPT_NAME'", ",", "''", ")", "return", "(", "'%s/resource_providers/%s'", "%", "(", "prefix", ",", "resource_provider", ".", "uuid"...
produce the url for a resource provider .
train
false
36,791
def tornado_sleep(duration): return gen.Task(IOLoop.instance().add_timeout, (time.time() + duration))
[ "def", "tornado_sleep", "(", "duration", ")", ":", "return", "gen", ".", "Task", "(", "IOLoop", ".", "instance", "(", ")", ".", "add_timeout", ",", "(", "time", ".", "time", "(", ")", "+", "duration", ")", ")" ]
sleep without blocking the tornado event loop to use with a gen .
train
false
36,792
def _mplayer_help(short=True): volume = '[{0}9{1}] volume [{0}0{1}]' volume = (volume if short else (volume + ' [{0}q{1}] return')) seek = '[{0}\\u2190{1}] seek [{0}\\u2192{1}]' pause = '[{0}\\u2193{1}] SEEK [{0}\\u2191{1}] [{0}space{1}] pause' if not_utf8_environment: seek = '[{0}<-{1}] seek [{0}->{1}]' pause = '[{0}DN{1}] SEEK [{0}UP{1}] [{0}space{1}] pause' single = '[{0}q{1}] return' next_prev = '[{0}>{1}] next/prev [{0}<{1}]' ret = (single if short else next_prev) fmt = ' %-20s %-20s' lines = (((fmt % (seek, volume)) + '\n') + (fmt % (pause, ret))) return lines.format(c.g, c.w)
[ "def", "_mplayer_help", "(", "short", "=", "True", ")", ":", "volume", "=", "'[{0}9{1}] volume [{0}0{1}]'", "volume", "=", "(", "volume", "if", "short", "else", "(", "volume", "+", "' [{0}q{1}] return'", ")", ")", "seek", "=", "'[{0}\\\\u2190{1}] seek [{0}\\\...
mplayer help .
train
false
36,793
def find_user_config(file_path, max_trials=10): file_path = os.path.normpath(os.path.abspath(os.path.expanduser(file_path))) old_dir = None base_dir = (file_path if os.path.isdir(file_path) else os.path.dirname(file_path)) home_dir = os.path.expanduser('~') while ((base_dir != old_dir) and (old_dir != home_dir) and (max_trials != 0)): config_file = os.path.join(base_dir, '.coafile') if os.path.isfile(config_file): return config_file old_dir = base_dir base_dir = os.path.dirname(old_dir) max_trials = (max_trials - 1) return ''
[ "def", "find_user_config", "(", "file_path", ",", "max_trials", "=", "10", ")", ":", "file_path", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "file_path", ")", ")", ...
uses the filepath to find the most suitable user config file for the file by going down one directory at a time and finding config files there .
train
false
36,795
@hug.not_found() def not_found_handler(): return True
[ "@", "hug", ".", "not_found", "(", ")", "def", "not_found_handler", "(", ")", ":", "return", "True" ]
for testing .
train
false
36,796
def dup_slice(f, m, n, K): k = len(f) if (k >= m): M = (k - m) else: M = 0 if (k >= n): N = (k - n) else: N = 0 f = f[N:M] if (not f): return [] else: return (f + ([K.zero] * m))
[ "def", "dup_slice", "(", "f", ",", "m", ",", "n", ",", "K", ")", ":", "k", "=", "len", "(", "f", ")", "if", "(", "k", ">=", "m", ")", ":", "M", "=", "(", "k", "-", "m", ")", "else", ":", "M", "=", "0", "if", "(", "k", ">=", "n", ")"...
take a continuous subsequence of terms of f in k[x] .
train
false
36,797
def set_scm(scm): if (scm is not None): if (not isinstance(scm, Scm)): raise ValueError(u'The scm must be an instance of Scm, given {}'.format(scm)) global _SCM _SCM = scm
[ "def", "set_scm", "(", "scm", ")", ":", "if", "(", "scm", "is", "not", "None", ")", ":", "if", "(", "not", "isinstance", "(", "scm", ",", "Scm", ")", ")", ":", "raise", "ValueError", "(", "u'The scm must be an instance of Scm, given {}'", ".", "format", ...
sets the pants scm .
train
true
36,798
def _parse_indented_counters(lines): counters = {} group = None group_indent = None for line in lines: if (not ((group is None) or (group_indent is None))): m = _INDENTED_COUNTER_RE.match(line) if (m and (len(m.group('indent')) > group_indent)): counter = m.group('counter') amount = int(m.group('amount')) counters.setdefault(group, {}) counters[group][counter] = amount continue m = _INDENTED_COUNTER_GROUP_RE.match(line) if m: group = m.group('group') group_indent = len(m.group('indent')) elif (not _INDENTED_COUNTERS_MESSAGE_RE.match(line)): log.warning(('unexpected counter line: %s' % line)) return counters
[ "def", "_parse_indented_counters", "(", "lines", ")", ":", "counters", "=", "{", "}", "group", "=", "None", "group_indent", "=", "None", "for", "line", "in", "lines", ":", "if", "(", "not", "(", "(", "group", "is", "None", ")", "or", "(", "group_indent...
parse counters in the indented format output/logged by the hadoop binary .
train
false
36,800
def getSymmetricXLoop(path, vertexes, x): loop = [] for point in path: vector3Index = Vector3Index(len(vertexes), x, point.real, point.imag) loop.append(vector3Index) vertexes.append(vector3Index) return loop
[ "def", "getSymmetricXLoop", "(", "path", ",", "vertexes", ",", "x", ")", ":", "loop", "=", "[", "]", "for", "point", "in", "path", ":", "vector3Index", "=", "Vector3Index", "(", "len", "(", "vertexes", ")", ",", "x", ",", "point", ".", "real", ",", ...
get symmetrix x loop .
train
false
36,803
def GetCampaignFeeds(client, feed, placeholder_type): campaign_feed_service = client.GetService('CampaignFeedService', 'v201609') campaign_feeds = [] more_pages = True selector = {'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], 'predicates': [{'field': 'Status', 'operator': 'EQUALS', 'values': ['ENABLED']}, {'field': 'FeedId', 'operator': 'EQUALS', 'values': [feed['id']]}, {'field': 'PlaceholderTypes', 'operator': 'CONTAINS_ANY', 'values': [placeholder_type]}], 'paging': {'startIndex': 0, 'numberResults': PAGE_SIZE}} while more_pages: page = campaign_feed_service.get(selector) if ('entries' in page): campaign_feeds.extend(page['entries']) selector['paging']['startIndex'] += PAGE_SIZE more_pages = (selector['paging']['startIndex'] < int(page['totalNumEntries'])) return campaign_feeds
[ "def", "GetCampaignFeeds", "(", "client", ",", "feed", ",", "placeholder_type", ")", ":", "campaign_feed_service", "=", "client", ".", "GetService", "(", "'CampaignFeedService'", ",", "'v201609'", ")", "campaign_feeds", "=", "[", "]", "more_pages", "=", "True", ...
get a list of feed item ids used by a campaign via a given campaign feed .
train
true
36,804
def response_message(): return s3_rest_controller('deploy', 'response', custom_crud_buttons={'list_btn': None})
[ "def", "response_message", "(", ")", ":", "return", "s3_rest_controller", "(", "'deploy'", ",", "'response'", ",", "custom_crud_buttons", "=", "{", "'list_btn'", ":", "None", "}", ")" ]
restful crud controller - cant be called response as this clobbbers web2py global! .
train
false
36,805
def get_c_cleanup(r, name, sub): post = ('\n {Py_XDECREF(py_%(name)s);}\n ' % locals()) return (r.type.c_cleanup(name, sub) + post)
[ "def", "get_c_cleanup", "(", "r", ",", "name", ",", "sub", ")", ":", "post", "=", "(", "'\\n {Py_XDECREF(py_%(name)s);}\\n '", "%", "locals", "(", ")", ")", "return", "(", "r", ".", "type", ".", "c_cleanup", "(", "name", ",", "sub", ")", "+", "po...
wrapper around c_cleanup that decrefs py_name .
train
false
36,807
def filter_query_params(url, remove_params): if (not url): return url remove_params = dict((((p, None) if isinstance(p, basestring) else p) for p in remove_params)) parsed_url = urlparse.urlparse(url) parsed_qsl = urlparse.parse_qsl(parsed_url.query, keep_blank_values=True) filtered_qsl = [(p, remove_params.get(p, v)) for (p, v) in parsed_qsl] filtered_qsl = [(p, v) for (p, v) in filtered_qsl if (v is not None)] filtered_url = urlparse.ParseResult(scheme=parsed_url.scheme, netloc=parsed_url.netloc, path=parsed_url.path, params=parsed_url.params, query=urllib.urlencode(filtered_qsl), fragment=parsed_url.fragment) return urlparse.urlunparse(filtered_url)
[ "def", "filter_query_params", "(", "url", ",", "remove_params", ")", ":", "if", "(", "not", "url", ")", ":", "return", "url", "remove_params", "=", "dict", "(", "(", "(", "(", "p", ",", "None", ")", "if", "isinstance", "(", "p", ",", "basestring", ")...
remove all provided parameters from the query section of the url .
train
false
36,808
def action_after_save(form): if request.post_vars.get('search_after_save'): s3task.async('msg_twitter_search', args=[form.vars.id]) session.information = T('The search results should appear shortly - refresh to see them')
[ "def", "action_after_save", "(", "form", ")", ":", "if", "request", ".", "post_vars", ".", "get", "(", "'search_after_save'", ")", ":", "s3task", ".", "async", "(", "'msg_twitter_search'", ",", "args", "=", "[", "form", ".", "vars", ".", "id", "]", ")", ...
schedules twitter query search immediately after save depending on flag .
train
false
36,809
def human_bytes(size): suffices = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB', 'HB'] for suffix in suffices: if (size < 1024): return ('%3.1f %s' % (size, suffix)) size /= 1024.0 return 'big'
[ "def", "human_bytes", "(", "size", ")", ":", "suffices", "=", "[", "'B'", ",", "'KB'", ",", "'MB'", ",", "'GB'", ",", "'TB'", ",", "'PB'", ",", "'EB'", ",", "'ZB'", ",", "'YB'", ",", "'HB'", "]", "for", "suffix", "in", "suffices", ":", "if", "(",...
formats size .
train
false
36,810
def maybe_int(x): try: return int(x) except ValueError: return x
[ "def", "maybe_int", "(", "x", ")", ":", "try", ":", "return", "int", "(", "x", ")", "except", "ValueError", ":", "return", "x" ]
try to convert x to int .
train
false
36,811
def upload_ssh_key(host, username, password, ssh_key=None, ssh_key_file=None, protocol=None, port=None, certificate_verify=False): if (protocol is None): protocol = 'https' if (port is None): port = 443 url = '{0}://{1}:{2}/host/ssh_root_authorized_keys'.format(protocol, host, port) ret = {} result = None try: if ssh_key: result = salt.utils.http.query(url, status=True, text=True, method='PUT', username=username, password=password, data=ssh_key, verify_ssl=certificate_verify) elif ssh_key_file: result = salt.utils.http.query(url, status=True, text=True, method='PUT', username=username, password=password, data_file=ssh_key_file, data_render=False, verify_ssl=certificate_verify) if (result.get('status') == 200): ret['status'] = True else: ret['status'] = False ret['Error'] = result['error'] except Exception as msg: ret['status'] = False ret['Error'] = msg return ret
[ "def", "upload_ssh_key", "(", "host", ",", "username", ",", "password", ",", "ssh_key", "=", "None", ",", "ssh_key_file", "=", "None", ",", "protocol", "=", "None", ",", "port", "=", "None", ",", "certificate_verify", "=", "False", ")", ":", "if", "(", ...
upload an ssh key for root to an esxi host via http put .
train
true
36,813
def parse_freshdesk_event(event_string): data = event_string.replace('{', '').replace('}', '').replace(',', ':').split(':') if (len(data) == 2): return data else: (property, _, from_state, _, to_state) = data return [property, property_name(property, int(from_state)), property_name(property, int(to_state))]
[ "def", "parse_freshdesk_event", "(", "event_string", ")", ":", "data", "=", "event_string", ".", "replace", "(", "'{'", ",", "''", ")", ".", "replace", "(", "'}'", ",", "''", ")", ".", "replace", "(", "','", ",", "':'", ")", ".", "split", "(", "':'",...
these are always of the form "{ticket_action:created}" or "{status:{from:4 .
train
false
36,815
def p_jump_statement_4(t): pass
[ "def", "p_jump_statement_4", "(", "t", ")", ":", "pass" ]
jump_statement : return expression_opt semi .
train
false
36,819
def catch_ioerror(meth): @wraps(meth) def wrapper(self, *args, **kwargs): try: return meth(self, *args, **kwargs) except IOError as (errno, strerror): if (errno == ENOSPC): msg = 'No space left on device' raise ScanMustStopByKnownReasonExc(msg) return wrapper
[ "def", "catch_ioerror", "(", "meth", ")", ":", "@", "wraps", "(", "meth", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "return", "meth", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ...
function to decorate methods in order to catch ioerror exceptions .
train
false
36,820
def test_dict_alias_expansion(): ad = _AliasDict({'bar': False, 'biz': True}, aliases={'foo': ['bar', 'nested'], 'nested': ['biz']}) eq_(ad.expand_aliases(['foo']), ['bar', 'biz'])
[ "def", "test_dict_alias_expansion", "(", ")", ":", "ad", "=", "_AliasDict", "(", "{", "'bar'", ":", "False", ",", "'biz'", ":", "True", "}", ",", "aliases", "=", "{", "'foo'", ":", "[", "'bar'", ",", "'nested'", "]", ",", "'nested'", ":", "[", "'biz'...
alias expansion .
train
false
36,821
def select_nth_child(cache, function, elem): (a, b) = function.parsed_arguments try: num = (cache.sibling_count(elem) + 1) except ValueError: return False if (a == 0): return (num == b) n = ((num - b) / a) return (n.is_integer() and (n > (-1)))
[ "def", "select_nth_child", "(", "cache", ",", "function", ",", "elem", ")", ":", "(", "a", ",", "b", ")", "=", "function", ".", "parsed_arguments", "try", ":", "num", "=", "(", "cache", ".", "sibling_count", "(", "elem", ")", "+", "1", ")", "except",...
implement :nth-child() .
train
false
36,822
def percent_encode_sequence(mapping, safe=SAFE_CHARS): encoded_pairs = [] if hasattr(mapping, 'items'): pairs = mapping.items() else: pairs = mapping for (key, value) in pairs: if isinstance(value, list): for element in value: encoded_pairs.append(('%s=%s' % (percent_encode(key), percent_encode(element)))) else: encoded_pairs.append(('%s=%s' % (percent_encode(key), percent_encode(value)))) return '&'.join(encoded_pairs)
[ "def", "percent_encode_sequence", "(", "mapping", ",", "safe", "=", "SAFE_CHARS", ")", ":", "encoded_pairs", "=", "[", "]", "if", "hasattr", "(", "mapping", ",", "'items'", ")", ":", "pairs", "=", "mapping", ".", "items", "(", ")", "else", ":", "pairs", ...
urlencode a dict or list into a string .
train
false
36,823
def _smw_logdet(s, A, AtA, BI, di, B_logdet): p = A.shape[0] ld = (p * np.log(s)) qmat = (AtA / s) m = BI.shape[0] qmat[0:m, 0:m] += BI ix = np.arange(m, A.shape[1]) qmat[(ix, ix)] += di if sparse.issparse(qmat): qmat = qmat.todense() (_, ld1) = np.linalg.slogdet(qmat) return ((B_logdet + ld) + ld1)
[ "def", "_smw_logdet", "(", "s", ",", "A", ",", "AtA", ",", "BI", ",", "di", ",", "B_logdet", ")", ":", "p", "=", "A", ".", "shape", "[", "0", "]", "ld", "=", "(", "p", "*", "np", ".", "log", "(", "s", ")", ")", "qmat", "=", "(", "AtA", ...
returns the log determinant of s*i + a*b*a .
train
false
36,824
def has_discussion_privileges(user, course_id): roles = get_role_ids(course_id) for role in roles: if (user.id in roles[role]): return True return False
[ "def", "has_discussion_privileges", "(", "user", ",", "course_id", ")", ":", "roles", "=", "get_role_ids", "(", "course_id", ")", "for", "role", "in", "roles", ":", "if", "(", "user", ".", "id", "in", "roles", "[", "role", "]", ")", ":", "return", "Tru...
returns true if the user is privileged in teams discussions for this course .
train
false
36,827
def _build_agg_args(spec): known_np_funcs = {np.min: 'min', np.max: 'max'} chunks = {} aggs = {} finalizers = [] for (result_column, func, input_column) in spec: func = funcname(known_np_funcs.get(func, func)) impls = _build_agg_args_single(result_column, func, input_column) chunks.update(((spec[0], spec) for spec in impls['chunk_funcs'])) aggs.update(((spec[0], spec) for spec in impls['aggregate_funcs'])) finalizers.append(impls['finalizer']) chunks = sorted(chunks.values()) aggs = sorted(aggs.values()) return (chunks, aggs, finalizers)
[ "def", "_build_agg_args", "(", "spec", ")", ":", "known_np_funcs", "=", "{", "np", ".", "min", ":", "'min'", ",", "np", ".", "max", ":", "'max'", "}", "chunks", "=", "{", "}", "aggs", "=", "{", "}", "finalizers", "=", "[", "]", "for", "(", "resul...
create transformation functions for a normalized aggregate spec .
train
false
36,828
def available_access_systems(): asList = [] try: from parser.http import IMDbHTTPAccessSystem asList.append('http') except ImportError: pass try: from parser.mobile import IMDbMobileAccessSystem asList.append('mobile') except ImportError: pass try: from parser.sql import IMDbSqlAccessSystem asList.append('sql') except ImportError: pass return asList
[ "def", "available_access_systems", "(", ")", ":", "asList", "=", "[", "]", "try", ":", "from", "parser", ".", "http", "import", "IMDbHTTPAccessSystem", "asList", ".", "append", "(", "'http'", ")", "except", "ImportError", ":", "pass", "try", ":", "from", "...
return the list of available data access systems .
train
false
36,829
def get_requests_resp_json(resp): if callable(resp.json): return resp.json() return resp.json
[ "def", "get_requests_resp_json", "(", "resp", ")", ":", "if", "callable", "(", "resp", ".", "json", ")", ":", "return", "resp", ".", "json", "(", ")", "return", "resp", ".", "json" ]
kludge so we can use requests versions below or above 1 .
train
false
36,830
def forrt(X, m=None): if (m is None): m = len(X) y = (np.fft.rfft(X, m) / m) return np.r_[(y.real, y[1:(-1)].imag)]
[ "def", "forrt", "(", "X", ",", "m", "=", "None", ")", ":", "if", "(", "m", "is", "None", ")", ":", "m", "=", "len", "(", "X", ")", "y", "=", "(", "np", ".", "fft", ".", "rfft", "(", "X", ",", "m", ")", "/", "m", ")", "return", "np", "...
rfft with order like munro fortt routine .
train
false
36,831
def PBToPy(numpb): return PhoneNumber(country_code=(numpb.country_code if numpb.HasField('country_code') else None), national_number=(numpb.national_number if numpb.HasField('national_number') else None), extension=(numpb.extension if numpb.HasField('extension') else None), italian_leading_zero=(numpb.italian_leading_zero if numpb.HasField('italian_leading_zero') else None), number_of_leading_zeros=(numpb.number_of_leading_zeros if numpb.HasField('number_of_leading_zeros') else None), raw_input=(numpb.raw_input if numpb.HasField('raw_input') else None), country_code_source=(numpb.country_code_source if numpb.HasField('country_code_source') else None), preferred_domestic_carrier_code=(numpb.preferred_domestic_carrier_code if numpb.HasField('preferred_domestic_carrier_code') else None))
[ "def", "PBToPy", "(", "numpb", ")", ":", "return", "PhoneNumber", "(", "country_code", "=", "(", "numpb", ".", "country_code", "if", "numpb", ".", "HasField", "(", "'country_code'", ")", "else", "None", ")", ",", "national_number", "=", "(", "numpb", ".", ...
convert phonenumber_pb2 .
train
true
36,834
def FetchAllEntitites(): ns = list(datastore.Query('__namespace__').Run()) original_ns = namespace_manager.get_namespace() entities_set = [] for namespace in ns: namespace_manager.set_namespace(namespace.key().name()) kinds_list = list(datastore.Query('__kind__').Run()) for kind_entity in kinds_list: ents = list(datastore.Query(kind_entity.key().name()).Run()) for ent in ents: entities_set.append(ent) namespace_manager.set_namespace(original_ns) return entities_set
[ "def", "FetchAllEntitites", "(", ")", ":", "ns", "=", "list", "(", "datastore", ".", "Query", "(", "'__namespace__'", ")", ".", "Run", "(", ")", ")", "original_ns", "=", "namespace_manager", ".", "get_namespace", "(", ")", "entities_set", "=", "[", "]", ...
returns all datastore entities from all namespaces as a list .
train
false
36,835
def media_prev_track(hass): hass.services.call(DOMAIN, SERVICE_MEDIA_PREVIOUS_TRACK)
[ "def", "media_prev_track", "(", "hass", ")", ":", "hass", ".", "services", ".", "call", "(", "DOMAIN", ",", "SERVICE_MEDIA_PREVIOUS_TRACK", ")" ]
press the keyboard button for prev track .
train
false
36,836
def get_object_usage(obj): pages = Page.objects.none() relations = [f for f in type(obj)._meta.get_fields(include_hidden=True) if ((f.one_to_many or f.one_to_one) and f.auto_created)] for relation in relations: related_model = relation.related_model if issubclass(related_model, Page): pages |= Page.objects.filter(id__in=related_model._base_manager.filter(**{relation.field.name: obj.id}).values_list(u'id', flat=True)) else: for f in related_model._meta.fields: if (isinstance(f, ParentalKey) and issubclass(f.rel.to, Page)): pages |= Page.objects.filter(id__in=related_model._base_manager.filter(**{relation.field.name: obj.id}).values_list(f.attname, flat=True)) return pages
[ "def", "get_object_usage", "(", "obj", ")", ":", "pages", "=", "Page", ".", "objects", ".", "none", "(", ")", "relations", "=", "[", "f", "for", "f", "in", "type", "(", "obj", ")", ".", "_meta", ".", "get_fields", "(", "include_hidden", "=", "True", ...
returns a queryset of pages that link to a particular object .
train
false
36,837
def get_class_from_string(path, default=None): try: from importlib import import_module except ImportError: from django.utils.importlib import import_module i = path.rfind('.') (module, attr) = (path[:i], path[(i + 1):]) mod = import_module(module) try: return getattr(mod, attr) except AttributeError: if default: return default else: raise ImportError('Cannot import name {} (from {})'.format(attr, mod))
[ "def", "get_class_from_string", "(", "path", ",", "default", "=", "None", ")", ":", "try", ":", "from", "importlib", "import", "import_module", "except", "ImportError", ":", "from", "django", ".", "utils", ".", "importlib", "import", "import_module", "i", "=",...
return the class specified by the string .
train
false
36,838
def translate_url(url, lang_code): parsed = urlsplit(url) try: match = resolve(parsed.path) except Resolver404: pass else: to_be_reversed = (('%s:%s' % (match.namespace, match.url_name)) if match.namespace else match.url_name) with override(lang_code): try: url = reverse(to_be_reversed, args=match.args, kwargs=match.kwargs) except NoReverseMatch: pass else: url = urlunsplit((parsed.scheme, parsed.netloc, url, parsed.query, parsed.fragment)) return url
[ "def", "translate_url", "(", "url", ",", "lang_code", ")", ":", "parsed", "=", "urlsplit", "(", "url", ")", "try", ":", "match", "=", "resolve", "(", "parsed", ".", "path", ")", "except", "Resolver404", ":", "pass", "else", ":", "to_be_reversed", "=", ...
translates the current url for the given language code .
train
false
36,839
@pytest.mark.network def test_install_wheel_with_target(script, data): script.pip('install', 'wheel') target_dir = (script.scratch_path / 'target') result = script.pip('install', 'simple.dist==0.1', '-t', target_dir, '--no-index', ('--find-links=' + data.find_links)) assert (((Path('scratch') / 'target') / 'simpledist') in result.files_created), str(result)
[ "@", "pytest", ".", "mark", ".", "network", "def", "test_install_wheel_with_target", "(", "script", ",", "data", ")", ":", "script", ".", "pip", "(", "'install'", ",", "'wheel'", ")", "target_dir", "=", "(", "script", ".", "scratch_path", "/", "'target'", ...
test installing a wheel using pip install --target .
train
false
36,840
def rest_api_context_factory(ca_certificate, control_credential): return _ControlServiceContextFactory(ca_certificate, control_credential, 'user-')
[ "def", "rest_api_context_factory", "(", "ca_certificate", ",", "control_credential", ")", ":", "return", "_ControlServiceContextFactory", "(", "ca_certificate", ",", "control_credential", ",", "'user-'", ")" ]
create a context factory that validates rest api clients connecting to the control service .
train
false
36,841
def revoke_certs_by_user(user_id): admin = context.get_admin_context() for cert in db.certificate_get_all_by_user(admin, user_id): revoke_cert(cert['project_id'], cert['file_name'])
[ "def", "revoke_certs_by_user", "(", "user_id", ")", ":", "admin", "=", "context", ".", "get_admin_context", "(", ")", "for", "cert", "in", "db", ".", "certificate_get_all_by_user", "(", "admin", ",", "user_id", ")", ":", "revoke_cert", "(", "cert", "[", "'pr...
revoke all user certs .
train
false
36,842
def _ParseOutputSpec(output_spec): pattern = re.compile('(O)(0|1|2)(l|s|c)(\\d+)') m = pattern.match(output_spec) if (m is None): raise ValueError(('Failed to parse output spec:' + output_spec)) out_dims = int(m.group(2)) out_func = m.group(3) if ((out_func == 'c') and (out_dims != 1)): raise ValueError('CTC can only be used with a 1-D sequence!') num_classes = int(m.group(4)) return (out_dims, out_func, num_classes)
[ "def", "_ParseOutputSpec", "(", "output_spec", ")", ":", "pattern", "=", "re", ".", "compile", "(", "'(O)(0|1|2)(l|s|c)(\\\\d+)'", ")", "m", "=", "pattern", ".", "match", "(", "output_spec", ")", "if", "(", "m", "is", "None", ")", ":", "raise", "ValueError...
parses the output spec .
train
false
36,843
def max_seeds_from_threads(threads): seeds = 0 for background in threads: log.debug((u'Coming up next: %s' % background.tracker)) background.join() seeds = max(seeds, background.tracker_seeds) log.debug((u'Current hightest number of seeds found: %s' % seeds)) return seeds
[ "def", "max_seeds_from_threads", "(", "threads", ")", ":", "seeds", "=", "0", "for", "background", "in", "threads", ":", "log", ".", "debug", "(", "(", "u'Coming up next: %s'", "%", "background", ".", "tracker", ")", ")", "background", ".", "join", "(", ")...
joins the threads and returns the maximum seeds found from any of them .
train
false
36,844
def get_thunk_type_set(): it_types = [] i_types = [] j = 0 getter_code = ' if (0) {}' for (I_typenum, I_type) in I_TYPES: piece = '\n else if (I_typenum == %(I_typenum)s) {\n if (T_typenum == -1) { return %(j)s; }' getter_code += (piece % dict(I_typenum=I_typenum, j=j)) i_types.append((j, I_typenum, None, I_type, None)) j += 1 for (T_typenum, T_type) in T_TYPES: piece = '\n else if (T_typenum == %(T_typenum)s) { return %(j)s; }' getter_code += (piece % dict(T_typenum=T_typenum, j=j)) it_types.append((j, I_typenum, T_typenum, I_type, T_type)) j += 1 getter_code += '\n }' return (i_types, it_types, (GET_THUNK_CASE_TEMPLATE % dict(content=getter_code)))
[ "def", "get_thunk_type_set", "(", ")", ":", "it_types", "=", "[", "]", "i_types", "=", "[", "]", "j", "=", "0", "getter_code", "=", "' if (0) {}'", "for", "(", "I_typenum", ",", "I_type", ")", "in", "I_TYPES", ":", "piece", "=", "'\\n else if (I_...
get a list containing cartesian product of data types .
train
false
36,846
def get_default_volume_size(dataset_backend_configuration): default_volume_size = GiB(1) if (dataset_backend_configuration.get('auth_plugin') == 'rackspace'): default_volume_size = RACKSPACE_MINIMUM_VOLUME_SIZE return int(default_volume_size.to_Byte().value)
[ "def", "get_default_volume_size", "(", "dataset_backend_configuration", ")", ":", "default_volume_size", "=", "GiB", "(", "1", ")", "if", "(", "dataset_backend_configuration", ".", "get", "(", "'auth_plugin'", ")", "==", "'rackspace'", ")", ":", "default_volume_size",...
calculate the default volume size for the given dataset backend configuration .
train
false
36,847
def has_handshake_cowpatty(target, capfile, nonstrict=True): if (not program_exists('cowpatty')): return False cmd = ['cowpatty', '-r', capfile, '-s', target.ssid, '-c'] if nonstrict: cmd.append('-2') proc = Popen(cmd, stdout=PIPE, stderr=DN) proc.wait() response = proc.communicate()[0] if (response.find('incomplete four-way handshake exchange') != (-1)): return False elif (response.find('Unsupported or unrecognized pcap file.') != (-1)): return False elif (response.find('Unable to open capture file: Success') != (-1)): return False return True
[ "def", "has_handshake_cowpatty", "(", "target", ",", "capfile", ",", "nonstrict", "=", "True", ")", ":", "if", "(", "not", "program_exists", "(", "'cowpatty'", ")", ")", ":", "return", "False", "cmd", "=", "[", "'cowpatty'", ",", "'-r'", ",", "capfile", ...
uses cowpatty to check for a handshake .
train
false
36,848
def comparefloats(a, b): aa = a bb = b if ((aa.dtype.name == 'float32') or (bb.dtype.name == 'float32')): precision = 1e-06 else: precision = 1e-16 precision = 1e-05 diff = np.absolute((aa - bb)) mask0 = (aa == 0) masknz = (aa != 0.0) if np.any(mask0): if (diff[mask0].max() != 0.0): return False if np.any(masknz): if ((diff[masknz] / np.absolute(aa[masknz])).max() > precision): return False return True
[ "def", "comparefloats", "(", "a", ",", "b", ")", ":", "aa", "=", "a", "bb", "=", "b", "if", "(", "(", "aa", ".", "dtype", ".", "name", "==", "'float32'", ")", "or", "(", "bb", ".", "dtype", ".", "name", "==", "'float32'", ")", ")", ":", "prec...
compare two float scalars or arrays and see if they are consistent consistency is determined ensuring the difference is less than the expected amount .
train
false
36,850
@pick_context_manager_reader def flavor_access_get_by_flavor_id(context, flavor_id): instance_type_id_subq = _flavor_get_id_from_flavor_query(context, flavor_id) access_refs = _flavor_access_query(context).filter_by(instance_type_id=instance_type_id_subq).all() return access_refs
[ "@", "pick_context_manager_reader", "def", "flavor_access_get_by_flavor_id", "(", "context", ",", "flavor_id", ")", ":", "instance_type_id_subq", "=", "_flavor_get_id_from_flavor_query", "(", "context", ",", "flavor_id", ")", "access_refs", "=", "_flavor_access_query", "(",...
get flavor access by flavor id .
train
false
36,851
def autolink(text, trim_url_limit=None, nofollow=False): trim_url = (lambda x, limit=trim_url_limit: (((limit is not None) and (x[:limit] + (((len(x) >= limit) and '...') or ''))) or x)) words = word_split_re.split(text) nofollow_attr = ((nofollow and ' rel="nofollow"') or '') for (i, word) in enumerate(words): match = punctuation_re.match(word) if match: (lead, middle, trail) = match.groups() if (middle.startswith('www.') or (('@' not in middle) and (not middle.startswith('http://')) and (not middle.startswith('https://')) and (len(middle) > 0) and (middle[0] in (string.letters + string.digits)) and (middle.endswith('.org') or middle.endswith('.net') or middle.endswith('.com')))): middle = ('<a href="http://%s"%s target="_blank">%s</a>' % (middle, nofollow_attr, trim_url(middle))) if (middle.startswith('http://') or middle.startswith('https://')): middle = ('<a href="%s"%s target="_blank">%s</a>' % (middle, nofollow_attr, trim_url(middle))) if (('@' in middle) and (not middle.startswith('www.')) and (not (':' in middle)) and simple_email_re.match(middle)): middle = ('<a href="mailto:%s">%s</a>' % (middle, middle)) if (((lead + middle) + trail) != word): words[i] = ((lead + middle) + trail) return ''.join(words)
[ "def", "autolink", "(", "text", ",", "trim_url_limit", "=", "None", ",", "nofollow", "=", "False", ")", ":", "trim_url", "=", "(", "lambda", "x", ",", "limit", "=", "trim_url_limit", ":", "(", "(", "(", "limit", "is", "not", "None", ")", "and", "(", ...
turn any urls into links .
train
false
36,852
def list_path_traversal(path): out = [path] (head, tail) = os.path.split(path) if (tail == ''): out = [head] (head, tail) = os.path.split(head) while (head != out[0]): out.insert(0, head) (head, tail) = os.path.split(head) return out
[ "def", "list_path_traversal", "(", "path", ")", ":", "out", "=", "[", "path", "]", "(", "head", ",", "tail", ")", "=", "os", ".", "path", ".", "split", "(", "path", ")", "if", "(", "tail", "==", "''", ")", ":", "out", "=", "[", "head", "]", "...
returns a full list of directories leading up to .
train
true
36,853
def assert_in_html(member, container, **kwargs): member = markupsafe.escape(member) return assert_in(member, container, **kwargs)
[ "def", "assert_in_html", "(", "member", ",", "container", ",", "**", "kwargs", ")", ":", "member", "=", "markupsafe", ".", "escape", "(", "member", ")", "return", "assert_in", "(", "member", ",", "container", ",", "**", "kwargs", ")" ]
looks for the specified member in markupsafe-escaped html output .
train
false
36,854
def demo_verbose_rule_format(): postag(ruleformat='verbose')
[ "def", "demo_verbose_rule_format", "(", ")", ":", "postag", "(", "ruleformat", "=", "'verbose'", ")" ]
exemplify rule .
train
false
36,855
def dup_mul_ground(f, c, K): if ((not c) or (not f)): return [] else: return [(cf * c) for cf in f]
[ "def", "dup_mul_ground", "(", "f", ",", "c", ",", "K", ")", ":", "if", "(", "(", "not", "c", ")", "or", "(", "not", "f", ")", ")", ":", "return", "[", "]", "else", ":", "return", "[", "(", "cf", "*", "c", ")", "for", "cf", "in", "f", "]" ...
multiply f by a constant value in k[x] .
train
false
36,856
def test_rl_yank_no_text(lineedit, bridge): lineedit.clear() bridge.rl_yank() assert (lineedit.aug_text() == '|')
[ "def", "test_rl_yank_no_text", "(", "lineedit", ",", "bridge", ")", ":", "lineedit", ".", "clear", "(", ")", "bridge", ".", "rl_yank", "(", ")", "assert", "(", "lineedit", ".", "aug_text", "(", ")", "==", "'|'", ")" ]
test yank without having deleted anything .
train
false
36,860
def dt_action(row=1, action=None, column=1, tableID='datatable'): config = current.test_config browser = config.browser if action: button = (".//*[@id='%s']/tbody/tr[%s]/td[%s]/a[contains(text(),'%s')]" % (tableID, row, column, action)) else: button = (".//*[@id='%s']/tbody/tr[%s]/td[%s]/a" % (tableID, row, column)) giveup = 0.0 sleeptime = 0.2 while (giveup < 10.0): try: element = browser.find_element_by_xpath(button) url = element.get_attribute('href') if url: browser.get(url) return True except Exception as inst: print ('%s with %s' % (type(inst), button)) time.sleep(sleeptime) giveup += sleeptime return False
[ "def", "dt_action", "(", "row", "=", "1", ",", "action", "=", "None", ",", "column", "=", "1", ",", "tableID", "=", "'datatable'", ")", ":", "config", "=", "current", ".", "test_config", "browser", "=", "config", ".", "browser", "if", "action", ":", ...
click the action button in the datatable .
train
false
36,861
def _process_bti_headshape(fname, convert=True, use_hpi=True): (idx_points, dig_points) = _read_head_shape(fname) if convert: ctf_head_t = _get_ctf_head_to_head_t(idx_points) else: ctf_head_t = Transform('ctf_head', 'ctf_head') if (dig_points is not None): all_points = np.r_[(idx_points, dig_points)] else: all_points = idx_points if convert: all_points = _convert_hs_points(all_points, ctf_head_t) dig = _points_to_dig(all_points, len(idx_points), use_hpi) return (dig, ctf_head_t)
[ "def", "_process_bti_headshape", "(", "fname", ",", "convert", "=", "True", ",", "use_hpi", "=", "True", ")", ":", "(", "idx_points", ",", "dig_points", ")", "=", "_read_head_shape", "(", "fname", ")", "if", "convert", ":", "ctf_head_t", "=", "_get_ctf_head_...
read index points and dig points from bti head shape file .
train
false
36,862
def excel_datetime(timestamp, epoch=datetime.datetime.fromordinal(693594)): return (epoch + datetime.timedelta(timestamp))
[ "def", "excel_datetime", "(", "timestamp", ",", "epoch", "=", "datetime", ".", "datetime", ".", "fromordinal", "(", "693594", ")", ")", ":", "return", "(", "epoch", "+", "datetime", ".", "timedelta", "(", "timestamp", ")", ")" ]
return datetime object from timestamp in excel serial format .
train
true
36,864
def manipulator_validator_unique(f, opts, self, field_data, all_data): lookup_type = f.get_validator_unique_lookup_type() try: old_obj = self.manager.get(**{lookup_type: field_data}) except ObjectDoesNotExist: return if (getattr(self, 'original_object', None) and (self.original_object._get_pk_val() == old_obj._get_pk_val())): return raise validators.ValidationError, (gettext('%(optname)s with this %(fieldname)s already exists.') % {'optname': capfirst(opts.verbose_name), 'fieldname': f.verbose_name})
[ "def", "manipulator_validator_unique", "(", "f", ",", "opts", ",", "self", ",", "field_data", ",", "all_data", ")", ":", "lookup_type", "=", "f", ".", "get_validator_unique_lookup_type", "(", ")", "try", ":", "old_obj", "=", "self", ".", "manager", ".", "get...
validates that the value is unique for this field .
train
false
36,865
def ids2str(ids): return ('(%s)' % ','.join((str(i) for i in ids)))
[ "def", "ids2str", "(", "ids", ")", ":", "return", "(", "'(%s)'", "%", "','", ".", "join", "(", "(", "str", "(", "i", ")", "for", "i", "in", "ids", ")", ")", ")" ]
given a list of integers .
train
false
36,867
def _EscapeCommandLineArgumentForMSBuild(s): def _Replace(match): return ((((len(match.group(1)) / 2) * 4) * '\\') + '\\"') s = quote_replacer_regex2.sub(_Replace, s) return s
[ "def", "_EscapeCommandLineArgumentForMSBuild", "(", "s", ")", ":", "def", "_Replace", "(", "match", ")", ":", "return", "(", "(", "(", "(", "len", "(", "match", ".", "group", "(", "1", ")", ")", "/", "2", ")", "*", "4", ")", "*", "'\\\\'", ")", "...
escapes a windows command-line argument for use by msbuild .
train
false
36,868
@hook.command def lower(text): return text.lower()
[ "@", "hook", ".", "command", "def", "lower", "(", "text", ")", ":", "return", "text", ".", "lower", "(", ")" ]
converts a string into all lowercase .
train
false
36,870
@register.inclusion_tag('test_incl_tag_current_app.html', takes_context=True) def inclusion_tag_current_app(context): return {}
[ "@", "register", ".", "inclusion_tag", "(", "'test_incl_tag_current_app.html'", ",", "takes_context", "=", "True", ")", "def", "inclusion_tag_current_app", "(", "context", ")", ":", "return", "{", "}" ]
expected inclusion_tag_current_app __doc__ .
train
false
36,871
def text_to_bytes_and_warn(label, obj): if isinstance(obj, text_type): warn(_TEXT_WARNING.format(label), category=DeprecationWarning, stacklevel=3) return obj.encode('utf-8') return obj
[ "def", "text_to_bytes_and_warn", "(", "label", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "text_type", ")", ":", "warn", "(", "_TEXT_WARNING", ".", "format", "(", "label", ")", ",", "category", "=", "DeprecationWarning", ",", "stacklevel", ...
if obj is text .
train
true
36,872
def getIsQuoted(word): if (len(word) < 2): return False firstCharacter = word[0] lastCharacter = word[(-1)] if ((firstCharacter == '"') and (lastCharacter == '"')): return True return ((firstCharacter == "'") and (lastCharacter == "'"))
[ "def", "getIsQuoted", "(", "word", ")", ":", "if", "(", "len", "(", "word", ")", "<", "2", ")", ":", "return", "False", "firstCharacter", "=", "word", "[", "0", "]", "lastCharacter", "=", "word", "[", "(", "-", "1", ")", "]", "if", "(", "(", "f...
determine if the word is quoted .
train
false
36,873
@event(u'manager.daemon.started') def setup_scheduler(manager): global scheduler if (logging.getLogger().getEffectiveLevel() > logging.DEBUG): logging.getLogger(u'apscheduler').setLevel(logging.WARNING) jobstores = {u'default': SQLAlchemyJobStore(engine=manager.engine, metadata=Base.metadata)} job_defaults = {u'coalesce': True, u'misfire_grace_time': ((60 * 60) * 24)} try: timezone = tzlocal.get_localzone() if (timezone.zone == u'local'): timezone = None except pytz.UnknownTimeZoneError: timezone = None except struct.error as e: log.warning(u'Hiding exception from tzlocal: %s', e) timezone = None if (not timezone): log.info(u'Local timezone name could not be determined. Scheduler will display times in UTC for any logmessages. To resolve this set up /etc/timezone with correct time zone name.') timezone = pytz.utc scheduler = BackgroundScheduler(jobstores=jobstores, job_defaults=job_defaults, timezone=timezone) setup_jobs(manager)
[ "@", "event", "(", "u'manager.daemon.started'", ")", "def", "setup_scheduler", "(", "manager", ")", ":", "global", "scheduler", "if", "(", "logging", ".", "getLogger", "(", ")", ".", "getEffectiveLevel", "(", ")", ">", "logging", ".", "DEBUG", ")", ":", "l...
configure and start apscheduler .
train
false
36,875
def rotate_left(x, y): if (len(x) == 0): return [] y = (y % len(x)) return (x[y:] + x[:y])
[ "def", "rotate_left", "(", "x", ",", "y", ")", ":", "if", "(", "len", "(", "x", ")", "==", "0", ")", ":", "return", "[", "]", "y", "=", "(", "y", "%", "len", "(", "x", ")", ")", "return", "(", "x", "[", "y", ":", "]", "+", "x", "[", "...
left rotates a list x by the number of steps specified in y .
train
false
36,876
def _m_disable(): if HAS_UPSTART: return MagicMock(return_value=True) else: return MagicMock(return_value=False)
[ "def", "_m_disable", "(", ")", ":", "if", "HAS_UPSTART", ":", "return", "MagicMock", "(", "return_value", "=", "True", ")", "else", ":", "return", "MagicMock", "(", "return_value", "=", "False", ")" ]
mock _upstart_disable method .
train
false
36,878
def write_properties(props): root = Element(('{%s}coreProperties' % COREPROPS_NS)) for attr in ('creator', 'title', 'description', 'subject', 'identifier', 'language'): SubElement(root, ('{%s}%s' % (DCORE_NS, attr))).text = getattr(props, attr) for attr in ('created', 'modified'): value = datetime_to_W3CDTF(getattr(props, attr)) SubElement(root, ('{%s}%s' % (DCTERMS_NS, attr)), {('{%s}type' % XSI_NS): ('%s:W3CDTF' % DCTERMS_PREFIX)}).text = value for attr in ('lastModifiedBy', 'category', 'contentStatus', 'version', 'revision', 'keywords'): SubElement(root, ('{%s}%s' % (COREPROPS_NS, attr))).text = getattr(props, attr) if (props.lastPrinted is not None): SubElement(root, ('{%s}lastPrinted' % COREPROPS_NS)).text = datetime_to_W3CDTF(props.lastPrinted) return tostring(root)
[ "def", "write_properties", "(", "props", ")", ":", "root", "=", "Element", "(", "(", "'{%s}coreProperties'", "%", "COREPROPS_NS", ")", ")", "for", "attr", "in", "(", "'creator'", ",", "'title'", ",", "'description'", ",", "'subject'", ",", "'identifier'", ",...
write the core properties to xml .
train
false
36,881
@cache_permission def can_overwrite_translation(user, project): return check_permission(user, project, 'trans.overwrite_translation')
[ "@", "cache_permission", "def", "can_overwrite_translation", "(", "user", ",", "project", ")", ":", "return", "check_permission", "(", "user", ",", "project", ",", "'trans.overwrite_translation'", ")" ]
checks whether user can overwrite translation on given project .
train
false
36,884
def is_switchport_default(existing): c1 = (existing['access_vlan'] == '1') c2 = (existing['native_vlan'] == '1') c3 = (existing['trunk_vlans'] == '1-4094') c4 = (existing['mode'] == 'access') default = (c1 and c2 and c3 and c4) return default
[ "def", "is_switchport_default", "(", "existing", ")", ":", "c1", "=", "(", "existing", "[", "'access_vlan'", "]", "==", "'1'", ")", "c2", "=", "(", "existing", "[", "'native_vlan'", "]", "==", "'1'", ")", "c3", "=", "(", "existing", "[", "'trunk_vlans'",...
determines if switchport has a default config based on mode args: existing : existing switchport configuration from ansible mod returns: boolean: true if switchport has oob layer 2 config .
train
false
36,885
def service_for_pool(test, pool): service = VolumeService(FilePath(test.mktemp()), pool, None) service.startService() test.addCleanup(service.stopService) return service
[ "def", "service_for_pool", "(", "test", ",", "pool", ")", ":", "service", "=", "VolumeService", "(", "FilePath", "(", "test", ".", "mktemp", "(", ")", ")", ",", "pool", ",", "None", ")", "service", ".", "startService", "(", ")", "test", ".", "addCleanu...
create a volumeservice wrapping a pool suitable for use in tests .
train
false
36,886
def create_clones(config, model_fn, args=None, kwargs=None): clones = [] args = (args or []) kwargs = (kwargs or {}) with slim.arg_scope([slim.model_variable, slim.variable], device=config.variables_device()): for i in range(0, config.num_clones): with tf.name_scope(config.clone_scope(i)) as clone_scope: clone_device = config.clone_device(i) with tf.device(clone_device): with tf.variable_scope(tf.get_variable_scope(), reuse=(True if (i > 0) else None)): outputs = model_fn(*args, **kwargs) clones.append(Clone(outputs, clone_scope, clone_device)) return clones
[ "def", "create_clones", "(", "config", ",", "model_fn", ",", "args", "=", "None", ",", "kwargs", "=", "None", ")", ":", "clones", "=", "[", "]", "args", "=", "(", "args", "or", "[", "]", ")", "kwargs", "=", "(", "kwargs", "or", "{", "}", ")", "...
creates multiple clones according to config using a model_fn .
train
false
36,887
def _PopConnection(): assert (len(_thread_local.connection_stack) >= 2) return _thread_local.connection_stack.pop()
[ "def", "_PopConnection", "(", ")", ":", "assert", "(", "len", "(", "_thread_local", ".", "connection_stack", ")", ">=", "2", ")", "return", "_thread_local", ".", "connection_stack", ".", "pop", "(", ")" ]
internal method to restores the previous connection .
train
false
36,888
def update_incompatible_versions(sender, instance, **kw): try: if (not (instance.addon.type == amo.ADDON_EXTENSION)): return except ObjectDoesNotExist: return from olympia.addons import tasks tasks.update_incompatible_appversions.delay([instance.id])
[ "def", "update_incompatible_versions", "(", "sender", ",", "instance", ",", "**", "kw", ")", ":", "try", ":", "if", "(", "not", "(", "instance", ".", "addon", ".", "type", "==", "amo", ".", "ADDON_EXTENSION", ")", ")", ":", "return", "except", "ObjectDoe...
when a new version is added or deleted .
train
false
36,889
def block_db_access(service_name): class NoDB(object, ): def __getattr__(self, attr): return self def __call__(self, *args, **kwargs): stacktrace = ''.join(traceback.format_stack()) LOG.error(_LE('No db access allowed in %(service_name)s: %(stacktrace)s'), dict(service_name=service_name, stacktrace=stacktrace)) raise exception.DBNotAllowed(service_name) nova.db.api.IMPL = NoDB()
[ "def", "block_db_access", "(", "service_name", ")", ":", "class", "NoDB", "(", "object", ",", ")", ":", "def", "__getattr__", "(", "self", ",", "attr", ")", ":", "return", "self", "def", "__call__", "(", "self", ",", "*", "args", ",", "**", "kwargs", ...
blocks nova db access .
train
false
36,890
def net_if_stats(): names = net_io_counters().keys() ret = {} for name in names: (isup, duplex, speed, mtu) = cext_posix.net_if_stats(name) if hasattr(_common, 'NicDuplex'): duplex = _common.NicDuplex(duplex) ret[name] = _common.snicstats(isup, duplex, speed, mtu) return ret
[ "def", "net_if_stats", "(", ")", ":", "names", "=", "net_io_counters", "(", ")", ".", "keys", "(", ")", "ret", "=", "{", "}", "for", "name", "in", "names", ":", "(", "isup", ",", "duplex", ",", "speed", ",", "mtu", ")", "=", "cext_posix", ".", "n...
return information about each nic installed on the system as a dictionary whose keys are the nic names and value is a namedtuple with the following fields: - isup: whether the interface is up - duplex: can be either nic_duplex_full .
train
false
36,892
def _wait_for_completion(conn, promise, wait_timeout, msg): if (not promise): return wait_timeout = (time.time() + wait_timeout) while (wait_timeout > time.time()): time.sleep(5) operation_result = conn.get_request(request_id=promise['requestId'], status=True) if (operation_result['metadata']['status'] == 'DONE'): return elif (operation_result['metadata']['status'] == 'FAILED'): raise Exception('Request: {0}, requestId: {1} failed to complete:\n{2}'.format(msg, str(promise['requestId']), operation_result['metadata']['message'])) raise Exception((((('Timed out waiting for async operation ' + msg) + ' "') + str(promise['requestId'])) + '" to complete.'))
[ "def", "_wait_for_completion", "(", "conn", ",", "promise", ",", "wait_timeout", ",", "msg", ")", ":", "if", "(", "not", "promise", ")", ":", "return", "wait_timeout", "=", "(", "time", ".", "time", "(", ")", "+", "wait_timeout", ")", "while", "(", "wa...
poll request status until resource is provisioned .
train
true
36,893
def backupVersionedFile(old_file, version): numTries = 0 new_file = u'{}.v{}'.format(old_file, version) while (not os.path.isfile(new_file)): if (not os.path.isfile(old_file)): sickrage.srCore.srLogger.debug((u"Not creating backup, %s doesn't exist" % old_file)) break try: sickrage.srCore.srLogger.debug((u'Trying to back up %s to %s' % (old_file, new_file))) shutil.copyfile(old_file, new_file) sickrage.srCore.srLogger.debug(u'Backup done') break except Exception as e: sickrage.srCore.srLogger.warning((u'Error while trying to back up %s to %s : %r' % (old_file, new_file, e))) numTries += 1 time.sleep(1) sickrage.srCore.srLogger.debug(u'Trying again.') if (numTries >= 10): sickrage.srCore.srLogger.error((u'Unable to back up %s to %s please do it manually.' % (old_file, new_file))) return False return True
[ "def", "backupVersionedFile", "(", "old_file", ",", "version", ")", ":", "numTries", "=", "0", "new_file", "=", "u'{}.v{}'", ".", "format", "(", "old_file", ",", "version", ")", "while", "(", "not", "os", ".", "path", ".", "isfile", "(", "new_file", ")",...
back up an old version of a file .
train
false
36,894
def _tile_perimeter_geom(coord, projection, padded): perimeter = _tile_perimeter(coord, projection, padded) wkt = ('POLYGON((%s))' % ', '.join([('%.7f %.7f' % xy) for xy in perimeter])) geom = ogr.CreateGeometryFromWkt(wkt) ref = osr.SpatialReference() ref.ImportFromProj4(projection.srs) geom.AssignSpatialReference(ref) return geom
[ "def", "_tile_perimeter_geom", "(", "coord", ",", "projection", ",", "padded", ")", ":", "perimeter", "=", "_tile_perimeter", "(", "coord", ",", "projection", ",", "padded", ")", "wkt", "=", "(", "'POLYGON((%s))'", "%", "', '", ".", "join", "(", "[", "(", ...
get an ogr geometry object for a coordinate tile polygon .
train
false
36,895
def store_rendered_templates(store, signal, sender, template, context, **kwargs): store.setdefault('template', []).append(template) store.setdefault('context', ContextList()).append(context)
[ "def", "store_rendered_templates", "(", "store", ",", "signal", ",", "sender", ",", "template", ",", "context", ",", "**", "kwargs", ")", ":", "store", ".", "setdefault", "(", "'template'", ",", "[", "]", ")", ".", "append", "(", "template", ")", "store"...
stores templates and contexts that are rendered .
train
false