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
30,569
def convert_ax_c_to_celsius(ax_f): (y1, y2) = ax_f.get_ylim() ax_c.set_ylim(fahrenheit2celsius(y1), fahrenheit2celsius(y2)) ax_c.figure.canvas.draw()
[ "def", "convert_ax_c_to_celsius", "(", "ax_f", ")", ":", "(", "y1", ",", "y2", ")", "=", "ax_f", ".", "get_ylim", "(", ")", "ax_c", ".", "set_ylim", "(", "fahrenheit2celsius", "(", "y1", ")", ",", "fahrenheit2celsius", "(", "y2", ")", ")", "ax_c", ".",...
update second axis according with first axis .
train
false
30,571
def validate_engine(engine): if (engine not in VALID_DB_ENGINES): raise ValueError(('DBInstance Engine must be one of: %s' % ', '.join(VALID_DB_ENGINES))) return engine
[ "def", "validate_engine", "(", "engine", ")", ":", "if", "(", "engine", "not", "in", "VALID_DB_ENGINES", ")", ":", "raise", "ValueError", "(", "(", "'DBInstance Engine must be one of: %s'", "%", "', '", ".", "join", "(", "VALID_DB_ENGINES", ")", ")", ")", "ret...
validate database engine for dbinstance .
train
false
30,572
def MakePoissonPmf(lam, high, step=1): pmf = Pmf() for k in range(0, (high + 1), step): p = EvalPoissonPmf(k, lam) pmf.Set(k, p) pmf.Normalize() return pmf
[ "def", "MakePoissonPmf", "(", "lam", ",", "high", ",", "step", "=", "1", ")", ":", "pmf", "=", "Pmf", "(", ")", "for", "k", "in", "range", "(", "0", ",", "(", "high", "+", "1", ")", ",", "step", ")", ":", "p", "=", "EvalPoissonPmf", "(", "k",...
makes a pmf discrete approx to a poisson distribution .
train
true
30,574
def get_when_exploration_rated(user_id, exploration_id): exp_user_data_model = user_models.ExplorationUserDataModel.get(user_id, exploration_id) return (exp_user_data_model.rated_on if exp_user_data_model else None)
[ "def", "get_when_exploration_rated", "(", "user_id", ",", "exploration_id", ")", ":", "exp_user_data_model", "=", "user_models", ".", "ExplorationUserDataModel", ".", "get", "(", "user_id", ",", "exploration_id", ")", "return", "(", "exp_user_data_model", ".", "rated_...
fetches the datetime the exploration was last rated by this user .
train
false
30,575
def nupicBindingsPrereleaseInstalled(): try: nupicDistribution = pkg_resources.get_distribution('nupic.bindings') if pkg_resources.parse_version(nupicDistribution.version).is_prerelease: return True except pkg_resources.DistributionNotFound: pass try: nupicDistribution = pkg_resources.get_distribution('nupic.research.bindings') return True except pkg_resources.DistributionNotFound: pass return False
[ "def", "nupicBindingsPrereleaseInstalled", "(", ")", ":", "try", ":", "nupicDistribution", "=", "pkg_resources", ".", "get_distribution", "(", "'nupic.bindings'", ")", "if", "pkg_resources", ".", "parse_version", "(", "nupicDistribution", ".", "version", ")", ".", "...
make an attempt to determine if a pre-release version of nupic .
train
false
30,578
def make_output_dir(outdir): try: if (not os.path.exists(os.path.abspath(outdir))): logger.debug(u'Creating %s', outdir) os.makedirs(outdir) except OSError: logger.debug(u'Problem creating %s', outdir) if (not os.path.exists(outdir)): raise OSError(u'Could not create %s', outdir) return outdir
[ "def", "make_output_dir", "(", "outdir", ")", ":", "try", ":", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "abspath", "(", "outdir", ")", ")", ")", ":", "logger", ".", "debug", "(", "u'Creating %s'", ",", "outdi...
make the output_dir if it doesnt exist .
train
false
30,579
def load_unixtime(buf, pos): (secs, pos) = load_le32(buf, pos) dt = datetime.fromtimestamp(secs, UTC) return (dt, pos)
[ "def", "load_unixtime", "(", "buf", ",", "pos", ")", ":", "(", "secs", ",", "pos", ")", "=", "load_le32", "(", "buf", ",", "pos", ")", "dt", "=", "datetime", ".", "fromtimestamp", "(", "secs", ",", "UTC", ")", "return", "(", "dt", ",", "pos", ")"...
load le32 unix timestamp .
train
true
30,580
def welch(x, fs=1.0, window='hann', nperseg=None, noverlap=None, nfft=None, detrend='constant', return_onesided=True, scaling='density', axis=(-1)): (freqs, Pxx) = csd(x, x, fs, window, nperseg, noverlap, nfft, detrend, return_onesided, scaling, axis) return (freqs, Pxx.real)
[ "def", "welch", "(", "x", ",", "fs", "=", "1.0", ",", "window", "=", "'hann'", ",", "nperseg", "=", "None", ",", "noverlap", "=", "None", ",", "nfft", "=", "None", ",", "detrend", "=", "'constant'", ",", "return_onesided", "=", "True", ",", "scaling"...
estimate power spectral density using welchs method .
train
false
30,581
def debug_assert(condition, msg=None): if (msg is None): msg = 'debug_assert failed' if (not condition): action = config.compute_test_value if (action in ['raise', 'ignore']): raise AssertionError(msg) else: assert (action == 'warn') warnings.warn(msg, stacklevel=2)
[ "def", "debug_assert", "(", "condition", ",", "msg", "=", "None", ")", ":", "if", "(", "msg", "is", "None", ")", ":", "msg", "=", "'debug_assert failed'", "if", "(", "not", "condition", ")", ":", "action", "=", "config", ".", "compute_test_value", "if", ...
customized assert with options to ignore the assert with just a warning .
train
false
30,582
def get_pattern(app_name=u'wiki', namespace=u'wiki', url_config_class=None): if (url_config_class is None): url_config_classname = getattr(settings, u'URL_CONFIG_CLASS', None) if (url_config_classname is None): url_config_class = WikiURLPatterns else: url_config_class = get_class_from_str(url_config_classname) urlpatterns = url_config_class().get_urls() return (urlpatterns, app_name, namespace)
[ "def", "get_pattern", "(", "app_name", "=", "u'wiki'", ",", "namespace", "=", "u'wiki'", ",", "url_config_class", "=", "None", ")", ":", "if", "(", "url_config_class", "is", "None", ")", ":", "url_config_classname", "=", "getattr", "(", "settings", ",", "u'U...
every url resolution takes place as "wiki:view_name" .
train
false
30,583
def disable_destructive_action_challenge(): YamlBindings.update_yml_source('/opt/spinnaker/config/clouddriver.yml', {'credentials': {'challengeDestructiveActionsEnvironments': ''}})
[ "def", "disable_destructive_action_challenge", "(", ")", ":", "YamlBindings", ".", "update_yml_source", "(", "'/opt/spinnaker/config/clouddriver.yml'", ",", "{", "'credentials'", ":", "{", "'challengeDestructiveActionsEnvironments'", ":", "''", "}", "}", ")" ]
disables destructive action challenge for codelab .
train
false
30,584
def colorbar(mappable, cax=None, ax=None, **kw): import matplotlib.pyplot as plt if (ax is None): ax = plt.gca() if (cax is None): (cax, kw) = make_axes(ax, **kw) cax._hold = True cb = Colorbar(cax, mappable, **kw) def on_changed(m): cb.set_cmap(m.get_cmap()) cb.set_clim(m.get_clim()) cb.update_bruteforce(m) cbid = mappable.callbacksSM.connect(u'changed', on_changed) mappable.colorbar = cb ax.figure.sca(ax) return cb
[ "def", "colorbar", "(", "mappable", ",", "cax", "=", "None", ",", "ax", "=", "None", ",", "**", "kw", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "if", "(", "ax", "is", "None", ")", ":", "ax", "=", "plt", ".", "gca", "(", ")",...
create a colorbar for a scalarmappable instance .
train
false
30,585
def _get_codes_for_values(values, categories): from pandas.core.algorithms import _get_data_algo, _hashtables if (not is_dtype_equal(values.dtype, categories.dtype)): values = _ensure_object(values) categories = _ensure_object(categories) ((hash_klass, vec_klass), vals) = _get_data_algo(values, _hashtables) ((_, _), cats) = _get_data_algo(categories, _hashtables) t = hash_klass(len(cats)) t.map_locations(cats) return _coerce_indexer_dtype(t.lookup(vals), cats)
[ "def", "_get_codes_for_values", "(", "values", ",", "categories", ")", ":", "from", "pandas", ".", "core", ".", "algorithms", "import", "_get_data_algo", ",", "_hashtables", "if", "(", "not", "is_dtype_equal", "(", "values", ".", "dtype", ",", "categories", "....
utility routine to turn values into codes given the specified categories .
train
false
30,586
def call_action_api(app, action, apikey=None, status=200, **kwargs): params = json.dumps(kwargs) response = app.post('/api/action/{0}'.format(action), params=params, extra_environ={'Authorization': str(apikey)}, status=status) assert ('/api/3/action/help_show?name={0}'.format(action) in response.json['help']) if (status in (200,)): assert (response.json['success'] is True) return response.json['result'] else: assert (response.json['success'] is False) return response.json['error']
[ "def", "call_action_api", "(", "app", ",", "action", ",", "apikey", "=", "None", ",", "status", "=", "200", ",", "**", "kwargs", ")", ":", "params", "=", "json", ".", "dumps", "(", "kwargs", ")", "response", "=", "app", ".", "post", "(", "'/api/actio...
post an http request to the ckan api and return the result .
train
false
30,587
@handle_response_format @treeio_login_required @_process_mass_form def index_in_progress(request, response_format='html'): query = Q(parent__isnull=True) if request.GET: query = ((query & Q(status__hidden=False)) & _get_filter_query(request.GET)) else: query = (query & Q(status__hidden=False)) tasks = Object.filter_by_request(request, Task.objects.filter(query)) milestones = Object.filter_by_request(request, Milestone.objects.filter(status__hidden=False)) filters = FilterForm(request.user.profile, 'status', request.GET) time_slots = Object.filter_by_request(request, TaskTimeSlot.objects.filter(time_from__isnull=False, time_to__isnull=True)) context = _get_default_context(request) context.update({'milestones': milestones, 'tasks': tasks, 'filters': filters, 'time_slots': time_slots}) return render_to_response('projects/index_in_progress', context, context_instance=RequestContext(request), response_format=response_format)
[ "@", "handle_response_format", "@", "treeio_login_required", "@", "_process_mass_form", "def", "index_in_progress", "(", "request", ",", "response_format", "=", "'html'", ")", ":", "query", "=", "Q", "(", "parent__isnull", "=", "True", ")", "if", "request", ".", ...
a page with a list of tasks in progress .
train
false
30,588
@pytest.mark.django_db def test_submit_no_source(rf, po_directory, default, store0): language = store0.translation_project.language unit = store0.units[0] source_string = unit.source_f directory = unit.store.parent post_dict = {'id': unit.id, 'index': unit.index, 'source_f_0': 'altered source string', 'target_f_0': 'dummy'} request = _create_post_request(rf, directory, data=post_dict, user=default) form = _create_unit_form(request, language, unit) assert form.is_valid() form.save() unit = store0.units[0] assert (unit.source_f == source_string) assert (unit.target_f == 'dummy')
[ "@", "pytest", ".", "mark", ".", "django_db", "def", "test_submit_no_source", "(", "rf", ",", "po_directory", ",", "default", ",", "store0", ")", ":", "language", "=", "store0", ".", "translation_project", ".", "language", "unit", "=", "store0", ".", "units"...
tests that the source string cannot be modified .
train
false
30,589
def isTechniqueAvailable(technique): if (conf.tech and isinstance(conf.tech, list) and (technique not in conf.tech)): return False else: return (getTechniqueData(technique) is not None)
[ "def", "isTechniqueAvailable", "(", "technique", ")", ":", "if", "(", "conf", ".", "tech", "and", "isinstance", "(", "conf", ".", "tech", ",", "list", ")", "and", "(", "technique", "not", "in", "conf", ".", "tech", ")", ")", ":", "return", "False", "...
returns true if there is injection data which sqlmap could use for technique specified .
train
false
30,591
def _default_model(klass): return (None, set())
[ "def", "_default_model", "(", "klass", ")", ":", "return", "(", "None", ",", "set", "(", ")", ")" ]
default model for unhandled classes .
train
false
30,592
def output(): return s3_rest_controller()
[ "def", "output", "(", ")", ":", "return", "s3_rest_controller", "(", ")" ]
print out yaml using the block mode .
train
false
30,593
def one_to_n(val, maxval): a = zeros(maxval, float) a[val] = 1.0 return a
[ "def", "one_to_n", "(", "val", ",", "maxval", ")", ":", "a", "=", "zeros", "(", "maxval", ",", "float", ")", "a", "[", "val", "]", "=", "1.0", "return", "a" ]
returns a 1-in-n binary encoding of a non-negative integer .
train
false
30,595
def hexadecimal(field): assert (hasattr(field, 'value') and hasattr(field, 'size')) size = field.size padding = (alignValue(size, 4) // 4) pattern = (u'0x%%0%ux' % padding) return (pattern % field.value)
[ "def", "hexadecimal", "(", "field", ")", ":", "assert", "(", "hasattr", "(", "field", ",", "'value'", ")", "and", "hasattr", "(", "field", ",", "'size'", ")", ")", "size", "=", "field", ".", "size", "padding", "=", "(", "alignValue", "(", "size", ","...
convert an integer to hexadecimal in lower case .
train
false
30,597
@validate('form') def valid_type_in_col(arch): return all((attrib.isdigit() for attrib in arch.xpath('//@col')))
[ "@", "validate", "(", "'form'", ")", "def", "valid_type_in_col", "(", "arch", ")", ":", "return", "all", "(", "(", "attrib", ".", "isdigit", "(", ")", "for", "attrib", "in", "arch", ".", "xpath", "(", "'//@col'", ")", ")", ")" ]
a col attribute must be an integer type .
train
false
30,599
def user_absent(name, channel=14, **kwargs): ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} user_id_list = __salt__['ipmi.get_name_uids'](name, channel, **kwargs) if (len(user_id_list) == 0): ret['result'] = True ret['comment'] = 'user already absent' return ret if __opts__['test']: ret['comment'] = 'would delete user(s)' ret['result'] = None ret['changes'] = {'delete': user_id_list} return ret for uid in user_id_list: __salt__['ipmi.delete_user'](uid, channel, **kwargs) ret['comment'] = 'user(s) removed' ret['changes'] = {'old': user_id_list, 'new': 'None'} return ret
[ "def", "user_absent", "(", "name", ",", "channel", "=", "14", ",", "**", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", "}", "user_id_list", "...
remove user delete all user records having the matching name .
train
true
30,601
def ShowUser(username, token=None): if (username is None): fd = aff4.FACTORY.Open('aff4:/users', token=token) for user in fd.OpenChildren(): if isinstance(user, users.GRRUser): EPrint(user.Describe()) else: user = aff4.FACTORY.Open(('aff4:/users/%s' % username), token=token) if isinstance(user, users.GRRUser): EPrint(user.Describe()) else: EPrint(('User %s not found' % username))
[ "def", "ShowUser", "(", "username", ",", "token", "=", "None", ")", ":", "if", "(", "username", "is", "None", ")", ":", "fd", "=", "aff4", ".", "FACTORY", ".", "Open", "(", "'aff4:/users'", ",", "token", "=", "token", ")", "for", "user", "in", "fd"...
implementation of the show_user command .
train
false
30,602
def input_loop(): while (mestate.exit != True): try: if (mestate.exit != True): line = raw_input(mestate.rl.prompt) except EOFError: mestate.exit = True sys.exit(1) mestate.input_queue.put(line)
[ "def", "input_loop", "(", ")", ":", "while", "(", "mestate", ".", "exit", "!=", "True", ")", ":", "try", ":", "if", "(", "mestate", ".", "exit", "!=", "True", ")", ":", "line", "=", "raw_input", "(", "mestate", ".", "rl", ".", "prompt", ")", "exc...
wait for user input .
train
true
30,603
def unrepeat(session, *args, **kwargs): kwargs['stop'] = True repeat(session, *args, **kwargs)
[ "def", "unrepeat", "(", "session", ",", "*", "args", ",", "**", "kwargs", ")", ":", "kwargs", "[", "'stop'", "]", "=", "True", "repeat", "(", "session", ",", "*", "args", ",", "**", "kwargs", ")" ]
wrapper for oob use .
train
false
30,604
def test_identity_join_node(tmpdir): global _sum_operands _sum_operands = [] os.chdir(str(tmpdir)) wf = pe.Workflow(name=u'test') inputspec = pe.Node(IdentityInterface(fields=[u'n']), name=u'inputspec') inputspec.iterables = [(u'n', [1, 2, 3])] pre_join1 = pe.Node(IncrementInterface(), name=u'pre_join1') wf.connect(inputspec, u'n', pre_join1, u'input1') join = pe.JoinNode(IdentityInterface(fields=[u'vector']), joinsource=u'inputspec', joinfield=u'vector', name=u'join') wf.connect(pre_join1, u'output1', join, u'vector') post_join1 = pe.Node(SumInterface(), name=u'post_join1') wf.connect(join, u'vector', post_join1, u'input1') result = wf.run() assert (len(result.nodes()) == 5), u'The number of expanded nodes is incorrect.' assert (_sum_operands[0] == [2, 3, 4]), (u'The join Sum input is incorrect: %s.' % _sum_operands[0])
[ "def", "test_identity_join_node", "(", "tmpdir", ")", ":", "global", "_sum_operands", "_sum_operands", "=", "[", "]", "os", ".", "chdir", "(", "str", "(", "tmpdir", ")", ")", "wf", "=", "pe", ".", "Workflow", "(", "name", "=", "u'test'", ")", "inputspec"...
test an identityinterface join .
train
false
30,605
def _rfc822(dt): return formatdate(timegm(dt.utctimetuple()))
[ "def", "_rfc822", "(", "dt", ")", ":", "return", "formatdate", "(", "timegm", "(", "dt", ".", "utctimetuple", "(", ")", ")", ")" ]
turn a datetime object into a formatted date .
train
false
30,606
def post_http_server(test, host, port, data, expected_response='ok'): def make_post(host, port, data): request = post('http://{host}:{port}'.format(host=host, port=port), data=data, timeout=SOCKET_TIMEOUT_FOR_POLLING, persistent=False) def failed(failure): Message.new(message_type=u'acceptance:http_query_failed', reason=unicode(failure)).write() return False request.addCallbacks(content, failed) return request d = verify_socket(host, port) d.addCallback((lambda _: loop_until(reactor, (lambda : make_post(host, port, data))))) d.addCallback(test.assertEqual, expected_response) return d
[ "def", "post_http_server", "(", "test", ",", "host", ",", "port", ",", "data", ",", "expected_response", "=", "'ok'", ")", ":", "def", "make_post", "(", "host", ",", "port", ",", "data", ")", ":", "request", "=", "post", "(", "'http://{host}:{port}'", "....
make a post request to an http server on the given host and port and assert that the response body matches the expected response .
train
false
30,607
def ajax_required(f): @wraps(f) def wrapper(request, *args, **kwargs): if ((not settings.DEBUG) and (not request.is_ajax())): return HttpResponseBadRequest('This must be an AJAX request.') return f(request, *args, **kwargs) return wrapper
[ "def", "ajax_required", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "(", "(", "not", "settings", ".", "DEBUG", ")", "and", "(", "not", "request", ".", ...
check that the request is an ajax request .
train
false
30,608
@app.route('/azurelogin') def azurelogin_view(): redirect_uri = request.values.get('redirect_uri') session_auth_state = auth.unique_auth_state() session['authstate'] = session_auth_state session['redirecturiafterauthorized'] = redirect_uri auth_url = auth.create_authorization_url(session_auth_state) return redirect(auth_url)
[ "@", "app", ".", "route", "(", "'/azurelogin'", ")", "def", "azurelogin_view", "(", ")", ":", "redirect_uri", "=", "request", ".", "values", ".", "get", "(", "'redirect_uri'", ")", "session_auth_state", "=", "auth", ".", "unique_auth_state", "(", ")", "sessi...
redirects to azure login page .
train
false
30,610
def as_vec4(obj, default=(0, 0, 0, 1)): obj = np.atleast_2d(obj) if (obj.shape[(-1)] < 4): new = np.empty((obj.shape[:(-1)] + (4,)), dtype=obj.dtype) new[:] = default new[..., :obj.shape[(-1)]] = obj obj = new elif (obj.shape[(-1)] > 4): raise TypeError(('Array shape %s cannot be converted to vec4' % obj.shape)) return obj
[ "def", "as_vec4", "(", "obj", ",", "default", "=", "(", "0", ",", "0", ",", "0", ",", "1", ")", ")", ":", "obj", "=", "np", ".", "atleast_2d", "(", "obj", ")", "if", "(", "obj", ".", "shape", "[", "(", "-", "1", ")", "]", "<", "4", ")", ...
convert obj to 4-element vector parameters obj : array-like original object .
train
true
30,611
def _consume_one_int(seq): (ints, remainder) = _consume_bytes(seq, 1) return (ints[0], remainder)
[ "def", "_consume_one_int", "(", "seq", ")", ":", "(", "ints", ",", "remainder", ")", "=", "_consume_bytes", "(", "seq", ",", "1", ")", "return", "(", "ints", "[", "0", "]", ",", "remainder", ")" ]
consumes one byte and returns int and remainder .
train
false
30,612
def getclasstree(classes, unique=0): children = {} roots = [] for c in classes: if c.__bases__: for parent in c.__bases__: if (not (parent in children)): children[parent] = [] if (c not in children[parent]): children[parent].append(c) if (unique and (parent in classes)): break elif (c not in roots): roots.append(c) for parent in children: if (parent not in classes): roots.append(parent) return walktree(roots, children, None)
[ "def", "getclasstree", "(", "classes", ",", "unique", "=", "0", ")", ":", "children", "=", "{", "}", "roots", "=", "[", "]", "for", "c", "in", "classes", ":", "if", "c", ".", "__bases__", ":", "for", "parent", "in", "c", ".", "__bases__", ":", "i...
arrange the given list of classes into a hierarchy of nested lists .
train
true
30,613
def libvlc_media_discoverer_event_manager(p_mdis): f = (_Cfunctions.get('libvlc_media_discoverer_event_manager', None) or _Cfunction('libvlc_media_discoverer_event_manager', ((1,),), class_result(EventManager), ctypes.c_void_p, MediaDiscoverer)) return f(p_mdis)
[ "def", "libvlc_media_discoverer_event_manager", "(", "p_mdis", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_media_discoverer_event_manager'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_media_discoverer_event_manager'", ",", "(", "(", "1",...
get event manager from media service discover object .
train
true
30,614
def test_write_noformat_arbitrary_file(tmpdir): _writers.update(_WRITERS_ORIGINAL) testfile = str(tmpdir.join(u'foo.example')) with pytest.raises(io_registry.IORegistryError) as exc: Table().write(testfile) assert str(exc.value).startswith(u'Format could not be identified.')
[ "def", "test_write_noformat_arbitrary_file", "(", "tmpdir", ")", ":", "_writers", ".", "update", "(", "_WRITERS_ORIGINAL", ")", "testfile", "=", "str", "(", "tmpdir", ".", "join", "(", "u'foo.example'", ")", ")", "with", "pytest", ".", "raises", "(", "io_regis...
tests that all identifier functions can accept arbitrary files .
train
false
30,615
def robot(registry, xml_parent, data): parent = XML.SubElement(xml_parent, 'hudson.plugins.robot.RobotPublisher') parent.set('plugin', 'robot') mappings = [('output-path', 'outputPath', None), ('log-file-link', 'logFileLink', ''), ('report-html', 'reportFileName', 'report.html'), ('log-html', 'logFileName', 'log.html'), ('output-xml', 'outputFileName', 'output.xml'), ('pass-threshold', 'passThreshold', '0.0'), ('unstable-threshold', 'unstableThreshold', '0.0'), ('only-critical', 'onlyCritical', True), ('enable-cache', 'enableCache', True)] helpers.convert_mapping_to_xml(parent, data, mappings, fail_required=True) other_files = XML.SubElement(parent, 'otherFiles') for other_file in data.get('other-files', []): XML.SubElement(other_files, 'string').text = str(other_file) XML.SubElement(parent, 'disableArchiveOutput').text = str((not data.get('archive-output-xml', True))).lower()
[ "def", "robot", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "parent", "=", "XML", ".", "SubElement", "(", "xml_parent", ",", "'hudson.plugins.robot.RobotPublisher'", ")", "parent", ".", "set", "(", "'plugin'", ",", "'robot'", ")", "mappings", ...
yaml: robot adds support for the robot framework plugin requires the jenkins :jenkins-wiki:robot framework plugin <robot+framework+plugin> .
train
false
30,616
def _test_remove_from_figure(use_gridspec): fig = plt.figure() ax = fig.add_subplot(111) sc = ax.scatter([1, 2], [3, 4], cmap=u'spring') sc.set_array(np.array([5, 6])) pre_figbox = np.array(ax.figbox) cb = fig.colorbar(sc, use_gridspec=use_gridspec) fig.subplots_adjust() cb.remove() fig.subplots_adjust() post_figbox = np.array(ax.figbox) assert (pre_figbox == post_figbox).all()
[ "def", "_test_remove_from_figure", "(", "use_gridspec", ")", ":", "fig", "=", "plt", ".", "figure", "(", ")", "ax", "=", "fig", ".", "add_subplot", "(", "111", ")", "sc", "=", "ax", ".", "scatter", "(", "[", "1", ",", "2", "]", ",", "[", "3", ","...
test remove_from_figure with the specified use_gridspec setting .
train
false
30,619
def test_nm3_wrong_nn_obj(): ratio = 'auto' nn = 'rnd' nn3 = NearestNeighbors(n_neighbors=3) nm3 = NearMiss(ratio=ratio, random_state=RND_SEED, version=VERSION_NEARMISS, return_indices=True, n_neighbors=nn, n_neighbors_ver3=nn3) assert_raises(ValueError, nm3.fit_sample, X, Y) nn3 = 'rnd' nn = NearestNeighbors(n_neighbors=3) nm3 = NearMiss(ratio=ratio, random_state=RND_SEED, version=VERSION_NEARMISS, return_indices=True, n_neighbors=nn, n_neighbors_ver3=nn3) assert_raises(ValueError, nm3.fit_sample, X, Y)
[ "def", "test_nm3_wrong_nn_obj", "(", ")", ":", "ratio", "=", "'auto'", "nn", "=", "'rnd'", "nn3", "=", "NearestNeighbors", "(", "n_neighbors", "=", "3", ")", "nm3", "=", "NearMiss", "(", "ratio", "=", "ratio", ",", "random_state", "=", "RND_SEED", ",", "...
test either if an error is raised with wrong nn object .
train
false
30,622
def make_form(app, global_conf, realm, authfunc, **kw): from paste.util.import_string import eval_import import types authfunc = eval_import(authfunc) assert isinstance(authfunc, types.FunctionType), 'authfunc must resolve to a function' template = kw.get('template') if (template is not None): template = eval_import(template) assert isinstance(template, str), 'template must resolve to a string' return AuthFormHandler(app, authfunc, template)
[ "def", "make_form", "(", "app", ",", "global_conf", ",", "realm", ",", "authfunc", ",", "**", "kw", ")", ":", "from", "paste", ".", "util", ".", "import_string", "import", "eval_import", "import", "types", "authfunc", "=", "eval_import", "(", "authfunc", "...
grant access via form authentication config looks like this:: [filter:grant] use = egg:paste#auth_form realm=myrealm authfunc=somepackage .
train
false
30,624
def get_flags(record): props = (('admin_review', 'admin-review', _lazy('Admin Review')), ('is_jetpack', 'jetpack', _lazy('Jetpack Add-on')), ('requires_restart', 'requires_restart', _lazy('Requires Restart')), ('has_info_request', 'info', _lazy('More Information Requested')), ('has_editor_comment', 'editor', _lazy('Contains Reviewer Comment')), ('sources_provided', 'sources-provided', _lazy('Sources provided')), ('is_webextension', 'webextension', _lazy('WebExtension'))) return [(cls, title) for (prop, cls, title) in props if getattr(record, prop)]
[ "def", "get_flags", "(", "record", ")", ":", "props", "=", "(", "(", "'admin_review'", ",", "'admin-review'", ",", "_lazy", "(", "'Admin Review'", ")", ")", ",", "(", "'is_jetpack'", ",", "'jetpack'", ",", "_lazy", "(", "'Jetpack Add-on'", ")", ")", ",", ...
return a list of tuples (indicating which flags should be displayed for a particular add-on .
train
false
30,625
def HA2(credentails, request, algorithm): if ((credentails.get('qop') == 'auth') or (credentails.get('qop') is None)): return H(':'.join([request['method'].encode('utf-8'), request['uri'].encode('utf-8')]), algorithm) elif (credentails.get('qop') == 'auth-int'): for k in ('method', 'uri', 'body'): if (k not in request): raise ValueError(('%s required' % k)) A2 = ':'.join([request['method'].encode('utf-8'), request['uri'].encode('utf-8'), H(request['body'], algorithm).encode('utf-8')]) return H(A2, algorithm) raise ValueError
[ "def", "HA2", "(", "credentails", ",", "request", ",", "algorithm", ")", ":", "if", "(", "(", "credentails", ".", "get", "(", "'qop'", ")", "==", "'auth'", ")", "or", "(", "credentails", ".", "get", "(", "'qop'", ")", "is", "None", ")", ")", ":", ...
create ha2 md5 hash if the qop directives value is "auth" or is unspecified .
train
false
30,626
def __mac(value): return (salt.utils.validate.net.mac(value), value, 'MAC address')
[ "def", "__mac", "(", "value", ")", ":", "return", "(", "salt", ".", "utils", ".", "validate", ".", "net", ".", "mac", "(", "value", ")", ",", "value", ",", "'MAC address'", ")" ]
validate a mac address .
train
false
30,628
def commit_item_json(): ctable = s3db.req_commit itable = s3db.req_commit_item stable = s3db.org_site query = ((((itable.req_item_id == request.args[0]) & (ctable.id == itable.commit_id)) & (ctable.site_id == stable.id)) & (itable.deleted == False)) records = db(query).select(ctable.id, ctable.date, stable.name, itable.quantity, orderby=db.req_commit.date) json_str = ('[%s,%s' % (json.dumps(dict(id=str(T('Committed')), quantity='#')), records.json()[1:])) response.headers['Content-Type'] = 'application/json' return json_str
[ "def", "commit_item_json", "(", ")", ":", "ctable", "=", "s3db", ".", "req_commit", "itable", "=", "s3db", ".", "req_commit_item", "stable", "=", "s3db", ".", "org_site", "query", "=", "(", "(", "(", "(", "itable", ".", "req_item_id", "==", "request", "....
used by s3 .
train
false
30,629
def captured_stdout(): return captured_output('stdout')
[ "def", "captured_stdout", "(", ")", ":", "return", "captured_output", "(", "'stdout'", ")" ]
capture the output of sys .
train
false
30,633
def trueQValues(Ts, R, discountFactor, policy): T = collapsedTransitions(Ts, policy) V = trueValues(T, R, discountFactor) Vnext = ((V * discountFactor) + R) numA = len(Ts) dim = len(R) Qs = zeros((dim, numA)) for si in range(dim): for a in range(numA): Qs[(si, a)] = dot(Ts[a][si], Vnext) return Qs
[ "def", "trueQValues", "(", "Ts", ",", "R", ",", "discountFactor", ",", "policy", ")", ":", "T", "=", "collapsedTransitions", "(", "Ts", ",", "policy", ")", "V", "=", "trueValues", "(", "T", ",", "R", ",", "discountFactor", ")", "Vnext", "=", "(", "("...
the true q-values .
train
false
30,634
def process_null_records(meta, scan=True): if scan: for table in reversed(meta.sorted_tables): if (table.name not in ('fixed_ips', 'shadow_fixed_ips')): scan_for_null_records(table, 'instance_uuid', check_fkeys=True) for table_name in ('instances', 'shadow_instances'): table = meta.tables[table_name] if scan: scan_for_null_records(table, 'uuid', check_fkeys=False) else: table.columns.uuid.alter(nullable=False)
[ "def", "process_null_records", "(", "meta", ",", "scan", "=", "True", ")", ":", "if", "scan", ":", "for", "table", "in", "reversed", "(", "meta", ".", "sorted_tables", ")", ":", "if", "(", "table", ".", "name", "not", "in", "(", "'fixed_ips'", ",", "...
scans the database for null instance_uuid records for processing .
train
false
30,635
def parse_common(source, info): initial_group_count = info.group_count branches = [parse_sequence(source, info)] final_group_count = info.group_count while source.match('|'): info.group_count = initial_group_count branches.append(parse_sequence(source, info)) final_group_count = max(final_group_count, info.group_count) info.group_count = final_group_count source.expect(')') if (len(branches) == 1): return branches[0] return Branch(branches)
[ "def", "parse_common", "(", "source", ",", "info", ")", ":", "initial_group_count", "=", "info", ".", "group_count", "branches", "=", "[", "parse_sequence", "(", "source", ",", "info", ")", "]", "final_group_count", "=", "info", ".", "group_count", "while", ...
parses a common groups branch .
train
false
30,636
def valid_post_signature(request, signature_header=SIGNATURE_BODY_HEADER): return valid_signature('Body:{}'.format(request.body), request.headers.get(signature_header), field='body')
[ "def", "valid_post_signature", "(", "request", ",", "signature_header", "=", "SIGNATURE_BODY_HEADER", ")", ":", "return", "valid_signature", "(", "'Body:{}'", ".", "format", "(", "request", ".", "body", ")", ",", "request", ".", "headers", ".", "get", "(", "si...
validate that the request has a properly signed body .
train
false
30,638
def is_writable_file_like(obj): return callable(getattr(obj, u'write', None))
[ "def", "is_writable_file_like", "(", "obj", ")", ":", "return", "callable", "(", "getattr", "(", "obj", ",", "u'write'", ",", "None", ")", ")" ]
return true if *obj* looks like a file object with a *write* method .
train
false
30,639
def convert_UserProperty(model, prop, kwargs): return None
[ "def", "convert_UserProperty", "(", "model", ",", "prop", ",", "kwargs", ")", ":", "return", "None" ]
returns a form field for a db .
train
false
30,640
def _create_module_and_parents(name): parts = name.split('.') parent = _create_module(parts[0]) created_parts = [parts[0]] parts.pop(0) while parts: child_name = parts.pop(0) module = new.module(child_name) setattr(parent, child_name, module) created_parts.append(child_name) sys.modules['.'.join(created_parts)] = module parent = module
[ "def", "_create_module_and_parents", "(", "name", ")", ":", "parts", "=", "name", ".", "split", "(", "'.'", ")", "parent", "=", "_create_module", "(", "parts", "[", "0", "]", ")", "created_parts", "=", "[", "parts", "[", "0", "]", "]", "parts", ".", ...
create a module .
train
false
30,642
def mode_cmd(mode, text, text_inp, chan, conn, notice): split = text_inp.split(' ') if split[0].startswith('#'): channel = split[0] target = split[1] notice('Attempting to {} {} in {}...'.format(text, target, channel)) conn.send('MODE {} {} {}'.format(channel, mode, target)) else: channel = chan target = split[0] notice('Attempting to {} {} in {}...'.format(text, target, channel)) conn.send('MODE {} {} {}'.format(channel, mode, target))
[ "def", "mode_cmd", "(", "mode", ",", "text", ",", "text_inp", ",", "chan", ",", "conn", ",", "notice", ")", ":", "split", "=", "text_inp", ".", "split", "(", "' '", ")", "if", "split", "[", "0", "]", ".", "startswith", "(", "'#'", ")", ":", "chan...
generic mode setting function .
train
false
30,643
def getClosestOppositeIntersectionPaths(yIntersectionPaths): yIntersectionPaths.sort(compareDistanceFromCenter) beforeFirst = (yIntersectionPaths[0].yMinusCenter < 0.0) yCloseToCenterPaths = [yIntersectionPaths[0]] for yIntersectionPath in yIntersectionPaths[1:]: beforeSecond = (yIntersectionPath.yMinusCenter < 0.0) if (beforeFirst != beforeSecond): yCloseToCenterPaths.append(yIntersectionPath) return yCloseToCenterPaths return yCloseToCenterPaths
[ "def", "getClosestOppositeIntersectionPaths", "(", "yIntersectionPaths", ")", ":", "yIntersectionPaths", ".", "sort", "(", "compareDistanceFromCenter", ")", "beforeFirst", "=", "(", "yIntersectionPaths", "[", "0", "]", ".", "yMinusCenter", "<", "0.0", ")", "yCloseToCe...
get the close to center paths .
train
false
30,644
def ref_to_obj(ref): if (not isinstance(ref, six.string_types)): raise TypeError('References must be strings') if (':' not in ref): raise ValueError('Invalid reference') (modulename, rest) = ref.split(':', 1) try: obj = __import__(modulename) except ImportError: raise LookupError(('Error resolving reference %s: could not import module' % ref)) try: for name in (modulename.split('.')[1:] + rest.split('.')): obj = getattr(obj, name) return obj except Exception: raise LookupError(('Error resolving reference %s: error looking up object' % ref))
[ "def", "ref_to_obj", "(", "ref", ")", ":", "if", "(", "not", "isinstance", "(", "ref", ",", "six", ".", "string_types", ")", ")", ":", "raise", "TypeError", "(", "'References must be strings'", ")", "if", "(", "':'", "not", "in", "ref", ")", ":", "rais...
returns the object pointed to by ref .
train
false
30,645
def send_beta_role_email(action, user, email_params): if (action == 'add'): email_params['message'] = 'add_beta_tester' email_params['email_address'] = user.email email_params['full_name'] = user.profile.name elif (action == 'remove'): email_params['message'] = 'remove_beta_tester' email_params['email_address'] = user.email email_params['full_name'] = user.profile.name else: raise ValueError("Unexpected action received '{}' - expected 'add' or 'remove'".format(action)) send_mail_to_student(user.email, email_params, language=get_user_email_language(user))
[ "def", "send_beta_role_email", "(", "action", ",", "user", ",", "email_params", ")", ":", "if", "(", "action", "==", "'add'", ")", ":", "email_params", "[", "'message'", "]", "=", "'add_beta_tester'", "email_params", "[", "'email_address'", "]", "=", "user", ...
send an email to a user added or removed as a beta tester .
train
false
30,646
@public def random_poly(x, n, inf, sup, domain=ZZ, polys=False): poly = Poly(dup_random(n, inf, sup, domain), x, domain=domain) if (not polys): return poly.as_expr() else: return poly
[ "@", "public", "def", "random_poly", "(", "x", ",", "n", ",", "inf", ",", "sup", ",", "domain", "=", "ZZ", ",", "polys", "=", "False", ")", ":", "poly", "=", "Poly", "(", "dup_random", "(", "n", ",", "inf", ",", "sup", ",", "domain", ")", ",", ...
return a polynomial of degree n with coefficients in [inf .
train
false
30,649
def ipv6_to_bin(ip): return addrconv.ipv6.text_to_bin(ip)
[ "def", "ipv6_to_bin", "(", "ip", ")", ":", "return", "addrconv", ".", "ipv6", ".", "text_to_bin", "(", "ip", ")" ]
converts human readable ipv6 string to binary representation .
train
false
30,650
@contextmanager def for_range(builder, count, start=None, intp=None): if (intp is None): intp = count.type if (start is None): start = intp(0) stop = count bbcond = builder.append_basic_block('for.cond') bbbody = builder.append_basic_block('for.body') bbend = builder.append_basic_block('for.end') def do_break(): builder.branch(bbend) bbstart = builder.basic_block builder.branch(bbcond) with builder.goto_block(bbcond): index = builder.phi(intp, name='loop.index') pred = builder.icmp_signed('<', index, stop) builder.cbranch(pred, bbbody, bbend) with builder.goto_block(bbbody): (yield Loop(index, do_break)) bbbody = builder.basic_block incr = increment_index(builder, index) terminate(builder, bbcond) index.add_incoming(start, bbstart) index.add_incoming(incr, bbbody) builder.position_at_end(bbend)
[ "@", "contextmanager", "def", "for_range", "(", "builder", ",", "count", ",", "start", "=", "None", ",", "intp", "=", "None", ")", ":", "if", "(", "intp", "is", "None", ")", ":", "intp", "=", "count", ".", "type", "if", "(", "start", "is", "None", ...
generate llvm ir for a for-loop in [start .
train
false
30,652
def libvlc_video_get_marquee_string(p_mi, option): f = (_Cfunctions.get('libvlc_video_get_marquee_string', None) or _Cfunction('libvlc_video_get_marquee_string', ((1,), (1,)), string_result, ctypes.c_void_p, MediaPlayer, ctypes.c_uint)) return f(p_mi, option)
[ "def", "libvlc_video_get_marquee_string", "(", "p_mi", ",", "option", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_video_get_marquee_string'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_video_get_marquee_string'", ",", "(", "(", "1", ...
get a string marquee option value .
train
true
30,653
def proxy_bypass_environment(host): no_proxy = (os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')) if (no_proxy == '*'): return 1 (hostonly, port) = splitport(host) for name in no_proxy.split(','): if (name and (hostonly.endswith(name) or host.endswith(name))): return 1 return 0
[ "def", "proxy_bypass_environment", "(", "host", ")", ":", "no_proxy", "=", "(", "os", ".", "environ", ".", "get", "(", "'no_proxy'", ",", "''", ")", "or", "os", ".", "environ", ".", "get", "(", "'NO_PROXY'", ",", "''", ")", ")", "if", "(", "no_proxy"...
test if proxies should not be used for a particular host .
train
true
30,654
def ispower2(n): bin_n = binary_repr(n)[1:] if (u'1' in bin_n): return 0 else: return len(bin_n)
[ "def", "ispower2", "(", "n", ")", ":", "bin_n", "=", "binary_repr", "(", "n", ")", "[", "1", ":", "]", "if", "(", "u'1'", "in", "bin_n", ")", ":", "return", "0", "else", ":", "return", "len", "(", "bin_n", ")" ]
returns the log base 2 of *n* if *n* is a power of 2 .
train
false
30,655
def test_pie_table(): chart = Pie(inner_radius=0.3, pretty_print=True) chart.title = 'Browser usage in February 2012 (in %)' chart.add('IE', 19.5) chart.add('Firefox', 36.6) chart.add('Chrome', 36.3) chart.add('Safari', 4.5) chart.add('Opera', 2.3) q = pq(chart.render_table()) assert (len(q('table')) == 1)
[ "def", "test_pie_table", "(", ")", ":", "chart", "=", "Pie", "(", "inner_radius", "=", "0.3", ",", "pretty_print", "=", "True", ")", "chart", ".", "title", "=", "'Browser usage in February 2012 (in %)'", "chart", ".", "add", "(", "'IE'", ",", "19.5", ")", ...
test rendering a table for a pie .
train
false
30,656
def mpi_tag_key(a): if isinstance(a.op, (MPISend, MPIRecv, MPIRecvWait, MPISendWait)): return a.op.tag else: return 0
[ "def", "mpi_tag_key", "(", "a", ")", ":", "if", "isinstance", "(", "a", ".", "op", ",", "(", "MPISend", ",", "MPIRecv", ",", "MPIRecvWait", ",", "MPISendWait", ")", ")", ":", "return", "a", ".", "op", ".", "tag", "else", ":", "return", "0" ]
break mpi ties by using the variable tag - prefer lower tags first .
train
false
30,658
def get_course_syllabus_section(course, section_key): if (section_key in ['syllabus', 'guest_syllabus']): try: filesys = course.system.resources_fs dirs = [(path('syllabus') / course.url_name), path('syllabus')] filepath = find_file(filesys, dirs, (section_key + '.html')) with filesys.open(filepath) as html_file: return replace_static_urls(html_file.read().decode('utf-8'), getattr(course, 'data_dir', None), course_id=course.id, static_asset_path=course.static_asset_path) except ResourceNotFoundError: log.exception(u'Missing syllabus section %s in course %s', section_key, course.location.to_deprecated_string()) return '! Syllabus missing !' raise KeyError(('Invalid about key ' + str(section_key)))
[ "def", "get_course_syllabus_section", "(", "course", ",", "section_key", ")", ":", "if", "(", "section_key", "in", "[", "'syllabus'", ",", "'guest_syllabus'", "]", ")", ":", "try", ":", "filesys", "=", "course", ".", "system", ".", "resources_fs", "dirs", "=...
this returns the snippet of html to be rendered on the syllabus page .
train
false
30,659
def _botocore_exception_maybe(): if HAS_BOTO3: return botocore.exceptions.ClientError return type(None)
[ "def", "_botocore_exception_maybe", "(", ")", ":", "if", "HAS_BOTO3", ":", "return", "botocore", ".", "exceptions", ".", "ClientError", "return", "type", "(", "None", ")" ]
allow for boto3 not being installed when using these utils by wrapping botocore .
train
false
30,660
def merge_profile(): with _profile_lock: new_profile = sys.getdxp() if has_pairs(new_profile): for first_inst in range(len(_cumulative_profile)): for second_inst in range(len(_cumulative_profile[first_inst])): _cumulative_profile[first_inst][second_inst] += new_profile[first_inst][second_inst] else: for inst in range(len(_cumulative_profile)): _cumulative_profile[inst] += new_profile[inst]
[ "def", "merge_profile", "(", ")", ":", "with", "_profile_lock", ":", "new_profile", "=", "sys", ".", "getdxp", "(", ")", "if", "has_pairs", "(", "new_profile", ")", ":", "for", "first_inst", "in", "range", "(", "len", "(", "_cumulative_profile", ")", ")", ...
reads sys .
train
false
30,661
def _append_domain(opts): if opts['id'].endswith(opts['append_domain']): return opts['id'] if opts['id'].endswith('.'): return opts['id'] return '{0[id]}.{0[append_domain]}'.format(opts)
[ "def", "_append_domain", "(", "opts", ")", ":", "if", "opts", "[", "'id'", "]", ".", "endswith", "(", "opts", "[", "'append_domain'", "]", ")", ":", "return", "opts", "[", "'id'", "]", "if", "opts", "[", "'id'", "]", ".", "endswith", "(", "'.'", ")...
append a domain to the existing id if it doesnt already exist .
train
true
30,662
def p_direct_abstract_declarator_3(t): pass
[ "def", "p_direct_abstract_declarator_3", "(", "t", ")", ":", "pass" ]
direct_abstract_declarator : lbracket constant_expression_opt rbracket .
train
false
30,663
def namespaced_function(function, global_dict, defaults=None, preserve_context=False): if (defaults is None): defaults = function.__defaults__ if preserve_context: _global_dict = function.__globals__.copy() _global_dict.update(global_dict) global_dict = _global_dict new_namespaced_function = types.FunctionType(function.__code__, global_dict, name=function.__name__, argdefs=defaults) new_namespaced_function.__dict__.update(function.__dict__) return new_namespaced_function
[ "def", "namespaced_function", "(", "function", ",", "global_dict", ",", "defaults", "=", "None", ",", "preserve_context", "=", "False", ")", ":", "if", "(", "defaults", "is", "None", ")", ":", "defaults", "=", "function", ".", "__defaults__", "if", "preserve...
redefine a function under a different globals() namespace scope preserve_context: allow to keep the context taken from orignal namespace .
train
true
30,666
def print_fails(stream): if (not FAILS): return stream.write('\n==============================\n') stream.write(('Failed %s tests - output below:' % len(FAILS))) stream.write('\n==============================\n') for f in FAILS: stream.write(('\n%s\n' % f['id'])) stream.write(('%s\n' % ('-' * len(f['id'])))) print_attachments(stream, f, all_channels=True) stream.write('\n')
[ "def", "print_fails", "(", "stream", ")", ":", "if", "(", "not", "FAILS", ")", ":", "return", "stream", ".", "write", "(", "'\\n==============================\\n'", ")", "stream", ".", "write", "(", "(", "'Failed %s tests - output below:'", "%", "len", "(", "F...
print summary failure report .
train
false
30,667
@decorators.api_view(['POST']) @decorators.permission_classes([TwitterAccountIgnorePermission]) def unignore(request): usernames = json.loads(request.body).get('usernames') if (not usernames): raise GenericAPIException(status.HTTP_400_BAD_REQUEST, 'Usernames not provided.') accounts = TwitterAccount.objects.filter(username__in=usernames) for account in accounts: if (account and account.ignored): account.ignored = False account.save() message = {'success': '{0} users unignored successfully.'.format(len(accounts))} return Response(message)
[ "@", "decorators", ".", "api_view", "(", "[", "'POST'", "]", ")", "@", "decorators", ".", "permission_classes", "(", "[", "TwitterAccountIgnorePermission", "]", ")", "def", "unignore", "(", "request", ")", ":", "usernames", "=", "json", ".", "loads", "(", ...
unignores a twitter account from showing up in the aoa tool .
train
false
30,668
def set_mode(path, mode): func_name = '{0}.set_mode'.format(__virtualname__) if (__opts__.get('fun', '') == func_name): log.info('The function {0} should not be used on Windows systems; see function docs for details. The value returned is always None. Use set_perms instead.'.format(func_name)) return get_mode(path)
[ "def", "set_mode", "(", "path", ",", "mode", ")", ":", "func_name", "=", "'{0}.set_mode'", ".", "format", "(", "__virtualname__", ")", "if", "(", "__opts__", ".", "get", "(", "'fun'", ",", "''", ")", "==", "func_name", ")", ":", "log", ".", "info", "...
list networks on a wireless interface cli example: salt minion iwtools .
train
true
30,669
def lookup_group_controller(group_type=None): return _group_controllers.get(group_type)
[ "def", "lookup_group_controller", "(", "group_type", "=", "None", ")", ":", "return", "_group_controllers", ".", "get", "(", "group_type", ")" ]
returns the group controller associated with the given group type .
train
false
30,670
def summarize_items(items, singleton): summary_parts = [] if (not singleton): summary_parts.append('{0} items'.format(len(items))) format_counts = {} for item in items: format_counts[item.format] = (format_counts.get(item.format, 0) + 1) if (len(format_counts) == 1): summary_parts.append(items[0].format) else: for (format, count) in format_counts.iteritems(): summary_parts.append('{0} {1}'.format(format, count)) average_bitrate = (sum([item.bitrate for item in items]) / len(items)) total_duration = sum([item.length for item in items]) summary_parts.append('{0}kbps'.format(int((average_bitrate / 1000)))) summary_parts.append(ui.human_seconds_short(total_duration)) return ', '.join(summary_parts)
[ "def", "summarize_items", "(", "items", ",", "singleton", ")", ":", "summary_parts", "=", "[", "]", "if", "(", "not", "singleton", ")", ":", "summary_parts", ".", "append", "(", "'{0} items'", ".", "format", "(", "len", "(", "items", ")", ")", ")", "fo...
produces a brief summary line describing a set of items .
train
false
30,671
def _ansi(method): def wrapper(self, *args, **kwargs): def convert(inp): if isinstance(inp, basestring): return parse_ansi(('{n%s{n' % inp)) elif hasattr(inp, '__iter__'): li = [] for element in inp: if isinstance(element, basestring): li.append(convert(element)) elif hasattr(element, '__iter__'): li.append(convert(element)) else: li.append(element) return li return inp args = [convert(arg) for arg in args] return method(self, *args, **kwargs) return wrapper
[ "def", "_ansi", "(", "method", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "def", "convert", "(", "inp", ")", ":", "if", "isinstance", "(", "inp", ",", "basestring", ")", ":", "return", "parse_ansi", "(...
decorator for converting ansi in input .
train
false
30,672
def strip_invalid_xml_chars(s): return _invalid_char_re.sub('', s)
[ "def", "strip_invalid_xml_chars", "(", "s", ")", ":", "return", "_invalid_char_re", ".", "sub", "(", "''", ",", "s", ")" ]
return the string with any invalid xml characters removed .
train
false
30,673
def buildSimpleTrainingSet(numOnes=5): numPatterns = 11 p = getSimplePatterns(numOnes, numPatterns) s1 = [p[0], p[1], p[2], p[3], p[4], p[5], p[6]] s2 = [p[7], p[8], p[2], p[3], p[4], p[9], p[10]] trainingSequences = [s1, s2] return (trainingSequences, 5)
[ "def", "buildSimpleTrainingSet", "(", "numOnes", "=", "5", ")", ":", "numPatterns", "=", "11", "p", "=", "getSimplePatterns", "(", "numOnes", ",", "numPatterns", ")", "s1", "=", "[", "p", "[", "0", "]", ",", "p", "[", "1", "]", ",", "p", "[", "2", ...
two very simple high order sequences for debugging .
train
false
30,674
def openLabJack(deviceType, connectionType, firstFound=True, pAddress=None, devNumber=None, handleOnly=False, LJSocket=None): rcvDataBuff = [] handle = None if (connectionType == LJ_ctLJSOCKET): handle = _openLabJackUsingLJSocket(deviceType, firstFound, pAddress, LJSocket, handleOnly) elif ((os.name == 'posix') and (connectionType == LJ_ctUSB)): handle = _openLabJackUsingExodriver(deviceType, firstFound, pAddress, devNumber) if isinstance(handle, Device): return handle elif (os.name == 'nt'): if (deviceType == 1281): handle = _openWirelessBridgeOnWindows(firstFound, pAddress, devNumber) handle = ctypes.c_void_p(handle) elif (staticLib is not None): handle = _openLabJackUsingUDDriver(deviceType, connectionType, firstFound, pAddress, devNumber) elif ((connectionType == LJ_ctETHERNET) and (deviceType == LJ_dtUE9)): handle = _openUE9OverEthernet(firstFound, pAddress, devNumber) if (not handleOnly): return _makeDeviceFromHandle(handle, deviceType) else: return Device(handle, devType=deviceType)
[ "def", "openLabJack", "(", "deviceType", ",", "connectionType", ",", "firstFound", "=", "True", ",", "pAddress", "=", "None", ",", "devNumber", "=", "None", ",", "handleOnly", "=", "False", ",", "LJSocket", "=", "None", ")", ":", "rcvDataBuff", "=", "[", ...
openlabjack note: on windows .
train
false
30,676
def _wrap_paragraphs(text, width=70, **kwargs): pars = text.split('\n') pars = ['\n'.join(textwrap.wrap(p, width=width, **kwargs)) for p in pars] s = '\n'.join(pars) return s
[ "def", "_wrap_paragraphs", "(", "text", ",", "width", "=", "70", ",", "**", "kwargs", ")", ":", "pars", "=", "text", ".", "split", "(", "'\\n'", ")", "pars", "=", "[", "'\\n'", ".", "join", "(", "textwrap", ".", "wrap", "(", "p", ",", "width", "=...
wraps paragraphs instead .
train
false
30,677
def rotate_180(request, fileobjects): transpose_image(request, fileobjects, 3)
[ "def", "rotate_180", "(", "request", ",", "fileobjects", ")", ":", "transpose_image", "(", "request", ",", "fileobjects", ",", "3", ")" ]
rotate image 180 degrees .
train
false
30,679
def delete_rax_network(args): print ("--- Cleaning Cloud Networks matching '%s'" % args.match_re) for region in pyrax.identity.services.network.regions: cnw = pyrax.connect_to_cloud_networks(region=region) for network in cnw.list(): if re.search(args.match_re, network.name): prompt_and_delete(network, ('Delete matching %s? [y/n]: ' % network), args.assumeyes)
[ "def", "delete_rax_network", "(", "args", ")", ":", "print", "(", "\"--- Cleaning Cloud Networks matching '%s'\"", "%", "args", ".", "match_re", ")", "for", "region", "in", "pyrax", ".", "identity", ".", "services", ".", "network", ".", "regions", ":", "cnw", ...
function for deleting cloud networks .
train
false
30,680
def MakeOtherAppResponse(): reference = json.loads(kVerifyResponseRenewedExpired) new = {'status': 0, 'receipt': reference['receipt']} new['receipt']['bid'] = 'com.angrybirds.AngryBirds' return json.dumps(new)
[ "def", "MakeOtherAppResponse", "(", ")", ":", "reference", "=", "json", ".", "loads", "(", "kVerifyResponseRenewedExpired", ")", "new", "=", "{", "'status'", ":", "0", ",", "'receipt'", ":", "reference", "[", "'receipt'", "]", "}", "new", "[", "'receipt'", ...
make a response for a valid receipt from another app .
train
false
30,682
def runProtocolsWithReactor(reactorBuilder, serverProtocol, clientProtocol, endpointCreator): reactor = reactorBuilder.buildReactor() serverProtocol._setAttributes(reactor, Deferred()) clientProtocol._setAttributes(reactor, Deferred()) serverFactory = _SingleProtocolFactory(serverProtocol) clientFactory = _SingleProtocolFactory(clientProtocol) serverEndpoint = endpointCreator.server(reactor) d = serverEndpoint.listen(serverFactory) def gotPort(p): clientEndpoint = endpointCreator.client(reactor, p.getHost()) return clientEndpoint.connect(clientFactory) d.addCallback(gotPort) def failed(result): log.err(result, 'Connection setup failed.') disconnected = gatherResults([serverProtocol._done, clientProtocol._done]) d.addCallback((lambda _: disconnected)) d.addErrback(failed) d.addCallback((lambda _: needsRunningReactor(reactor, reactor.stop))) reactorBuilder.runReactor(reactor) return reactor
[ "def", "runProtocolsWithReactor", "(", "reactorBuilder", ",", "serverProtocol", ",", "clientProtocol", ",", "endpointCreator", ")", ":", "reactor", "=", "reactorBuilder", ".", "buildReactor", "(", ")", "serverProtocol", ".", "_setAttributes", "(", "reactor", ",", "D...
connect two protocols using endpoints and a new reactor instance .
train
false
30,683
def remove_ip_addresses(inventory): hostvars = inventory['_meta']['hostvars'] for (host, variables) in hostvars.items(): if variables.get('is_metal', False): continue ip_vars = ['container_networks', 'container_address', 'ansible_host', 'ansible_ssh_host'] for ip_var in ip_vars: variables.pop(ip_var, None)
[ "def", "remove_ip_addresses", "(", "inventory", ")", ":", "hostvars", "=", "inventory", "[", "'_meta'", "]", "[", "'hostvars'", "]", "for", "(", "host", ",", "variables", ")", "in", "hostvars", ".", "items", "(", ")", ":", "if", "variables", ".", "get", ...
removes container ip address information from the inventory dictionary all container_networks information for containers will be deleted .
train
false
30,685
def _dict_with_extra_specs(inst_type_query): inst_type_dict = dict(inst_type_query) extra_specs = {x['key']: x['value'] for x in inst_type_query['extra_specs']} inst_type_dict['extra_specs'] = extra_specs return inst_type_dict
[ "def", "_dict_with_extra_specs", "(", "inst_type_query", ")", ":", "inst_type_dict", "=", "dict", "(", "inst_type_query", ")", "extra_specs", "=", "{", "x", "[", "'key'", "]", ":", "x", "[", "'value'", "]", "for", "x", "in", "inst_type_query", "[", "'extra_s...
takes an instance or instance type query returned by sqlalchemy and returns it as a dictionary .
train
false
30,686
def arccsch(val): return numpy.arcsinh((1.0 / val))
[ "def", "arccsch", "(", "val", ")", ":", "return", "numpy", ".", "arcsinh", "(", "(", "1.0", "/", "val", ")", ")" ]
inverse hyperbolic cosecant .
train
false
30,688
def _find_match(ele, lst): for _ele in lst: for match_key in _MATCH_KEYS: if (_ele.get(match_key) == ele.get(match_key)): return _ele
[ "def", "_find_match", "(", "ele", ",", "lst", ")", ":", "for", "_ele", "in", "lst", ":", "for", "match_key", "in", "_MATCH_KEYS", ":", "if", "(", "_ele", ".", "get", "(", "match_key", ")", "==", "ele", ".", "get", "(", "match_key", ")", ")", ":", ...
find a matching element in a list .
train
true
30,689
def lum_contrast(clip, lum=0, contrast=0, contrast_thr=127): def fl_image(im): im = (1.0 * im) corrected = ((im + lum) + (contrast * (im - float(contrast_thr)))) corrected[(corrected < 0)] = 0 corrected[(corrected > 255)] = 255 return corrected.astype('uint8') return clip.fl_image(fl_image)
[ "def", "lum_contrast", "(", "clip", ",", "lum", "=", "0", ",", "contrast", "=", "0", ",", "contrast_thr", "=", "127", ")", ":", "def", "fl_image", "(", "im", ")", ":", "im", "=", "(", "1.0", "*", "im", ")", "corrected", "=", "(", "(", "im", "+"...
luminosity-contrast correction of a clip .
train
false
30,690
def word_pairs(text): last_word = None for word in words(text): if (last_word is not None): (yield (last_word, word)) last_word = word (yield (last_word, '<end>'))
[ "def", "word_pairs", "(", "text", ")", ":", "last_word", "=", "None", "for", "word", "in", "words", "(", "text", ")", ":", "if", "(", "last_word", "is", "not", "None", ")", ":", "(", "yield", "(", "last_word", ",", "word", ")", ")", "last_word", "=...
given some text .
train
false
30,691
@api_view((u'GET',)) @renderer_classes((TemplateHTMLRenderer,)) def example(request): data = {u'object': u'foobar'} return Response(data, template_name=u'example.html')
[ "@", "api_view", "(", "(", "u'GET'", ",", ")", ")", "@", "renderer_classes", "(", "(", "TemplateHTMLRenderer", ",", ")", ")", "def", "example", "(", "request", ")", ":", "data", "=", "{", "u'object'", ":", "u'foobar'", "}", "return", "Response", "(", "...
a view that can returns an html representation .
train
false
30,692
def createAssembly(file_id, namespace_id, bar_num, default_filename='foo'): file_name = ((((Directory.GetCurrentDirectory() + '\\') + default_filename) + str(file_id)) + '.cs') file = open(file_name, 'w') print >>file, (cs_ipy % (str(namespace_id), bar_num)) file.close() compileAssembly(file_name)
[ "def", "createAssembly", "(", "file_id", ",", "namespace_id", ",", "bar_num", ",", "default_filename", "=", "'foo'", ")", ":", "file_name", "=", "(", "(", "(", "(", "Directory", ".", "GetCurrentDirectory", "(", ")", "+", "'\\\\'", ")", "+", "default_filename...
helper function creates a single "foo" assembly .
train
false
30,693
def subjectivity(s, **kwargs): return sentiment(s, **kwargs)[1]
[ "def", "subjectivity", "(", "s", ",", "**", "kwargs", ")", ":", "return", "sentiment", "(", "s", ",", "**", "kwargs", ")", "[", "1", "]" ]
returns the sentence subjectivity between 0 .
train
false
30,695
def finddir(o, match, case=False): if case: names = [(name, name) for name in dir(o) if is_string_like(name)] else: names = [(name.lower(), name) for name in dir(o) if is_string_like(name)] match = match.lower() return [orig for (name, orig) in names if (name.find(match) >= 0)]
[ "def", "finddir", "(", "o", ",", "match", ",", "case", "=", "False", ")", ":", "if", "case", ":", "names", "=", "[", "(", "name", ",", "name", ")", "for", "name", "in", "dir", "(", "o", ")", "if", "is_string_like", "(", "name", ")", "]", "else"...
return all attributes of *o* which match string in match .
train
false
30,697
def logo(): return load('logo.png')
[ "def", "logo", "(", ")", ":", "return", "load", "(", "'logo.png'", ")" ]
scikit-image logo .
train
false
30,699
def signin_redirect(redirect=None, user=None): if redirect: return redirect elif (user is not None): return (userena_settings.USERENA_SIGNIN_REDIRECT_URL % {'username': user.username}) else: return settings.LOGIN_REDIRECT_URL
[ "def", "signin_redirect", "(", "redirect", "=", "None", ",", "user", "=", "None", ")", ":", "if", "redirect", ":", "return", "redirect", "elif", "(", "user", "is", "not", "None", ")", ":", "return", "(", "userena_settings", ".", "USERENA_SIGNIN_REDIRECT_URL"...
redirect user after successful sign in .
train
true
30,700
def dark_palette(color, n_colors=6, reverse=False, as_cmap=False): gray = '#222222' colors = ([color, gray] if reverse else [gray, color]) return blend_palette(colors, n_colors, as_cmap)
[ "def", "dark_palette", "(", "color", ",", "n_colors", "=", "6", ",", "reverse", "=", "False", ",", "as_cmap", "=", "False", ")", ":", "gray", "=", "'#222222'", "colors", "=", "(", "[", "color", ",", "gray", "]", "if", "reverse", "else", "[", "gray", ...
make a sequential palette that blends from dark to color .
train
true
30,702
def has_identity(object): state = attributes.instance_state(object) return state.has_identity
[ "def", "has_identity", "(", "object", ")", ":", "state", "=", "attributes", ".", "instance_state", "(", "object", ")", "return", "state", ".", "has_identity" ]
return true if the given object has a database identity .
train
false
30,703
def xmlattrstr(attrs): from xml.sax.saxutils import quoteattr s = '' names = attrs.keys() names.sort() for name in names: s += (' %s=%s' % (name, quoteattr(str(attrs[name])))) return s
[ "def", "xmlattrstr", "(", "attrs", ")", ":", "from", "xml", ".", "sax", ".", "saxutils", "import", "quoteattr", "s", "=", "''", "names", "=", "attrs", ".", "keys", "(", ")", "names", ".", "sort", "(", ")", "for", "name", "in", "names", ":", "s", ...
construct an xml-safe attribute string from the given attributes "attrs" is a dictionary of attributes the returned attribute string includes a leading space .
train
false
30,704
def _createPublicKey(key): if (not isinstance(key, RSAKey)): raise AssertionError() return _createPublicRSAKey(key.n, key.e)
[ "def", "_createPublicKey", "(", "key", ")", ":", "if", "(", "not", "isinstance", "(", "key", ",", "RSAKey", ")", ")", ":", "raise", "AssertionError", "(", ")", "return", "_createPublicRSAKey", "(", "key", ".", "n", ",", "key", ".", "e", ")" ]
create a new public key .
train
false