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,620
def get_sentry_conf(): try: ctx = click.get_current_context() return ctx.obj['config'] except (RuntimeError, KeyError, TypeError): try: return os.environ['SENTRY_CONF'] except KeyError: return '~/.sentry'
[ "def", "get_sentry_conf", "(", ")", ":", "try", ":", "ctx", "=", "click", ".", "get_current_context", "(", ")", "return", "ctx", ".", "obj", "[", "'config'", "]", "except", "(", "RuntimeError", ",", "KeyError", ",", "TypeError", ")", ":", "try", ":", "return", "os", ".", "environ", "[", "'SENTRY_CONF'", "]", "except", "KeyError", ":", "return", "'~/.sentry'" ]
fetch the sentry_conf value .
train
false
36,621
def send_msg_v2(module, token, room, msg_from, msg, msg_format='text', color='yellow', notify=False, api=NOTIFY_URI_V2): headers = {'Authorization': ('Bearer %s' % token), 'Content-Type': 'application/json'} body = dict() body['message'] = msg body['color'] = color body['message_format'] = msg_format body['notify'] = notify POST_URL = (api + NOTIFY_URI_V2) url = POST_URL.replace('{id_or_name}', urllib.pathname2url(room)) data = json.dumps(body) if module.check_mode: module.exit_json(changed=False) (response, info) = fetch_url(module, url, data=data, headers=headers, method='POST') if (info['status'] in [200, 204]): return response.read() else: module.fail_json(msg=('failed to send message, return status=%s' % str(info['status'])))
[ "def", "send_msg_v2", "(", "module", ",", "token", ",", "room", ",", "msg_from", ",", "msg", ",", "msg_format", "=", "'text'", ",", "color", "=", "'yellow'", ",", "notify", "=", "False", ",", "api", "=", "NOTIFY_URI_V2", ")", ":", "headers", "=", "{", "'Authorization'", ":", "(", "'Bearer %s'", "%", "token", ")", ",", "'Content-Type'", ":", "'application/json'", "}", "body", "=", "dict", "(", ")", "body", "[", "'message'", "]", "=", "msg", "body", "[", "'color'", "]", "=", "color", "body", "[", "'message_format'", "]", "=", "msg_format", "body", "[", "'notify'", "]", "=", "notify", "POST_URL", "=", "(", "api", "+", "NOTIFY_URI_V2", ")", "url", "=", "POST_URL", ".", "replace", "(", "'{id_or_name}'", ",", "urllib", ".", "pathname2url", "(", "room", ")", ")", "data", "=", "json", ".", "dumps", "(", "body", ")", "if", "module", ".", "check_mode", ":", "module", ".", "exit_json", "(", "changed", "=", "False", ")", "(", "response", ",", "info", ")", "=", "fetch_url", "(", "module", ",", "url", ",", "data", "=", "data", ",", "headers", "=", "headers", ",", "method", "=", "'POST'", ")", "if", "(", "info", "[", "'status'", "]", "in", "[", "200", ",", "204", "]", ")", ":", "return", "response", ".", "read", "(", ")", "else", ":", "module", ".", "fail_json", "(", "msg", "=", "(", "'failed to send message, return status=%s'", "%", "str", "(", "info", "[", "'status'", "]", ")", ")", ")" ]
sending message to hipchat v2 server .
train
false
36,622
def filter_pathscrub(val, os_mode=None): return pathscrub(val, os_mode)
[ "def", "filter_pathscrub", "(", "val", ",", "os_mode", "=", "None", ")", ":", "return", "pathscrub", "(", "val", ",", "os_mode", ")" ]
replace problematic characters in a path .
train
false
36,624
def getTimezone(profile): try: return timezone(profile['timezone']) except: return None
[ "def", "getTimezone", "(", "profile", ")", ":", "try", ":", "return", "timezone", "(", "profile", "[", "'timezone'", "]", ")", "except", ":", "return", "None" ]
returns the pytz timezone for a given profile .
train
false
36,625
def resolve_parent(p): try: st = os.lstat(p) except OSError: st = None if (st and stat.S_ISLNK(st.st_mode)): (dir, name) = os.path.split(p) dir = os.path.realpath(dir) out = os.path.join(dir, name) else: out = os.path.realpath(p) return out
[ "def", "resolve_parent", "(", "p", ")", ":", "try", ":", "st", "=", "os", ".", "lstat", "(", "p", ")", "except", "OSError", ":", "st", "=", "None", "if", "(", "st", "and", "stat", ".", "S_ISLNK", "(", "st", ".", "st_mode", ")", ")", ":", "(", "dir", ",", "name", ")", "=", "os", ".", "path", ".", "split", "(", "p", ")", "dir", "=", "os", ".", "path", ".", "realpath", "(", "dir", ")", "out", "=", "os", ".", "path", ".", "join", "(", "dir", ",", "name", ")", "else", ":", "out", "=", "os", ".", "path", ".", "realpath", "(", "p", ")", "return", "out" ]
return the absolute path of a file without following any final symlink .
train
false
36,626
def load_strings(helpers, default='en'): global strings p = helpers.get_platform() locale_dir = helpers.get_resource_path('locale') translations = {} for filename in os.listdir(locale_dir): abs_filename = os.path.join(locale_dir, filename) (lang, ext) = os.path.splitext(filename) if abs_filename.endswith('.json'): lang_json = open(abs_filename, encoding='utf-8').read() translations[lang] = json.loads(lang_json) strings = translations[default] (lc, enc) = locale.getdefaultlocale() if lc: lang = lc[:2] if (lang in translations): for key in translations[default]: if (key in translations[lang]): strings[key] = translations[lang][key]
[ "def", "load_strings", "(", "helpers", ",", "default", "=", "'en'", ")", ":", "global", "strings", "p", "=", "helpers", ".", "get_platform", "(", ")", "locale_dir", "=", "helpers", ".", "get_resource_path", "(", "'locale'", ")", "translations", "=", "{", "}", "for", "filename", "in", "os", ".", "listdir", "(", "locale_dir", ")", ":", "abs_filename", "=", "os", ".", "path", ".", "join", "(", "locale_dir", ",", "filename", ")", "(", "lang", ",", "ext", ")", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "abs_filename", ".", "endswith", "(", "'.json'", ")", ":", "lang_json", "=", "open", "(", "abs_filename", ",", "encoding", "=", "'utf-8'", ")", ".", "read", "(", ")", "translations", "[", "lang", "]", "=", "json", ".", "loads", "(", "lang_json", ")", "strings", "=", "translations", "[", "default", "]", "(", "lc", ",", "enc", ")", "=", "locale", ".", "getdefaultlocale", "(", ")", "if", "lc", ":", "lang", "=", "lc", "[", ":", "2", "]", "if", "(", "lang", "in", "translations", ")", ":", "for", "key", "in", "translations", "[", "default", "]", ":", "if", "(", "key", "in", "translations", "[", "lang", "]", ")", ":", "strings", "[", "key", "]", "=", "translations", "[", "lang", "]", "[", "key", "]" ]
loads translated strings and fallback to english if the translation does not exist .
train
false
36,627
@nodes_or_number(0) def complete_graph(n, create_using=None): (n_name, nodes) = n G = empty_graph(n_name, create_using) G.name = ('complete_graph(%s)' % (n_name,)) if (len(nodes) > 1): if G.is_directed(): edges = itertools.permutations(nodes, 2) else: edges = itertools.combinations(nodes, 2) G.add_edges_from(edges) return G
[ "@", "nodes_or_number", "(", "0", ")", "def", "complete_graph", "(", "n", ",", "create_using", "=", "None", ")", ":", "(", "n_name", ",", "nodes", ")", "=", "n", "G", "=", "empty_graph", "(", "n_name", ",", "create_using", ")", "G", ".", "name", "=", "(", "'complete_graph(%s)'", "%", "(", "n_name", ",", ")", ")", "if", "(", "len", "(", "nodes", ")", ">", "1", ")", ":", "if", "G", ".", "is_directed", "(", ")", ":", "edges", "=", "itertools", ".", "permutations", "(", "nodes", ",", "2", ")", "else", ":", "edges", "=", "itertools", ".", "combinations", "(", "nodes", ",", "2", ")", "G", ".", "add_edges_from", "(", "edges", ")", "return", "G" ]
return the complete graph k_n with n nodes .
train
false
36,628
def test_html_rendered_properly(): request = HttpRequest() setattr(request, '_messages', default_storage(request)) info(request, 'Title', 'Body') messages = django_messages.get_messages(request) template = get_env().get_template('messages.html') html = template.render({'messages': messages}) assert ('<h2>' in html)
[ "def", "test_html_rendered_properly", "(", ")", ":", "request", "=", "HttpRequest", "(", ")", "setattr", "(", "request", ",", "'_messages'", ",", "default_storage", "(", "request", ")", ")", "info", "(", "request", ",", "'Title'", ",", "'Body'", ")", "messages", "=", "django_messages", ".", "get_messages", "(", "request", ")", "template", "=", "get_env", "(", ")", ".", "get_template", "(", "'messages.html'", ")", "html", "=", "template", ".", "render", "(", "{", "'messages'", ":", "messages", "}", ")", "assert", "(", "'<h2>'", "in", "html", ")" ]
html markup is properly displayed in final template .
train
false
36,629
def MultiLineEqual(expected, actual): if (actual == expected): return True print "Error: FLAGS.MainModuleHelp() didn't return the expected result." print 'Got:' print actual print '[End of got]' actual_lines = actual.split('\n') expected_lines = expected.split('\n') num_actual_lines = len(actual_lines) num_expected_lines = len(expected_lines) if (num_actual_lines != num_expected_lines): print ('Number of actual lines = %d, expected %d' % (num_actual_lines, num_expected_lines)) num_to_match = min(num_actual_lines, num_expected_lines) for i in range(num_to_match): if (actual_lines[i] != expected_lines[i]): print 'One discrepancy: Got:' print actual_lines[i] print 'Expected:' print expected_lines[i] break else: if (num_actual_lines > num_expected_lines): print 'New help line:' print actual_lines[num_expected_lines] elif (num_expected_lines > num_actual_lines): print 'Missing expected help line:' print expected_lines[num_actual_lines] else: print 'Bug in this test -- discrepancy detected but not found.' return False
[ "def", "MultiLineEqual", "(", "expected", ",", "actual", ")", ":", "if", "(", "actual", "==", "expected", ")", ":", "return", "True", "print", "\"Error: FLAGS.MainModuleHelp() didn't return the expected result.\"", "print", "'Got:'", "print", "actual", "print", "'[End of got]'", "actual_lines", "=", "actual", ".", "split", "(", "'\\n'", ")", "expected_lines", "=", "expected", ".", "split", "(", "'\\n'", ")", "num_actual_lines", "=", "len", "(", "actual_lines", ")", "num_expected_lines", "=", "len", "(", "expected_lines", ")", "if", "(", "num_actual_lines", "!=", "num_expected_lines", ")", ":", "print", "(", "'Number of actual lines = %d, expected %d'", "%", "(", "num_actual_lines", ",", "num_expected_lines", ")", ")", "num_to_match", "=", "min", "(", "num_actual_lines", ",", "num_expected_lines", ")", "for", "i", "in", "range", "(", "num_to_match", ")", ":", "if", "(", "actual_lines", "[", "i", "]", "!=", "expected_lines", "[", "i", "]", ")", ":", "print", "'One discrepancy: Got:'", "print", "actual_lines", "[", "i", "]", "print", "'Expected:'", "print", "expected_lines", "[", "i", "]", "break", "else", ":", "if", "(", "num_actual_lines", ">", "num_expected_lines", ")", ":", "print", "'New help line:'", "print", "actual_lines", "[", "num_expected_lines", "]", "elif", "(", "num_expected_lines", ">", "num_actual_lines", ")", ":", "print", "'Missing expected help line:'", "print", "expected_lines", "[", "num_actual_lines", "]", "else", ":", "print", "'Bug in this test -- discrepancy detected but not found.'", "return", "False" ]
returns true if expected == actual .
train
false
36,630
@libvirt_conn def get_dnsmasq_dhcp_lease(conn, vm_name): domain_name = ('vagrant_' + vm_name) mac_address = get_mac_address(conn, domain_name) with open('/var/lib/libvirt/dnsmasq/vagrant-private-dhcp.leases') as leases_file: reader = csv.reader(leases_file, delimiter=' ') for row in reader: (lease_mac, lease_ip, lease_vm_name) = row[1:4] if (not ((lease_mac == mac_address) and (lease_vm_name == vm_name))): continue return lease_ip raise NoDHCPLeaseException()
[ "@", "libvirt_conn", "def", "get_dnsmasq_dhcp_lease", "(", "conn", ",", "vm_name", ")", ":", "domain_name", "=", "(", "'vagrant_'", "+", "vm_name", ")", "mac_address", "=", "get_mac_address", "(", "conn", ",", "domain_name", ")", "with", "open", "(", "'/var/lib/libvirt/dnsmasq/vagrant-private-dhcp.leases'", ")", "as", "leases_file", ":", "reader", "=", "csv", ".", "reader", "(", "leases_file", ",", "delimiter", "=", "' '", ")", "for", "row", "in", "reader", ":", "(", "lease_mac", ",", "lease_ip", ",", "lease_vm_name", ")", "=", "row", "[", "1", ":", "4", "]", "if", "(", "not", "(", "(", "lease_mac", "==", "mac_address", ")", "and", "(", "lease_vm_name", "==", "vm_name", ")", ")", ")", ":", "continue", "return", "lease_ip", "raise", "NoDHCPLeaseException", "(", ")" ]
in libvirt under 1 .
train
false
36,631
def Horizon(data=None, x=None, y=None, series=None, **kws): kws['x'] = x kws['y'] = y kws['series'] = series tools = kws.get('tools', True) if (tools == True): tools = 'save,reset' elif isinstance(tools, string_types): tools = tools.replace('pan', '') tools = tools.replace('wheel_zoom', '') tools = tools.replace('box_zoom', '') tools = tools.replace(',,', ',') kws['tools'] = tools chart = create_and_build(HorizonBuilder, data, **kws) chart.left[0].visible = False chart.extra_y_ranges = {'series': FactorRange(factors=chart._builders[0].series_names)} chart.add_layout(CategoricalAxis(y_range_name='series'), 'left') return chart
[ "def", "Horizon", "(", "data", "=", "None", ",", "x", "=", "None", ",", "y", "=", "None", ",", "series", "=", "None", ",", "**", "kws", ")", ":", "kws", "[", "'x'", "]", "=", "x", "kws", "[", "'y'", "]", "=", "y", "kws", "[", "'series'", "]", "=", "series", "tools", "=", "kws", ".", "get", "(", "'tools'", ",", "True", ")", "if", "(", "tools", "==", "True", ")", ":", "tools", "=", "'save,reset'", "elif", "isinstance", "(", "tools", ",", "string_types", ")", ":", "tools", "=", "tools", ".", "replace", "(", "'pan'", ",", "''", ")", "tools", "=", "tools", ".", "replace", "(", "'wheel_zoom'", ",", "''", ")", "tools", "=", "tools", ".", "replace", "(", "'box_zoom'", ",", "''", ")", "tools", "=", "tools", ".", "replace", "(", "',,'", ",", "','", ")", "kws", "[", "'tools'", "]", "=", "tools", "chart", "=", "create_and_build", "(", "HorizonBuilder", ",", "data", ",", "**", "kws", ")", "chart", ".", "left", "[", "0", "]", ".", "visible", "=", "False", "chart", ".", "extra_y_ranges", "=", "{", "'series'", ":", "FactorRange", "(", "factors", "=", "chart", ".", "_builders", "[", "0", "]", ".", "series_names", ")", "}", "chart", ".", "add_layout", "(", "CategoricalAxis", "(", "y_range_name", "=", "'series'", ")", ",", "'left'", ")", "return", "chart" ]
create a horizon chart using :class:horizonbuilder <bokeh .
train
false
36,632
@cache_permission def can_lock_subproject(user, project): return check_permission(user, project, 'trans.lock_subproject')
[ "@", "cache_permission", "def", "can_lock_subproject", "(", "user", ",", "project", ")", ":", "return", "check_permission", "(", "user", ",", "project", ",", "'trans.lock_subproject'", ")" ]
checks whether user can lock translation subproject .
train
false
36,633
@utils.arg('server', metavar='<server>', help=_('Name or ID of server.')) def do_lock(cs, args): _find_server(cs, args.server).lock()
[ "@", "utils", ".", "arg", "(", "'server'", ",", "metavar", "=", "'<server>'", ",", "help", "=", "_", "(", "'Name or ID of server.'", ")", ")", "def", "do_lock", "(", "cs", ",", "args", ")", ":", "_find_server", "(", "cs", ",", "args", ".", "server", ")", ".", "lock", "(", ")" ]
lock a server .
train
false
36,634
def llen(key, host=None, port=None, db=None, password=None): server = _connect(host, port, db, password) return server.llen(key)
[ "def", "llen", "(", "key", ",", "host", "=", "None", ",", "port", "=", "None", ",", "db", "=", "None", ",", "password", "=", "None", ")", ":", "server", "=", "_connect", "(", "host", ",", "port", ",", "db", ",", "password", ")", "return", "server", ".", "llen", "(", "key", ")" ]
get the length of a list in redis cli example: .
train
true
36,635
def pack_ieee(value): return np.fromstring(value.tostring(), np.ubyte).reshape((value.shape + (4,)))
[ "def", "pack_ieee", "(", "value", ")", ":", "return", "np", ".", "fromstring", "(", "value", ".", "tostring", "(", ")", ",", "np", ".", "ubyte", ")", ".", "reshape", "(", "(", "value", ".", "shape", "+", "(", "4", ",", ")", ")", ")" ]
packs float ieee binary representation into 4 unsigned int8 returns pack: array packed interpolation kernel .
train
true
36,636
def get_completed_exploration_ids(user_id, collection_id): progress_model = user_models.CollectionProgressModel.get(user_id, collection_id) return (progress_model.completed_explorations if progress_model else [])
[ "def", "get_completed_exploration_ids", "(", "user_id", ",", "collection_id", ")", ":", "progress_model", "=", "user_models", ".", "CollectionProgressModel", ".", "get", "(", "user_id", ",", "collection_id", ")", "return", "(", "progress_model", ".", "completed_explorations", "if", "progress_model", "else", "[", "]", ")" ]
returns a list of explorations the user has completed within the context of the provided collection .
train
false
36,637
def correlate_data(data, timestamps): timestamps = list(timestamps) data_by_frame = [[] for i in timestamps] frame_idx = 0 data_index = 0 data.sort(key=(lambda d: d['timestamp'])) while True: try: datum = data[data_index] ts = ((timestamps[frame_idx] + timestamps[(frame_idx + 1)]) / 2.0) except IndexError: break if (datum['timestamp'] <= ts): datum['index'] = frame_idx data_by_frame[frame_idx].append(datum) data_index += 1 else: frame_idx += 1 return data_by_frame
[ "def", "correlate_data", "(", "data", ",", "timestamps", ")", ":", "timestamps", "=", "list", "(", "timestamps", ")", "data_by_frame", "=", "[", "[", "]", "for", "i", "in", "timestamps", "]", "frame_idx", "=", "0", "data_index", "=", "0", "data", ".", "sort", "(", "key", "=", "(", "lambda", "d", ":", "d", "[", "'timestamp'", "]", ")", ")", "while", "True", ":", "try", ":", "datum", "=", "data", "[", "data_index", "]", "ts", "=", "(", "(", "timestamps", "[", "frame_idx", "]", "+", "timestamps", "[", "(", "frame_idx", "+", "1", ")", "]", ")", "/", "2.0", ")", "except", "IndexError", ":", "break", "if", "(", "datum", "[", "'timestamp'", "]", "<=", "ts", ")", ":", "datum", "[", "'index'", "]", "=", "frame_idx", "data_by_frame", "[", "frame_idx", "]", ".", "append", "(", "datum", ")", "data_index", "+=", "1", "else", ":", "frame_idx", "+=", "1", "return", "data_by_frame" ]
data: list of data : each datum is a dict with at least: timestamp: float timestamps: timestamps list to correlate data to this takes a data list and a timestamps list and makes a new list with the length of the number of timestamps .
train
false
36,638
def inheritance_diagram_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): node = inheritance_diagram() class_names = arguments graph = InheritanceGraph(class_names) for name in graph.get_all_class_names(): (refnodes, x) = xfileref_role('class', (':class:`%s`' % name), name, 0, state) node.extend(refnodes) node['graph'] = graph node['parts'] = options.get('parts', 0) node['content'] = ' '.join(class_names) return [node]
[ "def", "inheritance_diagram_directive", "(", "name", ",", "arguments", ",", "options", ",", "content", ",", "lineno", ",", "content_offset", ",", "block_text", ",", "state", ",", "state_machine", ")", ":", "node", "=", "inheritance_diagram", "(", ")", "class_names", "=", "arguments", "graph", "=", "InheritanceGraph", "(", "class_names", ")", "for", "name", "in", "graph", ".", "get_all_class_names", "(", ")", ":", "(", "refnodes", ",", "x", ")", "=", "xfileref_role", "(", "'class'", ",", "(", "':class:`%s`'", "%", "name", ")", ",", "name", ",", "0", ",", "state", ")", "node", ".", "extend", "(", "refnodes", ")", "node", "[", "'graph'", "]", "=", "graph", "node", "[", "'parts'", "]", "=", "options", ".", "get", "(", "'parts'", ",", "0", ")", "node", "[", "'content'", "]", "=", "' '", ".", "join", "(", "class_names", ")", "return", "[", "node", "]" ]
run when the inheritance_diagram directive is first encountered .
train
true
36,639
def get_cvxopt_dense_intf(): import cvxpy.interface.cvxopt_interface.valuerix_interface as dmi return dmi.DenseMatrixInterface()
[ "def", "get_cvxopt_dense_intf", "(", ")", ":", "import", "cvxpy", ".", "interface", ".", "cvxopt_interface", ".", "valuerix_interface", "as", "dmi", "return", "dmi", ".", "DenseMatrixInterface", "(", ")" ]
dynamic import of cvxopt dense interface .
train
false
36,640
def get_pointer_arr(n): GeomArr = (GEOM_PTR * n) return GeomArr()
[ "def", "get_pointer_arr", "(", "n", ")", ":", "GeomArr", "=", "(", "GEOM_PTR", "*", "n", ")", "return", "GeomArr", "(", ")" ]
gets a ctypes pointer array for geosgeom_t opaque pointer .
train
false
36,644
def addShaft(derivation, negatives, positives): if (len(derivation.shaftPath) < 3): return positiveVertexes = matrix.getVertexes(positives) bottomPath = euclidean.getTopPath(positiveVertexes) topPath = euclidean.getBottomByPath(positiveVertexes) copyShallow = derivation.elementNode.getCopyShallow() copyShallow.attributes['path'] = [Vector3(0.0, 0.0, bottomPath), Vector3(0.0, 0.0, topPath)] extrudeDerivation = extrude.ExtrudeDerivation(copyShallow) extrude.addNegativesPositives(extrudeDerivation, negatives, [derivation.shaftPath], positives)
[ "def", "addShaft", "(", "derivation", ",", "negatives", ",", "positives", ")", ":", "if", "(", "len", "(", "derivation", ".", "shaftPath", ")", "<", "3", ")", ":", "return", "positiveVertexes", "=", "matrix", ".", "getVertexes", "(", "positives", ")", "bottomPath", "=", "euclidean", ".", "getTopPath", "(", "positiveVertexes", ")", "topPath", "=", "euclidean", ".", "getBottomByPath", "(", "positiveVertexes", ")", "copyShallow", "=", "derivation", ".", "elementNode", ".", "getCopyShallow", "(", ")", "copyShallow", ".", "attributes", "[", "'path'", "]", "=", "[", "Vector3", "(", "0.0", ",", "0.0", ",", "bottomPath", ")", ",", "Vector3", "(", "0.0", ",", "0.0", ",", "topPath", ")", "]", "extrudeDerivation", "=", "extrude", ".", "ExtrudeDerivation", "(", "copyShallow", ")", "extrude", ".", "addNegativesPositives", "(", "extrudeDerivation", ",", "negatives", ",", "[", "derivation", ".", "shaftPath", "]", ",", "positives", ")" ]
add shaft .
train
false
36,645
def test_no_loglines(request, quteproc_new): if request.config.webengine: pytest.skip('qute:log is not implemented with QtWebEngine yet') quteproc_new.start(args=(['--temp-basedir', '--loglines=0'] + _base_args(request.config))) quteproc_new.open_path('qute:log') assert (quteproc_new.get_content() == 'Log output was disabled.')
[ "def", "test_no_loglines", "(", "request", ",", "quteproc_new", ")", ":", "if", "request", ".", "config", ".", "webengine", ":", "pytest", ".", "skip", "(", "'qute:log is not implemented with QtWebEngine yet'", ")", "quteproc_new", ".", "start", "(", "args", "=", "(", "[", "'--temp-basedir'", ",", "'--loglines=0'", "]", "+", "_base_args", "(", "request", ".", "config", ")", ")", ")", "quteproc_new", ".", "open_path", "(", "'qute:log'", ")", "assert", "(", "quteproc_new", ".", "get_content", "(", ")", "==", "'Log output was disabled.'", ")" ]
test qute:log with --loglines=0 .
train
false
36,646
def plot_epipolar_line(im, F, x, epipole=None, show_epipole=True): (m, n) = im.shape[:2] line = dot(F, x) t = linspace(0, n, 100) lt = array([((line[2] + (line[0] * tt)) / (- line[1])) for tt in t]) ndx = ((lt >= 0) & (lt < m)) plot(t[ndx], lt[ndx], linewidth=2) if show_epipole: if (epipole is None): epipole = compute_epipole(F) plot((epipole[0] / epipole[2]), (epipole[1] / epipole[2]), 'r*')
[ "def", "plot_epipolar_line", "(", "im", ",", "F", ",", "x", ",", "epipole", "=", "None", ",", "show_epipole", "=", "True", ")", ":", "(", "m", ",", "n", ")", "=", "im", ".", "shape", "[", ":", "2", "]", "line", "=", "dot", "(", "F", ",", "x", ")", "t", "=", "linspace", "(", "0", ",", "n", ",", "100", ")", "lt", "=", "array", "(", "[", "(", "(", "line", "[", "2", "]", "+", "(", "line", "[", "0", "]", "*", "tt", ")", ")", "/", "(", "-", "line", "[", "1", "]", ")", ")", "for", "tt", "in", "t", "]", ")", "ndx", "=", "(", "(", "lt", ">=", "0", ")", "&", "(", "lt", "<", "m", ")", ")", "plot", "(", "t", "[", "ndx", "]", ",", "lt", "[", "ndx", "]", ",", "linewidth", "=", "2", ")", "if", "show_epipole", ":", "if", "(", "epipole", "is", "None", ")", ":", "epipole", "=", "compute_epipole", "(", "F", ")", "plot", "(", "(", "epipole", "[", "0", "]", "/", "epipole", "[", "2", "]", ")", ",", "(", "epipole", "[", "1", "]", "/", "epipole", "[", "2", "]", ")", ",", "'r*'", ")" ]
plot the epipole and epipolar line f*x=0 in an image .
train
false
36,647
@pytest.mark.parametrize(u'pattern', [pattern3, pattern4]) def test_issue118_prefix_reorder(doc, pattern): ORG = doc.vocab.strings[u'ORG'] matcher = Matcher(doc.vocab, {u'BostonCeltics': (u'ORG', {}, pattern)}) assert (len(list(doc.ents)) == 0) matches = [(ent_type, start, end) for (ent_id, ent_type, start, end) in matcher(doc)] doc.ents += tuple(matches)[1:] assert (matches == [(ORG, 9, 10), (ORG, 9, 11)]) ents = doc.ents assert (len(ents) == 1) assert (ents[0].label == ORG) assert (ents[0].start == 9) assert (ents[0].end == 11)
[ "@", "pytest", ".", "mark", ".", "parametrize", "(", "u'pattern'", ",", "[", "pattern3", ",", "pattern4", "]", ")", "def", "test_issue118_prefix_reorder", "(", "doc", ",", "pattern", ")", ":", "ORG", "=", "doc", ".", "vocab", ".", "strings", "[", "u'ORG'", "]", "matcher", "=", "Matcher", "(", "doc", ".", "vocab", ",", "{", "u'BostonCeltics'", ":", "(", "u'ORG'", ",", "{", "}", ",", "pattern", ")", "}", ")", "assert", "(", "len", "(", "list", "(", "doc", ".", "ents", ")", ")", "==", "0", ")", "matches", "=", "[", "(", "ent_type", ",", "start", ",", "end", ")", "for", "(", "ent_id", ",", "ent_type", ",", "start", ",", "end", ")", "in", "matcher", "(", "doc", ")", "]", "doc", ".", "ents", "+=", "tuple", "(", "matches", ")", "[", "1", ":", "]", "assert", "(", "matches", "==", "[", "(", "ORG", ",", "9", ",", "10", ")", ",", "(", "ORG", ",", "9", ",", "11", ")", "]", ")", "ents", "=", "doc", ".", "ents", "assert", "(", "len", "(", "ents", ")", "==", "1", ")", "assert", "(", "ents", "[", "0", "]", ".", "label", "==", "ORG", ")", "assert", "(", "ents", "[", "0", "]", ".", "start", "==", "9", ")", "assert", "(", "ents", "[", "0", "]", ".", "end", "==", "11", ")" ]
test a bug that arose from having overlapping matches .
train
false
36,650
def PacificDate(now): return datetime.date(*time.gmtime(PacificTime(now))[:3])
[ "def", "PacificDate", "(", "now", ")", ":", "return", "datetime", ".", "date", "(", "*", "time", ".", "gmtime", "(", "PacificTime", "(", "now", ")", ")", "[", ":", "3", "]", ")" ]
for a utc timestamp .
train
false
36,651
def rate_limiter(max_per_second): min_interval = (1.0 / float(max_per_second)) last_time_called = [0.0] def throttler(): elapsed = (time.clock() - last_time_called[0]) left_to_wait = (min_interval - elapsed) if (left_to_wait > 0): time.sleep(left_to_wait) last_time_called[0] = time.clock() return throttler
[ "def", "rate_limiter", "(", "max_per_second", ")", ":", "min_interval", "=", "(", "1.0", "/", "float", "(", "max_per_second", ")", ")", "last_time_called", "=", "[", "0.0", "]", "def", "throttler", "(", ")", ":", "elapsed", "=", "(", "time", ".", "clock", "(", ")", "-", "last_time_called", "[", "0", "]", ")", "left_to_wait", "=", "(", "min_interval", "-", "elapsed", ")", "if", "(", "left_to_wait", ">", "0", ")", ":", "time", ".", "sleep", "(", "left_to_wait", ")", "last_time_called", "[", "0", "]", "=", "time", ".", "clock", "(", ")", "return", "throttler" ]
limit number of calls to returned closure per second to max_per_second algorithm adapted from here: URL .
train
false
36,652
def delete_demo(exploration_id): if (not exp_domain.Exploration.is_demo_exploration_id(exploration_id)): raise Exception(('Invalid demo exploration id %s' % exploration_id)) exploration = get_exploration_by_id(exploration_id, strict=False) if (not exploration): logging.info(('Exploration with id %s was not deleted, because it does not exist.' % exploration_id)) else: delete_exploration(feconf.SYSTEM_COMMITTER_ID, exploration_id, force_deletion=True)
[ "def", "delete_demo", "(", "exploration_id", ")", ":", "if", "(", "not", "exp_domain", ".", "Exploration", ".", "is_demo_exploration_id", "(", "exploration_id", ")", ")", ":", "raise", "Exception", "(", "(", "'Invalid demo exploration id %s'", "%", "exploration_id", ")", ")", "exploration", "=", "get_exploration_by_id", "(", "exploration_id", ",", "strict", "=", "False", ")", "if", "(", "not", "exploration", ")", ":", "logging", ".", "info", "(", "(", "'Exploration with id %s was not deleted, because it does not exist.'", "%", "exploration_id", ")", ")", "else", ":", "delete_exploration", "(", "feconf", ".", "SYSTEM_COMMITTER_ID", ",", "exploration_id", ",", "force_deletion", "=", "True", ")" ]
deletes a single demo exploration .
train
false
36,654
def project_downloads(request, project_slug): project = get_object_or_404(Project.objects.protected(request.user), slug=project_slug) versions = Version.objects.public(user=request.user, project=project) version_data = SortedDict() for version in versions: data = version.get_downloads() if data: version_data[version] = data return render_to_response('projects/project_downloads.html', {'project': project, 'version_data': version_data, 'versions': versions}, context_instance=RequestContext(request))
[ "def", "project_downloads", "(", "request", ",", "project_slug", ")", ":", "project", "=", "get_object_or_404", "(", "Project", ".", "objects", ".", "protected", "(", "request", ".", "user", ")", ",", "slug", "=", "project_slug", ")", "versions", "=", "Version", ".", "objects", ".", "public", "(", "user", "=", "request", ".", "user", ",", "project", "=", "project", ")", "version_data", "=", "SortedDict", "(", ")", "for", "version", "in", "versions", ":", "data", "=", "version", ".", "get_downloads", "(", ")", "if", "data", ":", "version_data", "[", "version", "]", "=", "data", "return", "render_to_response", "(", "'projects/project_downloads.html'", ",", "{", "'project'", ":", "project", ",", "'version_data'", ":", "version_data", ",", "'versions'", ":", "versions", "}", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")" ]
a detail view for a project with various dataz .
train
false
36,655
def zoom_effect01(ax1, ax2, xmin, xmax, **kwargs): trans1 = blended_transform_factory(ax1.transData, ax1.transAxes) trans2 = blended_transform_factory(ax2.transData, ax2.transAxes) bbox = Bbox.from_extents(xmin, 0, xmax, 1) mybbox1 = TransformedBbox(bbox, trans1) mybbox2 = TransformedBbox(bbox, trans2) prop_patches = kwargs.copy() prop_patches['ec'] = 'none' prop_patches['alpha'] = 0.2 (c1, c2, bbox_patch1, bbox_patch2, p) = connect_bbox(mybbox1, mybbox2, loc1a=3, loc2a=2, loc1b=4, loc2b=1, prop_lines=kwargs, prop_patches=prop_patches) ax1.add_patch(bbox_patch1) ax2.add_patch(bbox_patch2) ax2.add_patch(c1) ax2.add_patch(c2) ax2.add_patch(p) return (c1, c2, bbox_patch1, bbox_patch2, p)
[ "def", "zoom_effect01", "(", "ax1", ",", "ax2", ",", "xmin", ",", "xmax", ",", "**", "kwargs", ")", ":", "trans1", "=", "blended_transform_factory", "(", "ax1", ".", "transData", ",", "ax1", ".", "transAxes", ")", "trans2", "=", "blended_transform_factory", "(", "ax2", ".", "transData", ",", "ax2", ".", "transAxes", ")", "bbox", "=", "Bbox", ".", "from_extents", "(", "xmin", ",", "0", ",", "xmax", ",", "1", ")", "mybbox1", "=", "TransformedBbox", "(", "bbox", ",", "trans1", ")", "mybbox2", "=", "TransformedBbox", "(", "bbox", ",", "trans2", ")", "prop_patches", "=", "kwargs", ".", "copy", "(", ")", "prop_patches", "[", "'ec'", "]", "=", "'none'", "prop_patches", "[", "'alpha'", "]", "=", "0.2", "(", "c1", ",", "c2", ",", "bbox_patch1", ",", "bbox_patch2", ",", "p", ")", "=", "connect_bbox", "(", "mybbox1", ",", "mybbox2", ",", "loc1a", "=", "3", ",", "loc2a", "=", "2", ",", "loc1b", "=", "4", ",", "loc2b", "=", "1", ",", "prop_lines", "=", "kwargs", ",", "prop_patches", "=", "prop_patches", ")", "ax1", ".", "add_patch", "(", "bbox_patch1", ")", "ax2", ".", "add_patch", "(", "bbox_patch2", ")", "ax2", ".", "add_patch", "(", "c1", ")", "ax2", ".", "add_patch", "(", "c2", ")", "ax2", ".", "add_patch", "(", "p", ")", "return", "(", "c1", ",", "c2", ",", "bbox_patch1", ",", "bbox_patch2", ",", "p", ")" ]
ax1 : the main axes ax1 : the zoomed axes : the limits of the colored area in both plot axes .
train
false
36,657
def lpol_sdiff(s): return (([1] + ([0] * (s - 1))) + [(-1)])
[ "def", "lpol_sdiff", "(", "s", ")", ":", "return", "(", "(", "[", "1", "]", "+", "(", "[", "0", "]", "*", "(", "s", "-", "1", ")", ")", ")", "+", "[", "(", "-", "1", ")", "]", ")" ]
return coefficients for seasonal difference just a trivial convenience function parameters s : int number of periods in season returns sdiff : list .
train
false
36,658
def _to_blockdev_map(thing): if (not thing): return None if isinstance(thing, BlockDeviceMapping): return thing if isinstance(thing, six.string_types): thing = json.loads(thing) if (not isinstance(thing, dict)): log.error("Can't convert '{0}' of type {1} to a boto.ec2.blockdevicemapping.BlockDeviceMapping".format(thing, type(thing))) return None bdm = BlockDeviceMapping() for (d, t) in six.iteritems(thing): bdt = BlockDeviceType(ephemeral_name=t.get('ephemeral_name'), no_device=t.get('no_device', False), volume_id=t.get('volume_id'), snapshot_id=t.get('snapshot_id'), status=t.get('status'), attach_time=t.get('attach_time'), delete_on_termination=t.get('delete_on_termination', False), size=t.get('size'), volume_type=t.get('volume_type'), iops=t.get('iops'), encrypted=t.get('encrypted')) bdm[d] = bdt return bdm
[ "def", "_to_blockdev_map", "(", "thing", ")", ":", "if", "(", "not", "thing", ")", ":", "return", "None", "if", "isinstance", "(", "thing", ",", "BlockDeviceMapping", ")", ":", "return", "thing", "if", "isinstance", "(", "thing", ",", "six", ".", "string_types", ")", ":", "thing", "=", "json", ".", "loads", "(", "thing", ")", "if", "(", "not", "isinstance", "(", "thing", ",", "dict", ")", ")", ":", "log", ".", "error", "(", "\"Can't convert '{0}' of type {1} to a boto.ec2.blockdevicemapping.BlockDeviceMapping\"", ".", "format", "(", "thing", ",", "type", "(", "thing", ")", ")", ")", "return", "None", "bdm", "=", "BlockDeviceMapping", "(", ")", "for", "(", "d", ",", "t", ")", "in", "six", ".", "iteritems", "(", "thing", ")", ":", "bdt", "=", "BlockDeviceType", "(", "ephemeral_name", "=", "t", ".", "get", "(", "'ephemeral_name'", ")", ",", "no_device", "=", "t", ".", "get", "(", "'no_device'", ",", "False", ")", ",", "volume_id", "=", "t", ".", "get", "(", "'volume_id'", ")", ",", "snapshot_id", "=", "t", ".", "get", "(", "'snapshot_id'", ")", ",", "status", "=", "t", ".", "get", "(", "'status'", ")", ",", "attach_time", "=", "t", ".", "get", "(", "'attach_time'", ")", ",", "delete_on_termination", "=", "t", ".", "get", "(", "'delete_on_termination'", ",", "False", ")", ",", "size", "=", "t", ".", "get", "(", "'size'", ")", ",", "volume_type", "=", "t", ".", "get", "(", "'volume_type'", ")", ",", "iops", "=", "t", ".", "get", "(", "'iops'", ")", ",", "encrypted", "=", "t", ".", "get", "(", "'encrypted'", ")", ")", "bdm", "[", "d", "]", "=", "bdt", "return", "bdm" ]
convert a string .
train
true
36,660
def safe_subn(pattern, repl, target, *args, **kwargs): return re.subn(str(pattern), str(repl), target, *args, **kwargs)
[ "def", "safe_subn", "(", "pattern", ",", "repl", ",", "target", ",", "*", "args", ",", "**", "kwargs", ")", ":", "return", "re", ".", "subn", "(", "str", "(", "pattern", ")", ",", "str", "(", "repl", ")", ",", "target", ",", "*", "args", ",", "**", "kwargs", ")" ]
there are unicode conversion problems with re .
train
false
36,661
def _dscl(cmd, ctype='create'): if (__grains__['osrelease_info'] < (10, 8)): (source, noderoot) = ('.', '') else: (source, noderoot) = ('localhost', '/Local/Default') if noderoot: cmd[0] = (noderoot + cmd[0]) return __salt__['cmd.run_all']((['dscl', source, ('-' + ctype)] + cmd), output_loglevel=('quiet' if (ctype == 'passwd') else 'debug'), python_shell=False)
[ "def", "_dscl", "(", "cmd", ",", "ctype", "=", "'create'", ")", ":", "if", "(", "__grains__", "[", "'osrelease_info'", "]", "<", "(", "10", ",", "8", ")", ")", ":", "(", "source", ",", "noderoot", ")", "=", "(", "'.'", ",", "''", ")", "else", ":", "(", "source", ",", "noderoot", ")", "=", "(", "'localhost'", ",", "'/Local/Default'", ")", "if", "noderoot", ":", "cmd", "[", "0", "]", "=", "(", "noderoot", "+", "cmd", "[", "0", "]", ")", "return", "__salt__", "[", "'cmd.run_all'", "]", "(", "(", "[", "'dscl'", ",", "source", ",", "(", "'-'", "+", "ctype", ")", "]", "+", "cmd", ")", ",", "output_loglevel", "=", "(", "'quiet'", "if", "(", "ctype", "==", "'passwd'", ")", "else", "'debug'", ")", ",", "python_shell", "=", "False", ")" ]
run a dscl -create command .
train
true
36,662
def setup_temp_logger(log_level='error'): if is_temp_logging_configured(): logging.getLogger(__name__).warning('Temporary logging is already configured') return if (log_level is None): log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) handler = None for handler in logging.root.handlers: if (handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER)): continue if (not hasattr(handler, 'stream')): continue if (handler.stream is sys.stderr): break else: handler = LOGGING_TEMP_HANDLER handler.setLevel(level) formatter = logging.Formatter('[%(levelname)-8s] %(message)s', datefmt='%H:%M:%S') handler.setFormatter(formatter) logging.root.addHandler(handler) if (LOGGING_NULL_HANDLER is not None): LOGGING_NULL_HANDLER.sync_with_handlers([handler]) else: logging.getLogger(__name__).debug("LOGGING_NULL_HANDLER is already None, can't sync messages with it") __remove_null_logging_handler() global __TEMP_LOGGING_CONFIGURED __TEMP_LOGGING_CONFIGURED = True
[ "def", "setup_temp_logger", "(", "log_level", "=", "'error'", ")", ":", "if", "is_temp_logging_configured", "(", ")", ":", "logging", ".", "getLogger", "(", "__name__", ")", ".", "warning", "(", "'Temporary logging is already configured'", ")", "return", "if", "(", "log_level", "is", "None", ")", ":", "log_level", "=", "'warning'", "level", "=", "LOG_LEVELS", ".", "get", "(", "log_level", ".", "lower", "(", ")", ",", "logging", ".", "ERROR", ")", "handler", "=", "None", "for", "handler", "in", "logging", ".", "root", ".", "handlers", ":", "if", "(", "handler", "in", "(", "LOGGING_NULL_HANDLER", ",", "LOGGING_STORE_HANDLER", ")", ")", ":", "continue", "if", "(", "not", "hasattr", "(", "handler", ",", "'stream'", ")", ")", ":", "continue", "if", "(", "handler", ".", "stream", "is", "sys", ".", "stderr", ")", ":", "break", "else", ":", "handler", "=", "LOGGING_TEMP_HANDLER", "handler", ".", "setLevel", "(", "level", ")", "formatter", "=", "logging", ".", "Formatter", "(", "'[%(levelname)-8s] %(message)s'", ",", "datefmt", "=", "'%H:%M:%S'", ")", "handler", ".", "setFormatter", "(", "formatter", ")", "logging", ".", "root", ".", "addHandler", "(", "handler", ")", "if", "(", "LOGGING_NULL_HANDLER", "is", "not", "None", ")", ":", "LOGGING_NULL_HANDLER", ".", "sync_with_handlers", "(", "[", "handler", "]", ")", "else", ":", "logging", ".", "getLogger", "(", "__name__", ")", ".", "debug", "(", "\"LOGGING_NULL_HANDLER is already None, can't sync messages with it\"", ")", "__remove_null_logging_handler", "(", ")", "global", "__TEMP_LOGGING_CONFIGURED", "__TEMP_LOGGING_CONFIGURED", "=", "True" ]
setup the temporary console logger .
train
true
36,663
def lambda2nu(lambda_): return (_np.asanyarray(c) / lambda_)
[ "def", "lambda2nu", "(", "lambda_", ")", ":", "return", "(", "_np", ".", "asanyarray", "(", "c", ")", "/", "lambda_", ")" ]
convert wavelength to optical frequency parameters lambda_ : array_like wavelength(s) to be converted .
train
false
36,664
def package_minifest(request): if (not settings.MARKETPLACE_GUID): return HttpResponseNotFound() return mini_manifest(request, settings.MARKETPLACE_GUID)
[ "def", "package_minifest", "(", "request", ")", ":", "if", "(", "not", "settings", ".", "MARKETPLACE_GUID", ")", ":", "return", "HttpResponseNotFound", "(", ")", "return", "mini_manifest", "(", "request", ",", "settings", ".", "MARKETPLACE_GUID", ")" ]
serve mini manifest for yulelogs packaged .
train
false
36,665
def strFromDate(date): return time.strftime('%Y_%m_%d %H:%M', date)
[ "def", "strFromDate", "(", "date", ")", ":", "return", "time", ".", "strftime", "(", "'%Y_%m_%d %H:%M'", ",", "date", ")" ]
simply returns a string with a std format from a date object .
train
false
36,666
def _getLastMessage(acc): path = os.path.expanduser((('~/Library/Application Support/Skype/' + getUserName()) + '/main.db')) with contextlib.closing(sqlite3.connect(path).cursor()) as db: db.execute('SELECT timestamp,body_xml FROM Messages WHERE author=? ORDER BY timestamp DESC LIMIT 1', (acc,)) return db.fetchone()
[ "def", "_getLastMessage", "(", "acc", ")", ":", "path", "=", "os", ".", "path", ".", "expanduser", "(", "(", "(", "'~/Library/Application Support/Skype/'", "+", "getUserName", "(", ")", ")", "+", "'/main.db'", ")", ")", "with", "contextlib", ".", "closing", "(", "sqlite3", ".", "connect", "(", "path", ")", ".", "cursor", "(", ")", ")", "as", "db", ":", "db", ".", "execute", "(", "'SELECT timestamp,body_xml FROM Messages WHERE author=? ORDER BY timestamp DESC LIMIT 1'", ",", "(", "acc", ",", ")", ")", "return", "db", ".", "fetchone", "(", ")" ]
get the last message that a user sent to the currently logged in user .
train
false
36,667
def recursive_list_removal(base_list, purge_list): for item in purge_list: for _item in base_list: if (item == _item): base_list.pop(base_list.index(item))
[ "def", "recursive_list_removal", "(", "base_list", ",", "purge_list", ")", ":", "for", "item", "in", "purge_list", ":", "for", "_item", "in", "base_list", ":", "if", "(", "item", "==", "_item", ")", ":", "base_list", ".", "pop", "(", "base_list", ".", "index", "(", "item", ")", ")" ]
remove items from a list .
train
false
36,669
def adjust_axes(axes, remove_spines=('top', 'right'), grid=True): axes = ([axes] if (not isinstance(axes, (list, tuple, np.ndarray))) else axes) for ax in axes: if grid: ax.grid(zorder=0) for key in remove_spines: ax.spines[key].set_visible(False)
[ "def", "adjust_axes", "(", "axes", ",", "remove_spines", "=", "(", "'top'", ",", "'right'", ")", ",", "grid", "=", "True", ")", ":", "axes", "=", "(", "[", "axes", "]", "if", "(", "not", "isinstance", "(", "axes", ",", "(", "list", ",", "tuple", ",", "np", ".", "ndarray", ")", ")", ")", "else", "axes", ")", "for", "ax", "in", "axes", ":", "if", "grid", ":", "ax", ".", "grid", "(", "zorder", "=", "0", ")", "for", "key", "in", "remove_spines", ":", "ax", ".", "spines", "[", "key", "]", ".", "set_visible", "(", "False", ")" ]
adjust some properties of axes .
train
false
36,670
def recall_score(y_real, y_pred): (_, r, _) = precision_recall_fscore(y_real, y_pred) return np.average(r)
[ "def", "recall_score", "(", "y_real", ",", "y_pred", ")", ":", "(", "_", ",", "r", ",", "_", ")", "=", "precision_recall_fscore", "(", "y_real", ",", "y_pred", ")", "return", "np", ".", "average", "(", "r", ")" ]
compute the recall the recall is the ratio tp / where tp is the number of true positives and fn the number of false negatives .
train
false
36,671
def remove_airodump_files(prefix): global RUN_CONFIG remove_file((prefix + '-01.cap')) remove_file((prefix + '-01.csv')) remove_file((prefix + '-01.kismet.csv')) remove_file((prefix + '-01.kismet.netxml')) for filename in os.listdir(RUN_CONFIG.temp): if filename.lower().endswith('.xor'): remove_file((RUN_CONFIG.temp + filename)) for filename in os.listdir('.'): if (filename.startswith('replay_') and filename.endswith('.cap')): remove_file(filename) if filename.endswith('.xor'): remove_file(filename) "i = 2\n while os.path.exists(temp + 'wep-' + str(i) + '.cap'):\n os.remove(temp + 'wep-' + str(i) + '.cap')\n i += 1\n "
[ "def", "remove_airodump_files", "(", "prefix", ")", ":", "global", "RUN_CONFIG", "remove_file", "(", "(", "prefix", "+", "'-01.cap'", ")", ")", "remove_file", "(", "(", "prefix", "+", "'-01.csv'", ")", ")", "remove_file", "(", "(", "prefix", "+", "'-01.kismet.csv'", ")", ")", "remove_file", "(", "(", "prefix", "+", "'-01.kismet.netxml'", ")", ")", "for", "filename", "in", "os", ".", "listdir", "(", "RUN_CONFIG", ".", "temp", ")", ":", "if", "filename", ".", "lower", "(", ")", ".", "endswith", "(", "'.xor'", ")", ":", "remove_file", "(", "(", "RUN_CONFIG", ".", "temp", "+", "filename", ")", ")", "for", "filename", "in", "os", ".", "listdir", "(", "'.'", ")", ":", "if", "(", "filename", ".", "startswith", "(", "'replay_'", ")", "and", "filename", ".", "endswith", "(", "'.cap'", ")", ")", ":", "remove_file", "(", "filename", ")", "if", "filename", ".", "endswith", "(", "'.xor'", ")", ":", "remove_file", "(", "filename", ")", "\"i = 2\\n while os.path.exists(temp + 'wep-' + str(i) + '.cap'):\\n os.remove(temp + 'wep-' + str(i) + '.cap')\\n i += 1\\n \"" ]
removes airodump output files for whatever file prefix used by wpa_get_handshake() and attack_wep() .
train
false
36,672
def init(mpstate): return SerialModule(mpstate)
[ "def", "init", "(", "mpstate", ")", ":", "return", "SerialModule", "(", "mpstate", ")" ]
initialise module .
train
false
36,675
@pytest.fixture(scope='module', params=VC_BRANCH.keys()) def test_repo(request): vc = request.param temp_dir = tempfile.mkdtemp() os.chdir(temp_dir) try: sp.call([vc, 'init']) except FileNotFoundError: pytest.skip('cannot find {} executable'.format(vc)) if (vc == 'git'): with open('test-file', 'w'): pass sp.call(['git', 'add', 'test-file']) sp.call(['git', 'commit', '-m', 'test commit']) return {'name': vc, 'dir': temp_dir}
[ "@", "pytest", ".", "fixture", "(", "scope", "=", "'module'", ",", "params", "=", "VC_BRANCH", ".", "keys", "(", ")", ")", "def", "test_repo", "(", "request", ")", ":", "vc", "=", "request", ".", "param", "temp_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "os", ".", "chdir", "(", "temp_dir", ")", "try", ":", "sp", ".", "call", "(", "[", "vc", ",", "'init'", "]", ")", "except", "FileNotFoundError", ":", "pytest", ".", "skip", "(", "'cannot find {} executable'", ".", "format", "(", "vc", ")", ")", "if", "(", "vc", "==", "'git'", ")", ":", "with", "open", "(", "'test-file'", ",", "'w'", ")", ":", "pass", "sp", ".", "call", "(", "[", "'git'", ",", "'add'", ",", "'test-file'", "]", ")", "sp", ".", "call", "(", "[", "'git'", ",", "'commit'", ",", "'-m'", ",", "'test commit'", "]", ")", "return", "{", "'name'", ":", "vc", ",", "'dir'", ":", "temp_dir", "}" ]
return a dict with vc and a temporary dir that is a repository for testing .
train
false
36,676
@deprecated def setattr_default(obj, name, value): if (not hasattr(obj, name)): setattr(obj, name, value)
[ "@", "deprecated", "def", "setattr_default", "(", "obj", ",", "name", ",", "value", ")", ":", "if", "(", "not", "hasattr", "(", "obj", ",", "name", ")", ")", ":", "setattr", "(", "obj", ",", "name", ",", "value", ")" ]
set attribute value .
train
false
36,677
def get_language_from_request(request): global _accepted from django.conf import settings supported = dict(settings.LANGUAGES) if hasattr(request, 'session'): lang_code = request.session.get('django_language', None) if ((lang_code in supported) and (lang_code is not None) and check_for_language(lang_code)): return lang_code lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME) if (lang_code and (lang_code not in supported)): lang_code = lang_code.split('-')[0] if (lang_code and (lang_code in supported) and check_for_language(lang_code)): return lang_code accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '') for (accept_lang, unused) in parse_accept_lang_header(accept): if (accept_lang == '*'): break normalized = locale.locale_alias.get(to_locale(accept_lang, True)) if (not normalized): continue normalized = normalized.split('.')[0] if (normalized in _accepted): return _accepted[normalized] for (lang, dirname) in ((accept_lang, normalized), (accept_lang.split('-')[0], normalized.split('_')[0])): if (lang.lower() not in supported): continue for path in all_locale_paths(): if os.path.exists(os.path.join(path, dirname, 'LC_MESSAGES', 'django.mo')): _accepted[normalized] = lang return lang return settings.LANGUAGE_CODE
[ "def", "get_language_from_request", "(", "request", ")", ":", "global", "_accepted", "from", "django", ".", "conf", "import", "settings", "supported", "=", "dict", "(", "settings", ".", "LANGUAGES", ")", "if", "hasattr", "(", "request", ",", "'session'", ")", ":", "lang_code", "=", "request", ".", "session", ".", "get", "(", "'django_language'", ",", "None", ")", "if", "(", "(", "lang_code", "in", "supported", ")", "and", "(", "lang_code", "is", "not", "None", ")", "and", "check_for_language", "(", "lang_code", ")", ")", ":", "return", "lang_code", "lang_code", "=", "request", ".", "COOKIES", ".", "get", "(", "settings", ".", "LANGUAGE_COOKIE_NAME", ")", "if", "(", "lang_code", "and", "(", "lang_code", "not", "in", "supported", ")", ")", ":", "lang_code", "=", "lang_code", ".", "split", "(", "'-'", ")", "[", "0", "]", "if", "(", "lang_code", "and", "(", "lang_code", "in", "supported", ")", "and", "check_for_language", "(", "lang_code", ")", ")", ":", "return", "lang_code", "accept", "=", "request", ".", "META", ".", "get", "(", "'HTTP_ACCEPT_LANGUAGE'", ",", "''", ")", "for", "(", "accept_lang", ",", "unused", ")", "in", "parse_accept_lang_header", "(", "accept", ")", ":", "if", "(", "accept_lang", "==", "'*'", ")", ":", "break", "normalized", "=", "locale", ".", "locale_alias", ".", "get", "(", "to_locale", "(", "accept_lang", ",", "True", ")", ")", "if", "(", "not", "normalized", ")", ":", "continue", "normalized", "=", "normalized", ".", "split", "(", "'.'", ")", "[", "0", "]", "if", "(", "normalized", "in", "_accepted", ")", ":", "return", "_accepted", "[", "normalized", "]", "for", "(", "lang", ",", "dirname", ")", "in", "(", "(", "accept_lang", ",", "normalized", ")", ",", "(", "accept_lang", ".", "split", "(", "'-'", ")", "[", "0", "]", ",", "normalized", ".", "split", "(", "'_'", ")", "[", "0", "]", ")", ")", ":", "if", "(", "lang", ".", "lower", "(", ")", "not", "in", "supported", ")", ":", "continue", "for", "path", "in", "all_locale_paths", "(", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "path", ",", "dirname", ",", "'LC_MESSAGES'", ",", "'django.mo'", ")", ")", ":", "_accepted", "[", "normalized", "]", "=", "lang", "return", "lang", "return", "settings", ".", "LANGUAGE_CODE" ]
analyzes the request to find what language the user wants the system to show .
train
false
36,678
@with_session def log_once(message, logger=logging.getLogger(u'log_once'), once_level=logging.INFO, suppressed_level=f_logger.VERBOSE, session=None): from flexget.manager import manager if (not manager): log.warning(u'DB not initialized. log_once will not work properly.') logger.log(once_level, message) return digest = hashlib.md5() digest.update(message.encode(u'latin1', u'replace')) md5sum = digest.hexdigest() if session.query(LogMessage).filter_by(md5sum=md5sum).first(): logger.log(suppressed_level, message) return False row = LogMessage(md5sum) session.add(row) logger.log(once_level, message) return True
[ "@", "with_session", "def", "log_once", "(", "message", ",", "logger", "=", "logging", ".", "getLogger", "(", "u'log_once'", ")", ",", "once_level", "=", "logging", ".", "INFO", ",", "suppressed_level", "=", "f_logger", ".", "VERBOSE", ",", "session", "=", "None", ")", ":", "from", "flexget", ".", "manager", "import", "manager", "if", "(", "not", "manager", ")", ":", "log", ".", "warning", "(", "u'DB not initialized. log_once will not work properly.'", ")", "logger", ".", "log", "(", "once_level", ",", "message", ")", "return", "digest", "=", "hashlib", ".", "md5", "(", ")", "digest", ".", "update", "(", "message", ".", "encode", "(", "u'latin1'", ",", "u'replace'", ")", ")", "md5sum", "=", "digest", ".", "hexdigest", "(", ")", "if", "session", ".", "query", "(", "LogMessage", ")", ".", "filter_by", "(", "md5sum", "=", "md5sum", ")", ".", "first", "(", ")", ":", "logger", ".", "log", "(", "suppressed_level", ",", "message", ")", "return", "False", "row", "=", "LogMessage", "(", "md5sum", ")", "session", ".", "add", "(", "row", ")", "logger", ".", "log", "(", "once_level", ",", "message", ")", "return", "True" ]
log message only once using given logger .
train
false
36,680
def apply_special_queries(query, specials): for i in specials: query = FILTERS_LIST[i](specials[i], query) return query
[ "def", "apply_special_queries", "(", "query", ",", "specials", ")", ":", "for", "i", "in", "specials", ":", "query", "=", "FILTERS_LIST", "[", "i", "]", "(", "specials", "[", "i", "]", ",", "query", ")", "return", "query" ]
apply all special queries on the current existing :query .
train
false
36,683
def prob_mv_grid(bins, cdf, axis=(-1)): if (not isinstance(bins, np.ndarray)): bins = lmap(np.asarray, bins) n_dim = len(bins) bins_ = [] if all((lmap(np.ndim, bins) == np.ones(n_dim))): for d in range(n_dim): sl = ([None] * n_dim) sl[d] = slice(None) bins_.append(bins[d][sl]) else: n_dim = bins.shape[0] bins_ = bins print(len(bins)) cdf_values = cdf(bins_) probs = cdf_values.copy() for d in range(n_dim): probs = np.diff(probs, axis=d) return probs
[ "def", "prob_mv_grid", "(", "bins", ",", "cdf", ",", "axis", "=", "(", "-", "1", ")", ")", ":", "if", "(", "not", "isinstance", "(", "bins", ",", "np", ".", "ndarray", ")", ")", ":", "bins", "=", "lmap", "(", "np", ".", "asarray", ",", "bins", ")", "n_dim", "=", "len", "(", "bins", ")", "bins_", "=", "[", "]", "if", "all", "(", "(", "lmap", "(", "np", ".", "ndim", ",", "bins", ")", "==", "np", ".", "ones", "(", "n_dim", ")", ")", ")", ":", "for", "d", "in", "range", "(", "n_dim", ")", ":", "sl", "=", "(", "[", "None", "]", "*", "n_dim", ")", "sl", "[", "d", "]", "=", "slice", "(", "None", ")", "bins_", ".", "append", "(", "bins", "[", "d", "]", "[", "sl", "]", ")", "else", ":", "n_dim", "=", "bins", ".", "shape", "[", "0", "]", "bins_", "=", "bins", "print", "(", "len", "(", "bins", ")", ")", "cdf_values", "=", "cdf", "(", "bins_", ")", "probs", "=", "cdf_values", ".", "copy", "(", ")", "for", "d", "in", "range", "(", "n_dim", ")", ":", "probs", "=", "np", ".", "diff", "(", "probs", ",", "axis", "=", "d", ")", "return", "probs" ]
helper function for probability of a rectangle grid in a multivariate distribution how does this generalize to more than 2 variates ? bins : tuple tuple of bin edges .
train
false
36,684
def server_pxe(): if __execute_cmd('config -g cfgServerInfo -o cfgServerFirstBootDevice PXE'): if __execute_cmd('config -g cfgServerInfo -o cfgServerBootOnce 1'): return server_reboot else: log.warning('failed to set boot order') return False log.warning('failed to to configure PXE boot') return False
[ "def", "server_pxe", "(", ")", ":", "if", "__execute_cmd", "(", "'config -g cfgServerInfo -o cfgServerFirstBootDevice PXE'", ")", ":", "if", "__execute_cmd", "(", "'config -g cfgServerInfo -o cfgServerBootOnce 1'", ")", ":", "return", "server_reboot", "else", ":", "log", ".", "warning", "(", "'failed to set boot order'", ")", "return", "False", "log", ".", "warning", "(", "'failed to to configure PXE boot'", ")", "return", "False" ]
configure server to pxe perform a one off pxe boot cli example: .
train
true
36,685
def make_pass_decorator(object_type, ensure=False): def decorator(f): def new_func(*args, **kwargs): ctx = get_current_context() if ensure: obj = ctx.ensure_object(object_type) else: obj = ctx.find_object(object_type) if (obj is None): raise RuntimeError(('Managed to invoke callback without a context object of type %r existing' % object_type.__name__)) return ctx.invoke(f, obj, *args[1:], **kwargs) return update_wrapper(new_func, f) return decorator
[ "def", "make_pass_decorator", "(", "object_type", ",", "ensure", "=", "False", ")", ":", "def", "decorator", "(", "f", ")", ":", "def", "new_func", "(", "*", "args", ",", "**", "kwargs", ")", ":", "ctx", "=", "get_current_context", "(", ")", "if", "ensure", ":", "obj", "=", "ctx", ".", "ensure_object", "(", "object_type", ")", "else", ":", "obj", "=", "ctx", ".", "find_object", "(", "object_type", ")", "if", "(", "obj", "is", "None", ")", ":", "raise", "RuntimeError", "(", "(", "'Managed to invoke callback without a context object of type %r existing'", "%", "object_type", ".", "__name__", ")", ")", "return", "ctx", ".", "invoke", "(", "f", ",", "obj", ",", "*", "args", "[", "1", ":", "]", ",", "**", "kwargs", ")", "return", "update_wrapper", "(", "new_func", ",", "f", ")", "return", "decorator" ]
given an object type this creates a decorator that will work similar to :func:pass_obj but instead of passing the object of the current context .
train
true
36,686
def _potential_before(i, input_string): return (((i - 2) >= 0) and (input_string[i] == input_string[(i - 2)]) and (input_string[(i - 1)] not in seps))
[ "def", "_potential_before", "(", "i", ",", "input_string", ")", ":", "return", "(", "(", "(", "i", "-", "2", ")", ">=", "0", ")", "and", "(", "input_string", "[", "i", "]", "==", "input_string", "[", "(", "i", "-", "2", ")", "]", ")", "and", "(", "input_string", "[", "(", "i", "-", "1", ")", "]", "not", "in", "seps", ")", ")" ]
check if the character at position i can be a potential single char separator considering whats before it .
train
false
36,687
def getFromObjectOrXMLElement(xmlElement): xmlElementMatrix = None if (xmlElement.object != None): xmlElementMatrix = xmlElement.object.matrix4X4 else: xmlElementMatrix = Matrix() return xmlElementMatrix.getFromXMLElement('matrix.', xmlElement)
[ "def", "getFromObjectOrXMLElement", "(", "xmlElement", ")", ":", "xmlElementMatrix", "=", "None", "if", "(", "xmlElement", ".", "object", "!=", "None", ")", ":", "xmlElementMatrix", "=", "xmlElement", ".", "object", ".", "matrix4X4", "else", ":", "xmlElementMatrix", "=", "Matrix", "(", ")", "return", "xmlElementMatrix", ".", "getFromXMLElement", "(", "'matrix.'", ",", "xmlElement", ")" ]
get matrix starting from the object if it exists .
train
false
36,689
@testing.requires_testing_data def test_acqparser_averaging(): raw = read_raw_fif(fname_raw_elekta, preload=True) acqp = AcqParserFIF(raw.info) for cat in acqp.categories: cond = acqp.get_condition(raw, cat) eps = Epochs(raw, baseline=((-0.05), 0), **cond) ev = eps.average() ev_ref = read_evokeds(fname_ave_elekta, cat['comment'], baseline=((-0.05), 0), proj=False) ev_mag = ev.copy() ev_mag.pick_channels(['MEG0111']) ev_grad = ev.copy() ev_grad.pick_channels(['MEG2643', 'MEG1622']) ev_ref_mag = ev_ref.copy() ev_ref_mag.pick_channels(['MEG0111']) ev_ref_grad = ev_ref.copy() ev_ref_grad.pick_channels(['MEG2643', 'MEG1622']) assert_allclose(ev_mag.data, ev_ref_mag.data, rtol=0, atol=1e-15) assert_allclose(ev_grad.data, ev_ref_grad.data, rtol=0, atol=1e-13)
[ "@", "testing", ".", "requires_testing_data", "def", "test_acqparser_averaging", "(", ")", ":", "raw", "=", "read_raw_fif", "(", "fname_raw_elekta", ",", "preload", "=", "True", ")", "acqp", "=", "AcqParserFIF", "(", "raw", ".", "info", ")", "for", "cat", "in", "acqp", ".", "categories", ":", "cond", "=", "acqp", ".", "get_condition", "(", "raw", ",", "cat", ")", "eps", "=", "Epochs", "(", "raw", ",", "baseline", "=", "(", "(", "-", "0.05", ")", ",", "0", ")", ",", "**", "cond", ")", "ev", "=", "eps", ".", "average", "(", ")", "ev_ref", "=", "read_evokeds", "(", "fname_ave_elekta", ",", "cat", "[", "'comment'", "]", ",", "baseline", "=", "(", "(", "-", "0.05", ")", ",", "0", ")", ",", "proj", "=", "False", ")", "ev_mag", "=", "ev", ".", "copy", "(", ")", "ev_mag", ".", "pick_channels", "(", "[", "'MEG0111'", "]", ")", "ev_grad", "=", "ev", ".", "copy", "(", ")", "ev_grad", ".", "pick_channels", "(", "[", "'MEG2643'", ",", "'MEG1622'", "]", ")", "ev_ref_mag", "=", "ev_ref", ".", "copy", "(", ")", "ev_ref_mag", ".", "pick_channels", "(", "[", "'MEG0111'", "]", ")", "ev_ref_grad", "=", "ev_ref", ".", "copy", "(", ")", "ev_ref_grad", ".", "pick_channels", "(", "[", "'MEG2643'", ",", "'MEG1622'", "]", ")", "assert_allclose", "(", "ev_mag", ".", "data", ",", "ev_ref_mag", ".", "data", ",", "rtol", "=", "0", ",", "atol", "=", "1e-15", ")", "assert_allclose", "(", "ev_grad", ".", "data", ",", "ev_ref_grad", ".", "data", ",", "rtol", "=", "0", ",", "atol", "=", "1e-13", ")" ]
test averaging with acqparserfif vs .
train
false
36,692
@profiler.trace def ikepolicy_create(request, **kwargs): body = {'ikepolicy': {'name': kwargs['name'], 'description': kwargs['description'], 'auth_algorithm': kwargs['auth_algorithm'], 'encryption_algorithm': kwargs['encryption_algorithm'], 'ike_version': kwargs['ike_version'], 'lifetime': kwargs['lifetime'], 'pfs': kwargs['pfs'], 'phase1_negotiation_mode': kwargs['phase1_negotiation_mode']}} ikepolicy = neutronclient(request).create_ikepolicy(body).get('ikepolicy') return IKEPolicy(ikepolicy)
[ "@", "profiler", ".", "trace", "def", "ikepolicy_create", "(", "request", ",", "**", "kwargs", ")", ":", "body", "=", "{", "'ikepolicy'", ":", "{", "'name'", ":", "kwargs", "[", "'name'", "]", ",", "'description'", ":", "kwargs", "[", "'description'", "]", ",", "'auth_algorithm'", ":", "kwargs", "[", "'auth_algorithm'", "]", ",", "'encryption_algorithm'", ":", "kwargs", "[", "'encryption_algorithm'", "]", ",", "'ike_version'", ":", "kwargs", "[", "'ike_version'", "]", ",", "'lifetime'", ":", "kwargs", "[", "'lifetime'", "]", ",", "'pfs'", ":", "kwargs", "[", "'pfs'", "]", ",", "'phase1_negotiation_mode'", ":", "kwargs", "[", "'phase1_negotiation_mode'", "]", "}", "}", "ikepolicy", "=", "neutronclient", "(", "request", ")", ".", "create_ikepolicy", "(", "body", ")", ".", "get", "(", "'ikepolicy'", ")", "return", "IKEPolicy", "(", "ikepolicy", ")" ]
create ikepolicy .
train
false
36,693
def test_column_params_should_be_preserved_under_inheritance(): class MyTableA(MyTable, ): u'\n having an empty `class Meta` should not undo the explicit definition\n of column item1 in MyTable.\n ' class Meta(MyTable.Meta, ): pass class MyTableB(MyTable, ): u'\n having a non-empty `class Meta` should not undo the explicit definition\n of column item1 in MyTable.\n ' class Meta(MyTable.Meta, ): per_page = 22 table = MyTable(MyModel.objects.all()) tableA = MyTableA(MyModel.objects.all()) tableB = MyTableB(MyModel.objects.all()) assert (table.columns[u'item1'].verbose_name == u'Nice column name') assert (tableA.columns[u'item1'].verbose_name == u'Nice column name') assert (tableB.columns[u'item1'].verbose_name == u'Nice column name')
[ "def", "test_column_params_should_be_preserved_under_inheritance", "(", ")", ":", "class", "MyTableA", "(", "MyTable", ",", ")", ":", "class", "Meta", "(", "MyTable", ".", "Meta", ",", ")", ":", "pass", "class", "MyTableB", "(", "MyTable", ",", ")", ":", "class", "Meta", "(", "MyTable", ".", "Meta", ",", ")", ":", "per_page", "=", "22", "table", "=", "MyTable", "(", "MyModel", ".", "objects", ".", "all", "(", ")", ")", "tableA", "=", "MyTableA", "(", "MyModel", ".", "objects", ".", "all", "(", ")", ")", "tableB", "=", "MyTableB", "(", "MyModel", ".", "objects", ".", "all", "(", ")", ")", "assert", "(", "table", ".", "columns", "[", "u'item1'", "]", ".", "verbose_name", "==", "u'Nice column name'", ")", "assert", "(", "tableA", ".", "columns", "[", "u'item1'", "]", ".", "verbose_name", "==", "u'Nice column name'", ")", "assert", "(", "tableB", ".", "columns", "[", "u'item1'", "]", ".", "verbose_name", "==", "u'Nice column name'", ")" ]
github issue #337 columns explicitly defined on mytable get overridden by columns implicitly defined on its child .
train
false
36,695
def copyfile(src, dst): if _samefile(src, dst): raise Error, ('`%s` and `%s` are the same file' % (src, dst)) fsrc = None fdst = None try: fsrc = open(src, 'rb') fdst = open(dst, 'wb') copyfileobj(fsrc, fdst) finally: if fdst: fdst.close() if fsrc: fsrc.close()
[ "def", "copyfile", "(", "src", ",", "dst", ")", ":", "if", "_samefile", "(", "src", ",", "dst", ")", ":", "raise", "Error", ",", "(", "'`%s` and `%s` are the same file'", "%", "(", "src", ",", "dst", ")", ")", "fsrc", "=", "None", "fdst", "=", "None", "try", ":", "fsrc", "=", "open", "(", "src", ",", "'rb'", ")", "fdst", "=", "open", "(", "dst", ",", "'wb'", ")", "copyfileobj", "(", "fsrc", ",", "fdst", ")", "finally", ":", "if", "fdst", ":", "fdst", ".", "close", "(", ")", "if", "fsrc", ":", "fsrc", ".", "close", "(", ")" ]
copy a file and its modification times .
train
false
36,696
def update_resource(zone, resource_type, resource_selector, **kwargs): return _resource('update', zone, resource_type, resource_selector, **kwargs)
[ "def", "update_resource", "(", "zone", ",", "resource_type", ",", "resource_selector", ",", "**", "kwargs", ")", ":", "return", "_resource", "(", "'update'", ",", "zone", ",", "resource_type", ",", "resource_selector", ",", "**", "kwargs", ")" ]
add a resource zone : string name of zone resource_type : string type of resource resource_selector : string unique resource identifier **kwargs : string|int| .
train
true
36,698
def customize_compiler(compiler): if (compiler.compiler_type == 'unix'): if (sys.platform == 'darwin'): global _config_vars if (not get_config_var('CUSTOMIZED_OSX_COMPILER')): import _osx_support _osx_support.customize_compiler(_config_vars) _config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True' (cc, cxx, opt, cflags, ccshared, ldshared, so_ext, ar, ar_flags) = get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS', 'CCSHARED', 'LDSHARED', 'SO', 'AR', 'ARFLAGS') if ('CC' in os.environ): newcc = os.environ['CC'] if ((sys.platform == 'darwin') and ('LDSHARED' not in os.environ) and ldshared.startswith(cc)): ldshared = (newcc + ldshared[len(cc):]) cc = newcc if ('CXX' in os.environ): cxx = os.environ['CXX'] if ('LDSHARED' in os.environ): ldshared = os.environ['LDSHARED'] if ('CPP' in os.environ): cpp = os.environ['CPP'] else: cpp = (cc + ' -E') if ('LDFLAGS' in os.environ): ldshared = ((ldshared + ' ') + os.environ['LDFLAGS']) if ('CFLAGS' in os.environ): cflags = ((opt + ' ') + os.environ['CFLAGS']) ldshared = ((ldshared + ' ') + os.environ['CFLAGS']) if ('CPPFLAGS' in os.environ): cpp = ((cpp + ' ') + os.environ['CPPFLAGS']) cflags = ((cflags + ' ') + os.environ['CPPFLAGS']) ldshared = ((ldshared + ' ') + os.environ['CPPFLAGS']) if ('AR' in os.environ): ar = os.environ['AR'] if ('ARFLAGS' in os.environ): archiver = ((ar + ' ') + os.environ['ARFLAGS']) else: archiver = ((ar + ' ') + ar_flags) cc_cmd = ((cc + ' ') + cflags) compiler.set_executables(preprocessor=cpp, compiler=cc_cmd, compiler_so=((cc_cmd + ' ') + ccshared), compiler_cxx=cxx, linker_so=ldshared, linker_exe=cc, archiver=archiver) compiler.shared_lib_extension = so_ext
[ "def", "customize_compiler", "(", "compiler", ")", ":", "if", "(", "compiler", ".", "compiler_type", "==", "'unix'", ")", ":", "if", "(", "sys", ".", "platform", "==", "'darwin'", ")", ":", "global", "_config_vars", "if", "(", "not", "get_config_var", "(", "'CUSTOMIZED_OSX_COMPILER'", ")", ")", ":", "import", "_osx_support", "_osx_support", ".", "customize_compiler", "(", "_config_vars", ")", "_config_vars", "[", "'CUSTOMIZED_OSX_COMPILER'", "]", "=", "'True'", "(", "cc", ",", "cxx", ",", "opt", ",", "cflags", ",", "ccshared", ",", "ldshared", ",", "so_ext", ",", "ar", ",", "ar_flags", ")", "=", "get_config_vars", "(", "'CC'", ",", "'CXX'", ",", "'OPT'", ",", "'CFLAGS'", ",", "'CCSHARED'", ",", "'LDSHARED'", ",", "'SO'", ",", "'AR'", ",", "'ARFLAGS'", ")", "if", "(", "'CC'", "in", "os", ".", "environ", ")", ":", "newcc", "=", "os", ".", "environ", "[", "'CC'", "]", "if", "(", "(", "sys", ".", "platform", "==", "'darwin'", ")", "and", "(", "'LDSHARED'", "not", "in", "os", ".", "environ", ")", "and", "ldshared", ".", "startswith", "(", "cc", ")", ")", ":", "ldshared", "=", "(", "newcc", "+", "ldshared", "[", "len", "(", "cc", ")", ":", "]", ")", "cc", "=", "newcc", "if", "(", "'CXX'", "in", "os", ".", "environ", ")", ":", "cxx", "=", "os", ".", "environ", "[", "'CXX'", "]", "if", "(", "'LDSHARED'", "in", "os", ".", "environ", ")", ":", "ldshared", "=", "os", ".", "environ", "[", "'LDSHARED'", "]", "if", "(", "'CPP'", "in", "os", ".", "environ", ")", ":", "cpp", "=", "os", ".", "environ", "[", "'CPP'", "]", "else", ":", "cpp", "=", "(", "cc", "+", "' -E'", ")", "if", "(", "'LDFLAGS'", "in", "os", ".", "environ", ")", ":", "ldshared", "=", "(", "(", "ldshared", "+", "' '", ")", "+", "os", ".", "environ", "[", "'LDFLAGS'", "]", ")", "if", "(", "'CFLAGS'", "in", "os", ".", "environ", ")", ":", "cflags", "=", "(", "(", "opt", "+", "' '", ")", "+", "os", ".", "environ", "[", "'CFLAGS'", "]", ")", "ldshared", "=", "(", "(", "ldshared", "+", "' '", ")", "+", "os", ".", "environ", "[", "'CFLAGS'", "]", ")", "if", "(", "'CPPFLAGS'", "in", "os", ".", "environ", ")", ":", "cpp", "=", "(", "(", "cpp", "+", "' '", ")", "+", "os", ".", "environ", "[", "'CPPFLAGS'", "]", ")", "cflags", "=", "(", "(", "cflags", "+", "' '", ")", "+", "os", ".", "environ", "[", "'CPPFLAGS'", "]", ")", "ldshared", "=", "(", "(", "ldshared", "+", "' '", ")", "+", "os", ".", "environ", "[", "'CPPFLAGS'", "]", ")", "if", "(", "'AR'", "in", "os", ".", "environ", ")", ":", "ar", "=", "os", ".", "environ", "[", "'AR'", "]", "if", "(", "'ARFLAGS'", "in", "os", ".", "environ", ")", ":", "archiver", "=", "(", "(", "ar", "+", "' '", ")", "+", "os", ".", "environ", "[", "'ARFLAGS'", "]", ")", "else", ":", "archiver", "=", "(", "(", "ar", "+", "' '", ")", "+", "ar_flags", ")", "cc_cmd", "=", "(", "(", "cc", "+", "' '", ")", "+", "cflags", ")", "compiler", ".", "set_executables", "(", "preprocessor", "=", "cpp", ",", "compiler", "=", "cc_cmd", ",", "compiler_so", "=", "(", "(", "cc_cmd", "+", "' '", ")", "+", "ccshared", ")", ",", "compiler_cxx", "=", "cxx", ",", "linker_so", "=", "ldshared", ",", "linker_exe", "=", "cc", ",", "archiver", "=", "archiver", ")", "compiler", ".", "shared_lib_extension", "=", "so_ext" ]
customize compiler path and configuration variables .
train
false
36,700
def get_encoding(headers, content): encoding = None content_type = headers.get('content-type') if content_type: (_, params) = cgi.parse_header(content_type) if ('charset' in params): encoding = params['charset'].strip('\'"') if (not encoding): content = (utils.pretty_unicode(content[:1000]) if six.PY3 else content) charset_re = re.compile('<meta.*?charset=["\\\']*(.+?)["\\\'>]', flags=re.I) pragma_re = re.compile('<meta.*?content=["\\\']*;?charset=(.+?)["\\\'>]', flags=re.I) xml_re = re.compile('^<\\?xml.*?encoding=["\\\']*(.+?)["\\\'>]') encoding = ((charset_re.findall(content) + pragma_re.findall(content)) + xml_re.findall(content)) encoding = ((encoding and encoding[0]) or None) return encoding
[ "def", "get_encoding", "(", "headers", ",", "content", ")", ":", "encoding", "=", "None", "content_type", "=", "headers", ".", "get", "(", "'content-type'", ")", "if", "content_type", ":", "(", "_", ",", "params", ")", "=", "cgi", ".", "parse_header", "(", "content_type", ")", "if", "(", "'charset'", "in", "params", ")", ":", "encoding", "=", "params", "[", "'charset'", "]", ".", "strip", "(", "'\\'\"'", ")", "if", "(", "not", "encoding", ")", ":", "content", "=", "(", "utils", ".", "pretty_unicode", "(", "content", "[", ":", "1000", "]", ")", "if", "six", ".", "PY3", "else", "content", ")", "charset_re", "=", "re", ".", "compile", "(", "'<meta.*?charset=[\"\\\\\\']*(.+?)[\"\\\\\\'>]'", ",", "flags", "=", "re", ".", "I", ")", "pragma_re", "=", "re", ".", "compile", "(", "'<meta.*?content=[\"\\\\\\']*;?charset=(.+?)[\"\\\\\\'>]'", ",", "flags", "=", "re", ".", "I", ")", "xml_re", "=", "re", ".", "compile", "(", "'^<\\\\?xml.*?encoding=[\"\\\\\\']*(.+?)[\"\\\\\\'>]'", ")", "encoding", "=", "(", "(", "charset_re", ".", "findall", "(", "content", ")", "+", "pragma_re", ".", "findall", "(", "content", ")", ")", "+", "xml_re", ".", "findall", "(", "content", ")", ")", "encoding", "=", "(", "(", "encoding", "and", "encoding", "[", "0", "]", ")", "or", "None", ")", "return", "encoding" ]
returns the unicode encoding type .
train
true
36,701
def _check_input_size(n_components, n_features): if (n_components <= 0): raise ValueError(('n_components must be strictly positive, got %d' % n_components)) if (n_features <= 0): raise ValueError(('n_features must be strictly positive, got %d' % n_components))
[ "def", "_check_input_size", "(", "n_components", ",", "n_features", ")", ":", "if", "(", "n_components", "<=", "0", ")", ":", "raise", "ValueError", "(", "(", "'n_components must be strictly positive, got %d'", "%", "n_components", ")", ")", "if", "(", "n_features", "<=", "0", ")", ":", "raise", "ValueError", "(", "(", "'n_features must be strictly positive, got %d'", "%", "n_components", ")", ")" ]
factorize argument checking for random matrix generation .
train
false
36,702
@request_cached def get_course_cohort_settings(course_key): try: course_cohort_settings = CourseCohortsSettings.objects.get(course_id=course_key) except CourseCohortsSettings.DoesNotExist: course = courses.get_course_by_id(course_key) course_cohort_settings = migrate_cohort_settings(course) return course_cohort_settings
[ "@", "request_cached", "def", "get_course_cohort_settings", "(", "course_key", ")", ":", "try", ":", "course_cohort_settings", "=", "CourseCohortsSettings", ".", "objects", ".", "get", "(", "course_id", "=", "course_key", ")", "except", "CourseCohortsSettings", ".", "DoesNotExist", ":", "course", "=", "courses", ".", "get_course_by_id", "(", "course_key", ")", "course_cohort_settings", "=", "migrate_cohort_settings", "(", "course", ")", "return", "course_cohort_settings" ]
return cohort settings for a course .
train
false
36,703
def task_hashing(): import hashlib with open(__file__, 'rb') as f: arg = (f.read(5000) * 30) def compute(s): hashlib.sha1(s).digest() return (compute, (arg,))
[ "def", "task_hashing", "(", ")", ":", "import", "hashlib", "with", "open", "(", "__file__", ",", "'rb'", ")", "as", "f", ":", "arg", "=", "(", "f", ".", "read", "(", "5000", ")", "*", "30", ")", "def", "compute", "(", "s", ")", ":", "hashlib", ".", "sha1", "(", "s", ")", ".", "digest", "(", ")", "return", "(", "compute", ",", "(", "arg", ",", ")", ")" ]
sha1 hashing (c) .
train
false
36,705
def get_backend_configuration(backend_name): config_stanzas = CONF.list_all_sections() if (backend_name not in config_stanzas): msg = _('Could not find backend stanza %(backend_name)s in configuration. Available stanzas are %(stanzas)s') params = {'stanzas': config_stanzas, 'backend_name': backend_name} raise exception.ConfigNotFound(message=(msg % params)) config = configuration.Configuration(driver.volume_opts, config_group=backend_name) config.append_config_values(na_opts.netapp_proxy_opts) config.append_config_values(na_opts.netapp_connection_opts) config.append_config_values(na_opts.netapp_transport_opts) config.append_config_values(na_opts.netapp_basicauth_opts) config.append_config_values(na_opts.netapp_provisioning_opts) config.append_config_values(na_opts.netapp_cluster_opts) config.append_config_values(na_opts.netapp_san_opts) config.append_config_values(na_opts.netapp_replication_opts) return config
[ "def", "get_backend_configuration", "(", "backend_name", ")", ":", "config_stanzas", "=", "CONF", ".", "list_all_sections", "(", ")", "if", "(", "backend_name", "not", "in", "config_stanzas", ")", ":", "msg", "=", "_", "(", "'Could not find backend stanza %(backend_name)s in configuration. Available stanzas are %(stanzas)s'", ")", "params", "=", "{", "'stanzas'", ":", "config_stanzas", ",", "'backend_name'", ":", "backend_name", "}", "raise", "exception", ".", "ConfigNotFound", "(", "message", "=", "(", "msg", "%", "params", ")", ")", "config", "=", "configuration", ".", "Configuration", "(", "driver", ".", "volume_opts", ",", "config_group", "=", "backend_name", ")", "config", ".", "append_config_values", "(", "na_opts", ".", "netapp_proxy_opts", ")", "config", ".", "append_config_values", "(", "na_opts", ".", "netapp_connection_opts", ")", "config", ".", "append_config_values", "(", "na_opts", ".", "netapp_transport_opts", ")", "config", ".", "append_config_values", "(", "na_opts", ".", "netapp_basicauth_opts", ")", "config", ".", "append_config_values", "(", "na_opts", ".", "netapp_provisioning_opts", ")", "config", ".", "append_config_values", "(", "na_opts", ".", "netapp_cluster_opts", ")", "config", ".", "append_config_values", "(", "na_opts", ".", "netapp_san_opts", ")", "config", ".", "append_config_values", "(", "na_opts", ".", "netapp_replication_opts", ")", "return", "config" ]
get a cdot configuration object for a specific backend .
train
false
36,706
def vm_action(name, kwargs=None, call=None): if (call != 'action'): raise SaltCloudSystemExit('The vm_action function must be called with -a or --action.') if (kwargs is None): kwargs = {} action = kwargs.get('action', None) if (action is None): raise SaltCloudSystemExit("The vm_action function must have an 'action' provided.") (server, user, password) = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = {'action': ('vm.action.' + str(action)), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2]} return data
[ "def", "vm_action", "(", "name", ",", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "(", "call", "!=", "'action'", ")", ":", "raise", "SaltCloudSystemExit", "(", "'The vm_action function must be called with -a or --action.'", ")", "if", "(", "kwargs", "is", "None", ")", ":", "kwargs", "=", "{", "}", "action", "=", "kwargs", ".", "get", "(", "'action'", ",", "None", ")", "if", "(", "action", "is", "None", ")", ":", "raise", "SaltCloudSystemExit", "(", "\"The vm_action function must have an 'action' provided.\"", ")", "(", "server", ",", "user", ",", "password", ")", "=", "_get_xml_rpc", "(", ")", "auth", "=", "':'", ".", "join", "(", "[", "user", ",", "password", "]", ")", "vm_id", "=", "int", "(", "get_vm_id", "(", "kwargs", "=", "{", "'name'", ":", "name", "}", ")", ")", "response", "=", "server", ".", "one", ".", "vm", ".", "action", "(", "auth", ",", "action", ",", "vm_id", ")", "data", "=", "{", "'action'", ":", "(", "'vm.action.'", "+", "str", "(", "action", ")", ")", ",", "'actioned'", ":", "response", "[", "0", "]", ",", "'vm_id'", ":", "response", "[", "1", "]", ",", "'error_code'", ":", "response", "[", "2", "]", "}", "return", "data" ]
submits an action to be performed on a given virtual machine .
train
true
36,707
def get_hashval(inputdict, skip=None): dict_withhash = {} dict_nofilename = OrderedDict() keys = {} for key in inputdict: if ((skip is not None) and (key in skip)): continue keys[key.uri] = key for key in sorted(keys): val = inputdict[keys[key]] outname = key try: if isinstance(val, pm.URIRef): val = val.decode() except AttributeError: pass if isinstance(val, pm.QualifiedName): val = val.uri if isinstance(val, pm.Literal): val = val.value dict_nofilename[outname] = _get_sorteddict(val) dict_withhash[outname] = _get_sorteddict(val, True) sorted_dict = str(sorted(dict_nofilename.items())) return (dict_withhash, md5(sorted_dict.encode()).hexdigest())
[ "def", "get_hashval", "(", "inputdict", ",", "skip", "=", "None", ")", ":", "dict_withhash", "=", "{", "}", "dict_nofilename", "=", "OrderedDict", "(", ")", "keys", "=", "{", "}", "for", "key", "in", "inputdict", ":", "if", "(", "(", "skip", "is", "not", "None", ")", "and", "(", "key", "in", "skip", ")", ")", ":", "continue", "keys", "[", "key", ".", "uri", "]", "=", "key", "for", "key", "in", "sorted", "(", "keys", ")", ":", "val", "=", "inputdict", "[", "keys", "[", "key", "]", "]", "outname", "=", "key", "try", ":", "if", "isinstance", "(", "val", ",", "pm", ".", "URIRef", ")", ":", "val", "=", "val", ".", "decode", "(", ")", "except", "AttributeError", ":", "pass", "if", "isinstance", "(", "val", ",", "pm", ".", "QualifiedName", ")", ":", "val", "=", "val", ".", "uri", "if", "isinstance", "(", "val", ",", "pm", ".", "Literal", ")", ":", "val", "=", "val", ".", "value", "dict_nofilename", "[", "outname", "]", "=", "_get_sorteddict", "(", "val", ")", "dict_withhash", "[", "outname", "]", "=", "_get_sorteddict", "(", "val", ",", "True", ")", "sorted_dict", "=", "str", "(", "sorted", "(", "dict_nofilename", ".", "items", "(", ")", ")", ")", "return", "(", "dict_withhash", ",", "md5", "(", "sorted_dict", ".", "encode", "(", ")", ")", ".", "hexdigest", "(", ")", ")" ]
return a dictionary of our items with hashes for each file .
train
false
36,708
def cs_output(func, argtypes): func.argtypes = argtypes func.restype = CS_PTR func.errcheck = check_cs_ptr return func
[ "def", "cs_output", "(", "func", ",", "argtypes", ")", ":", "func", ".", "argtypes", "=", "argtypes", "func", ".", "restype", "=", "CS_PTR", "func", ".", "errcheck", "=", "check_cs_ptr", "return", "func" ]
for routines that return a coordinate sequence .
train
false
36,709
def _merge_prefix(deque, size): if ((len(deque) == 1) and (len(deque[0]) <= size)): return prefix = [] remaining = size while (deque and (remaining > 0)): chunk = deque.popleft() if (len(chunk) > remaining): deque.appendleft(chunk[remaining:]) chunk = chunk[:remaining] prefix.append(chunk) remaining -= len(chunk) if prefix: deque.appendleft(type(prefix[0])().join(prefix)) if (not deque): deque.appendleft('')
[ "def", "_merge_prefix", "(", "deque", ",", "size", ")", ":", "if", "(", "(", "len", "(", "deque", ")", "==", "1", ")", "and", "(", "len", "(", "deque", "[", "0", "]", ")", "<=", "size", ")", ")", ":", "return", "prefix", "=", "[", "]", "remaining", "=", "size", "while", "(", "deque", "and", "(", "remaining", ">", "0", ")", ")", ":", "chunk", "=", "deque", ".", "popleft", "(", ")", "if", "(", "len", "(", "chunk", ")", ">", "remaining", ")", ":", "deque", ".", "appendleft", "(", "chunk", "[", "remaining", ":", "]", ")", "chunk", "=", "chunk", "[", ":", "remaining", "]", "prefix", ".", "append", "(", "chunk", ")", "remaining", "-=", "len", "(", "chunk", ")", "if", "prefix", ":", "deque", ".", "appendleft", "(", "type", "(", "prefix", "[", "0", "]", ")", "(", ")", ".", "join", "(", "prefix", ")", ")", "if", "(", "not", "deque", ")", ":", "deque", ".", "appendleft", "(", "''", ")" ]
replace the first entries in a deque of strings with a single string of up to size bytes .
train
false
36,710
def verify_socket(host, port): def can_connect(): with closing(socket()) as s: s.settimeout(SOCKET_TIMEOUT_FOR_POLLING) conn = s.connect_ex((host, port)) Message.new(message_type='acceptance:verify_socket', host=host, port=port, result=conn).write() return (conn == 0) dl = loop_until(reactor, can_connect) return dl
[ "def", "verify_socket", "(", "host", ",", "port", ")", ":", "def", "can_connect", "(", ")", ":", "with", "closing", "(", "socket", "(", ")", ")", "as", "s", ":", "s", ".", "settimeout", "(", "SOCKET_TIMEOUT_FOR_POLLING", ")", "conn", "=", "s", ".", "connect_ex", "(", "(", "host", ",", "port", ")", ")", "Message", ".", "new", "(", "message_type", "=", "'acceptance:verify_socket'", ",", "host", "=", "host", ",", "port", "=", "port", ",", "result", "=", "conn", ")", ".", "write", "(", ")", "return", "(", "conn", "==", "0", ")", "dl", "=", "loop_until", "(", "reactor", ",", "can_connect", ")", "return", "dl" ]
attempt to bind to the sockets to verify that they are available .
train
false
36,711
def createAppendByTextb(parentNode, xmlText): monad = OpenMonad(parentNode) for character in xmlText: monad = monad.getNextMonad(character)
[ "def", "createAppendByTextb", "(", "parentNode", ",", "xmlText", ")", ":", "monad", "=", "OpenMonad", "(", "parentNode", ")", "for", "character", "in", "xmlText", ":", "monad", "=", "monad", ".", "getNextMonad", "(", "character", ")" ]
create and append the child nodes from the xmltext .
train
false
36,713
def modcheck(value): rearranged = (value[4:] + value[:4]) converted = [char_value(char) for char in rearranged] integerized = int(''.join([str(i) for i in converted])) return ((integerized % 97) == 1)
[ "def", "modcheck", "(", "value", ")", ":", "rearranged", "=", "(", "value", "[", "4", ":", "]", "+", "value", "[", ":", "4", "]", ")", "converted", "=", "[", "char_value", "(", "char", ")", "for", "char", "in", "rearranged", "]", "integerized", "=", "int", "(", "''", ".", "join", "(", "[", "str", "(", "i", ")", "for", "i", "in", "converted", "]", ")", ")", "return", "(", "(", "integerized", "%", "97", ")", "==", "1", ")" ]
check if the value string passes the mod97-test .
train
true
36,714
def process_email_outbox(): msg.process_outbox(contact_method='EMAIL')
[ "def", "process_email_outbox", "(", ")", ":", "msg", ".", "process_outbox", "(", "contact_method", "=", "'EMAIL'", ")" ]
send pending email messages .
train
false
36,715
def is_func_default(node): parent = node.scope() if isinstance(parent, astroid.Function): for default_node in parent.args.defaults: for default_name_node in default_node.nodes_of_class(astroid.Name): if (default_name_node is node): return True return False
[ "def", "is_func_default", "(", "node", ")", ":", "parent", "=", "node", ".", "scope", "(", ")", "if", "isinstance", "(", "parent", ",", "astroid", ".", "Function", ")", ":", "for", "default_node", "in", "parent", ".", "args", ".", "defaults", ":", "for", "default_name_node", "in", "default_node", ".", "nodes_of_class", "(", "astroid", ".", "Name", ")", ":", "if", "(", "default_name_node", "is", "node", ")", ":", "return", "True", "return", "False" ]
return true if the given name node is used in function default arguments value .
train
false
36,716
def plot_conv_weights(layer, figsize=(6, 6)): W = layer.W.get_value() shape = W.shape nrows = np.ceil(np.sqrt(shape[0])).astype(int) ncols = nrows for feature_map in range(shape[1]): (figs, axes) = plt.subplots(nrows, ncols, figsize=figsize, squeeze=False) for ax in axes.flatten(): ax.set_xticks([]) ax.set_yticks([]) ax.axis('off') for (i, (r, c)) in enumerate(product(range(nrows), range(ncols))): if (i >= shape[0]): break axes[(r, c)].imshow(W[(i, feature_map)], cmap='gray', interpolation='none') return plt
[ "def", "plot_conv_weights", "(", "layer", ",", "figsize", "=", "(", "6", ",", "6", ")", ")", ":", "W", "=", "layer", ".", "W", ".", "get_value", "(", ")", "shape", "=", "W", ".", "shape", "nrows", "=", "np", ".", "ceil", "(", "np", ".", "sqrt", "(", "shape", "[", "0", "]", ")", ")", ".", "astype", "(", "int", ")", "ncols", "=", "nrows", "for", "feature_map", "in", "range", "(", "shape", "[", "1", "]", ")", ":", "(", "figs", ",", "axes", ")", "=", "plt", ".", "subplots", "(", "nrows", ",", "ncols", ",", "figsize", "=", "figsize", ",", "squeeze", "=", "False", ")", "for", "ax", "in", "axes", ".", "flatten", "(", ")", ":", "ax", ".", "set_xticks", "(", "[", "]", ")", "ax", ".", "set_yticks", "(", "[", "]", ")", "ax", ".", "axis", "(", "'off'", ")", "for", "(", "i", ",", "(", "r", ",", "c", ")", ")", "in", "enumerate", "(", "product", "(", "range", "(", "nrows", ")", ",", "range", "(", "ncols", ")", ")", ")", ":", "if", "(", "i", ">=", "shape", "[", "0", "]", ")", ":", "break", "axes", "[", "(", "r", ",", "c", ")", "]", ".", "imshow", "(", "W", "[", "(", "i", ",", "feature_map", ")", "]", ",", "cmap", "=", "'gray'", ",", "interpolation", "=", "'none'", ")", "return", "plt" ]
plot the weights of a specific layer .
train
true
36,717
@bdd.then(bdd.parsers.parse('The session should look like:\n{expected}')) def compare_session(request, quteproc, expected): quteproc.compare_session(expected)
[ "@", "bdd", ".", "then", "(", "bdd", ".", "parsers", ".", "parse", "(", "'The session should look like:\\n{expected}'", ")", ")", "def", "compare_session", "(", "request", ",", "quteproc", ",", "expected", ")", ":", "quteproc", ".", "compare_session", "(", "expected", ")" ]
compare the current sessions against the given template .
train
false
36,719
def build_standard_config(module, doctype_info): if (not frappe.db.get_value(u'Module Def', module)): frappe.throw(_(u'Module Not Found')) data = [] add_section(data, _(u'Documents'), u'fa fa-star', [d for d in doctype_info if (d.document_type in (u'Document', u'Transaction'))]) add_section(data, _(u'Setup'), u'fa fa-cog', [d for d in doctype_info if (d.document_type in (u'Master', u'Setup', u''))]) add_section(data, _(u'Standard Reports'), u'fa fa-list', get_report_list(module, is_standard=u'Yes')) return data
[ "def", "build_standard_config", "(", "module", ",", "doctype_info", ")", ":", "if", "(", "not", "frappe", ".", "db", ".", "get_value", "(", "u'Module Def'", ",", "module", ")", ")", ":", "frappe", ".", "throw", "(", "_", "(", "u'Module Not Found'", ")", ")", "data", "=", "[", "]", "add_section", "(", "data", ",", "_", "(", "u'Documents'", ")", ",", "u'fa fa-star'", ",", "[", "d", "for", "d", "in", "doctype_info", "if", "(", "d", ".", "document_type", "in", "(", "u'Document'", ",", "u'Transaction'", ")", ")", "]", ")", "add_section", "(", "data", ",", "_", "(", "u'Setup'", ")", ",", "u'fa fa-cog'", ",", "[", "d", "for", "d", "in", "doctype_info", "if", "(", "d", ".", "document_type", "in", "(", "u'Master'", ",", "u'Setup'", ",", "u''", ")", ")", "]", ")", "add_section", "(", "data", ",", "_", "(", "u'Standard Reports'", ")", ",", "u'fa fa-list'", ",", "get_report_list", "(", "module", ",", "is_standard", "=", "u'Yes'", ")", ")", "return", "data" ]
build standard module data from doctypes .
train
false
36,724
def _get_cyg_dir(cyg_arch='x86_64'): if (cyg_arch == 'x86_64'): return 'cygwin64' elif (cyg_arch == 'x86'): return 'cygwin' raise SaltInvocationError('Invalid architecture {arch}'.format(arch=cyg_arch))
[ "def", "_get_cyg_dir", "(", "cyg_arch", "=", "'x86_64'", ")", ":", "if", "(", "cyg_arch", "==", "'x86_64'", ")", ":", "return", "'cygwin64'", "elif", "(", "cyg_arch", "==", "'x86'", ")", ":", "return", "'cygwin'", "raise", "SaltInvocationError", "(", "'Invalid architecture {arch}'", ".", "format", "(", "arch", "=", "cyg_arch", ")", ")" ]
return the cygwin install directory based on the architecture .
train
false
36,726
@auth.route('/reauth', methods=['GET', 'POST']) @limiter.exempt @login_required def reauth(): if (not login_fresh()): form = ReauthForm(request.form) if form.validate_on_submit(): if current_user.check_password(form.password.data): confirm_login() flash(_('Reauthenticated.'), 'success') return redirect_or_next(current_user.url) flash(_('Wrong password.'), 'danger') return render_template('auth/reauth.html', form=form) return redirect((request.args.get('next') or current_user.url))
[ "@", "auth", ".", "route", "(", "'/reauth'", ",", "methods", "=", "[", "'GET'", ",", "'POST'", "]", ")", "@", "limiter", ".", "exempt", "@", "login_required", "def", "reauth", "(", ")", ":", "if", "(", "not", "login_fresh", "(", ")", ")", ":", "form", "=", "ReauthForm", "(", "request", ".", "form", ")", "if", "form", ".", "validate_on_submit", "(", ")", ":", "if", "current_user", ".", "check_password", "(", "form", ".", "password", ".", "data", ")", ":", "confirm_login", "(", ")", "flash", "(", "_", "(", "'Reauthenticated.'", ")", ",", "'success'", ")", "return", "redirect_or_next", "(", "current_user", ".", "url", ")", "flash", "(", "_", "(", "'Wrong password.'", ")", ",", "'danger'", ")", "return", "render_template", "(", "'auth/reauth.html'", ",", "form", "=", "form", ")", "return", "redirect", "(", "(", "request", ".", "args", ".", "get", "(", "'next'", ")", "or", "current_user", ".", "url", ")", ")" ]
reauthenticates a user .
train
false
36,727
def redact_loc(image_meta, copy_dict=True): if copy_dict: new_image_meta = copy.copy(image_meta) else: new_image_meta = image_meta new_image_meta.pop('location', None) new_image_meta.pop('location_data', None) return new_image_meta
[ "def", "redact_loc", "(", "image_meta", ",", "copy_dict", "=", "True", ")", ":", "if", "copy_dict", ":", "new_image_meta", "=", "copy", ".", "copy", "(", "image_meta", ")", "else", ":", "new_image_meta", "=", "image_meta", "new_image_meta", ".", "pop", "(", "'location'", ",", "None", ")", "new_image_meta", ".", "pop", "(", "'location_data'", ",", "None", ")", "return", "new_image_meta" ]
create a shallow copy of image meta with location removed for security .
train
false
36,728
def mvn_loglike(x, sigma): sigmainv = linalg.inv(sigma) logdetsigma = np.log(np.linalg.det(sigma)) nobs = len(x) llf = (- np.dot(x, np.dot(sigmainv, x))) llf -= (nobs * np.log((2 * np.pi))) llf -= logdetsigma llf *= 0.5 return llf
[ "def", "mvn_loglike", "(", "x", ",", "sigma", ")", ":", "sigmainv", "=", "linalg", ".", "inv", "(", "sigma", ")", "logdetsigma", "=", "np", ".", "log", "(", "np", ".", "linalg", ".", "det", "(", "sigma", ")", ")", "nobs", "=", "len", "(", "x", ")", "llf", "=", "(", "-", "np", ".", "dot", "(", "x", ",", "np", ".", "dot", "(", "sigmainv", ",", "x", ")", ")", ")", "llf", "-=", "(", "nobs", "*", "np", ".", "log", "(", "(", "2", "*", "np", ".", "pi", ")", ")", ")", "llf", "-=", "logdetsigma", "llf", "*=", "0.5", "return", "llf" ]
loglike multivariate normal assumes x is 1d .
train
false
36,730
def parse_submodules(config): for section in config.keys(): (section_kind, section_name) = section if (section_kind == 'submodule'): sm_path = config.get(section, 'path') sm_url = config.get(section, 'url') (yield (sm_path, sm_url, section_name))
[ "def", "parse_submodules", "(", "config", ")", ":", "for", "section", "in", "config", ".", "keys", "(", ")", ":", "(", "section_kind", ",", "section_name", ")", "=", "section", "if", "(", "section_kind", "==", "'submodule'", ")", ":", "sm_path", "=", "config", ".", "get", "(", "section", ",", "'path'", ")", "sm_url", "=", "config", ".", "get", "(", "section", ",", "'url'", ")", "(", "yield", "(", "sm_path", ",", "sm_url", ",", "section_name", ")", ")" ]
parse a gitmodules gitconfig file .
train
false
36,731
def build_or_str(elements, str_format=None): if (not elements): return '' if (not isinstance(elements, six.string_types)): elements = _(' or ').join(elements) if str_format: return (str_format % elements) return elements
[ "def", "build_or_str", "(", "elements", ",", "str_format", "=", "None", ")", ":", "if", "(", "not", "elements", ")", ":", "return", "''", "if", "(", "not", "isinstance", "(", "elements", ",", "six", ".", "string_types", ")", ")", ":", "elements", "=", "_", "(", "' or '", ")", ".", "join", "(", "elements", ")", "if", "str_format", ":", "return", "(", "str_format", "%", "elements", ")", "return", "elements" ]
builds a string of elements joined by or .
train
false
36,732
def CellIsRule(operator=None, formula=None, stopIfTrue=None, font=None, border=None, fill=None): expand = {'>': 'greaterThan', '>=': 'greaterThanOrEqual', '<': 'lessThan', '<=': 'lessThanOrEqual', '=': 'equal', '==': 'equal', '!=': 'notEqual'} operator = expand.get(operator, operator) rule = Rule(type='cellIs', operator=operator, formula=formula, stopIfTrue=stopIfTrue) rule.dxf = DifferentialStyle(font=font, border=border, fill=fill) return rule
[ "def", "CellIsRule", "(", "operator", "=", "None", ",", "formula", "=", "None", ",", "stopIfTrue", "=", "None", ",", "font", "=", "None", ",", "border", "=", "None", ",", "fill", "=", "None", ")", ":", "expand", "=", "{", "'>'", ":", "'greaterThan'", ",", "'>='", ":", "'greaterThanOrEqual'", ",", "'<'", ":", "'lessThan'", ",", "'<='", ":", "'lessThanOrEqual'", ",", "'='", ":", "'equal'", ",", "'=='", ":", "'equal'", ",", "'!='", ":", "'notEqual'", "}", "operator", "=", "expand", ".", "get", "(", "operator", ",", "operator", ")", "rule", "=", "Rule", "(", "type", "=", "'cellIs'", ",", "operator", "=", "operator", ",", "formula", "=", "formula", ",", "stopIfTrue", "=", "stopIfTrue", ")", "rule", ".", "dxf", "=", "DifferentialStyle", "(", "font", "=", "font", ",", "border", "=", "border", ",", "fill", "=", "fill", ")", "return", "rule" ]
conditional formatting rule based on cell contents .
train
false
36,733
def get_column_names(line_contents, parent_key=''): column_names = [] for (k, v) in line_contents.iteritems(): column_name = ('{0}.{1}'.format(parent_key, k) if parent_key else k) if isinstance(v, collections.MutableMapping): column_names.extend(get_column_names(v, column_name).items()) else: column_names.append((column_name, v)) return dict(column_names)
[ "def", "get_column_names", "(", "line_contents", ",", "parent_key", "=", "''", ")", ":", "column_names", "=", "[", "]", "for", "(", "k", ",", "v", ")", "in", "line_contents", ".", "iteritems", "(", ")", ":", "column_name", "=", "(", "'{0}.{1}'", ".", "format", "(", "parent_key", ",", "k", ")", "if", "parent_key", "else", "k", ")", "if", "isinstance", "(", "v", ",", "collections", ".", "MutableMapping", ")", ":", "column_names", ".", "extend", "(", "get_column_names", "(", "v", ",", "column_name", ")", ".", "items", "(", ")", ")", "else", ":", "column_names", ".", "append", "(", "(", "column_name", ",", "v", ")", ")", "return", "dict", "(", "column_names", ")" ]
return a list of flattened key names given a dict .
train
false
36,734
def _to_binary_string_py2(text): return str(text)
[ "def", "_to_binary_string_py2", "(", "text", ")", ":", "return", "str", "(", "text", ")" ]
converts a string to a binary string if it is not already one .
train
false
36,735
@gating_enabled(default=[]) def get_gated_content(course, user): if _has_access_to_course(user, 'staff', course.id): return [] else: return [m['content_id'] for m in find_gating_milestones(course.id, None, 'requires', {'id': user.id})]
[ "@", "gating_enabled", "(", "default", "=", "[", "]", ")", "def", "get_gated_content", "(", "course", ",", "user", ")", ":", "if", "_has_access_to_course", "(", "user", ",", "'staff'", ",", "course", ".", "id", ")", ":", "return", "[", "]", "else", ":", "return", "[", "m", "[", "'content_id'", "]", "for", "m", "in", "find_gating_milestones", "(", "course", ".", "id", ",", "None", ",", "'requires'", ",", "{", "'id'", ":", "user", ".", "id", "}", ")", "]" ]
returns the unfulfilled gated content usage keys in the given course .
train
false
36,740
def change_weibo_header(uri, headers, body): auth = headers.get('Authorization') if auth: auth = auth.replace('Bearer', 'OAuth2') headers['Authorization'] = auth return (uri, headers, body)
[ "def", "change_weibo_header", "(", "uri", ",", "headers", ",", "body", ")", ":", "auth", "=", "headers", ".", "get", "(", "'Authorization'", ")", "if", "auth", ":", "auth", "=", "auth", ".", "replace", "(", "'Bearer'", ",", "'OAuth2'", ")", "headers", "[", "'Authorization'", "]", "=", "auth", "return", "(", "uri", ",", "headers", ",", "body", ")" ]
since weibo is a rubbish server .
train
true
36,742
def coregistration(tabbed=False, split=True, scene_width=500, inst=None, subject=None, subjects_dir=None, guess_mri_subject=None): _check_mayavi_version() from ._backend import _check_backend _check_backend() from ._coreg_gui import CoregFrame, _make_view view = _make_view(tabbed, split, scene_width) gui = CoregFrame(inst, subject, subjects_dir, guess_mri_subject) gui.configure_traits(view=view) return gui
[ "def", "coregistration", "(", "tabbed", "=", "False", ",", "split", "=", "True", ",", "scene_width", "=", "500", ",", "inst", "=", "None", ",", "subject", "=", "None", ",", "subjects_dir", "=", "None", ",", "guess_mri_subject", "=", "None", ")", ":", "_check_mayavi_version", "(", ")", "from", ".", "_backend", "import", "_check_backend", "_check_backend", "(", ")", "from", ".", "_coreg_gui", "import", "CoregFrame", ",", "_make_view", "view", "=", "_make_view", "(", "tabbed", ",", "split", ",", "scene_width", ")", "gui", "=", "CoregFrame", "(", "inst", ",", "subject", ",", "subjects_dir", ",", "guess_mri_subject", ")", "gui", ".", "configure_traits", "(", "view", "=", "view", ")", "return", "gui" ]
coregister an mri with a subjects head shape .
train
false
36,744
def getCircleIntersectionLoops(circleIntersections): circleIntersectionLoops = [] for circleIntersection in circleIntersections: if (not circleIntersection.steppedOn): circleIntersectionLoop = [circleIntersection] circleIntersectionLoops.append(circleIntersectionLoop) addCircleIntersectionLoop(circleIntersectionLoop, circleIntersections) return circleIntersectionLoops
[ "def", "getCircleIntersectionLoops", "(", "circleIntersections", ")", ":", "circleIntersectionLoops", "=", "[", "]", "for", "circleIntersection", "in", "circleIntersections", ":", "if", "(", "not", "circleIntersection", ".", "steppedOn", ")", ":", "circleIntersectionLoop", "=", "[", "circleIntersection", "]", "circleIntersectionLoops", ".", "append", "(", "circleIntersectionLoop", ")", "addCircleIntersectionLoop", "(", "circleIntersectionLoop", ",", "circleIntersections", ")", "return", "circleIntersectionLoops" ]
get all the loops going through the circle intersections .
train
false
36,745
def render_cheetah_tmpl(tmplstr, context, tmplpath=None): from Cheetah.Template import Template return str(Template(tmplstr, searchList=[context]))
[ "def", "render_cheetah_tmpl", "(", "tmplstr", ",", "context", ",", "tmplpath", "=", "None", ")", ":", "from", "Cheetah", ".", "Template", "import", "Template", "return", "str", "(", "Template", "(", "tmplstr", ",", "searchList", "=", "[", "context", "]", ")", ")" ]
render a cheetah template .
train
false
36,746
def getSectionNumber(header): if (not header): return None return domhelpers.gatherTextNodes(header.childNodes[0])
[ "def", "getSectionNumber", "(", "header", ")", ":", "if", "(", "not", "header", ")", ":", "return", "None", "return", "domhelpers", ".", "gatherTextNodes", "(", "header", ".", "childNodes", "[", "0", "]", ")" ]
retrieve the section number of the given node .
train
false
36,749
def _sampleDistribution(params, numSamples, verbosity=0): if params.has_key('name'): if (params['name'] == 'normal'): samples = numpy.random.normal(loc=params['mean'], scale=math.sqrt(params['variance']), size=numSamples) elif (params['name'] == 'pareto'): samples = numpy.random.pareto(params['alpha'], size=numSamples) elif (params['name'] == 'beta'): samples = numpy.random.beta(a=params['alpha'], b=params['beta'], size=numSamples) else: raise ValueError(('Undefined distribution: ' + params['name'])) else: raise ValueError(('Bad distribution params: ' + str(params))) if (verbosity > 0): print '\nSampling from distribution:', params print 'After estimation, mean=', numpy.mean(samples), 'var=', numpy.var(samples), 'stdev=', math.sqrt(numpy.var(samples)) return samples
[ "def", "_sampleDistribution", "(", "params", ",", "numSamples", ",", "verbosity", "=", "0", ")", ":", "if", "params", ".", "has_key", "(", "'name'", ")", ":", "if", "(", "params", "[", "'name'", "]", "==", "'normal'", ")", ":", "samples", "=", "numpy", ".", "random", ".", "normal", "(", "loc", "=", "params", "[", "'mean'", "]", ",", "scale", "=", "math", ".", "sqrt", "(", "params", "[", "'variance'", "]", ")", ",", "size", "=", "numSamples", ")", "elif", "(", "params", "[", "'name'", "]", "==", "'pareto'", ")", ":", "samples", "=", "numpy", ".", "random", ".", "pareto", "(", "params", "[", "'alpha'", "]", ",", "size", "=", "numSamples", ")", "elif", "(", "params", "[", "'name'", "]", "==", "'beta'", ")", ":", "samples", "=", "numpy", ".", "random", ".", "beta", "(", "a", "=", "params", "[", "'alpha'", "]", ",", "b", "=", "params", "[", "'beta'", "]", ",", "size", "=", "numSamples", ")", "else", ":", "raise", "ValueError", "(", "(", "'Undefined distribution: '", "+", "params", "[", "'name'", "]", ")", ")", "else", ":", "raise", "ValueError", "(", "(", "'Bad distribution params: '", "+", "str", "(", "params", ")", ")", ")", "if", "(", "verbosity", ">", "0", ")", ":", "print", "'\\nSampling from distribution:'", ",", "params", "print", "'After estimation, mean='", ",", "numpy", ".", "mean", "(", "samples", ")", ",", "'var='", ",", "numpy", ".", "var", "(", "samples", ")", ",", "'stdev='", ",", "math", ".", "sqrt", "(", "numpy", ".", "var", "(", "samples", ")", ")", "return", "samples" ]
given the parameters of a distribution .
train
false
36,750
def validate_domain(value): if (not re.search(u'^[a-zA-Z0-9-\\.]+$', value)): raise ValidationError(u'"{}" contains unexpected characters'.format(value))
[ "def", "validate_domain", "(", "value", ")", ":", "if", "(", "not", "re", ".", "search", "(", "u'^[a-zA-Z0-9-\\\\.]+$'", ",", "value", ")", ")", ":", "raise", "ValidationError", "(", "u'\"{}\" contains unexpected characters'", ".", "format", "(", "value", ")", ")" ]
error if the domain contains unexpected characters .
train
false
36,751
def check_data_query_args(data_query_time, data_query_tz): if ((data_query_time is None) ^ (data_query_tz is None)): raise ValueError(("either 'data_query_time' and 'data_query_tz' must both be None or neither may be None (got %r, %r)" % (data_query_time, data_query_tz)))
[ "def", "check_data_query_args", "(", "data_query_time", ",", "data_query_tz", ")", ":", "if", "(", "(", "data_query_time", "is", "None", ")", "^", "(", "data_query_tz", "is", "None", ")", ")", ":", "raise", "ValueError", "(", "(", "\"either 'data_query_time' and 'data_query_tz' must both be None or neither may be None (got %r, %r)\"", "%", "(", "data_query_time", ",", "data_query_tz", ")", ")", ")" ]
checks the data_query_time and data_query_tz arguments for loaders and raises a standard exception if one is none and the other is not .
train
false
36,752
def qt5_qml_plugins_binaries(directory): binaries = [] qmldir = qt5_qml_dir() qt5_qml_plugin_dir = os.path.join(qmldir, directory) files = misc.dlls_in_subdirs(qt5_qml_plugin_dir) for f in files: relpath = os.path.relpath(f, qmldir) (instdir, file) = os.path.split(relpath) instdir = os.path.join('qml', instdir) logger.debug(('qt5_qml_plugins_binaries installing %s in %s' % (f, instdir))) binaries.append((f, instdir)) return binaries
[ "def", "qt5_qml_plugins_binaries", "(", "directory", ")", ":", "binaries", "=", "[", "]", "qmldir", "=", "qt5_qml_dir", "(", ")", "qt5_qml_plugin_dir", "=", "os", ".", "path", ".", "join", "(", "qmldir", ",", "directory", ")", "files", "=", "misc", ".", "dlls_in_subdirs", "(", "qt5_qml_plugin_dir", ")", "for", "f", "in", "files", ":", "relpath", "=", "os", ".", "path", ".", "relpath", "(", "f", ",", "qmldir", ")", "(", "instdir", ",", "file", ")", "=", "os", ".", "path", ".", "split", "(", "relpath", ")", "instdir", "=", "os", ".", "path", ".", "join", "(", "'qml'", ",", "instdir", ")", "logger", ".", "debug", "(", "(", "'qt5_qml_plugins_binaries installing %s in %s'", "%", "(", "f", ",", "instdir", ")", ")", ")", "binaries", ".", "append", "(", "(", "f", ",", "instdir", ")", ")", "return", "binaries" ]
return list of dynamic libraries formatted for mod .
train
false
36,753
def dup_nth(f, n, K): if (n < 0): raise IndexError(("'n' must be non-negative, got %i" % n)) elif (n >= len(f)): return K.zero else: return f[(dup_degree(f) - n)]
[ "def", "dup_nth", "(", "f", ",", "n", ",", "K", ")", ":", "if", "(", "n", "<", "0", ")", ":", "raise", "IndexError", "(", "(", "\"'n' must be non-negative, got %i\"", "%", "n", ")", ")", "elif", "(", "n", ">=", "len", "(", "f", ")", ")", ":", "return", "K", ".", "zero", "else", ":", "return", "f", "[", "(", "dup_degree", "(", "f", ")", "-", "n", ")", "]" ]
return the n-th coefficient of f in k[x] .
train
false
36,754
def is_class_private_name(name): return (name.startswith('__') and (not name.endswith('__')))
[ "def", "is_class_private_name", "(", "name", ")", ":", "return", "(", "name", ".", "startswith", "(", "'__'", ")", "and", "(", "not", "name", ".", "endswith", "(", "'__'", ")", ")", ")" ]
determine if a name is a class private name .
train
false
36,756
def _DoesTargetTypeRequireBuild(target_dict): return bool(((target_dict['type'] != 'none') or target_dict.get('actions') or target_dict.get('rules')))
[ "def", "_DoesTargetTypeRequireBuild", "(", "target_dict", ")", ":", "return", "bool", "(", "(", "(", "target_dict", "[", "'type'", "]", "!=", "'none'", ")", "or", "target_dict", ".", "get", "(", "'actions'", ")", "or", "target_dict", ".", "get", "(", "'rules'", ")", ")", ")" ]
returns true if the target type is such that it needs to be built .
train
false
36,757
def get_default_ca_certs(): if (not hasattr(get_default_ca_certs, '_path')): for path in ('/etc/pki/ca-trust/extracted/openssl/ca-bundle.trust.crt', '/etc/ssl/certs', '/etc/ssl/certificates'): if os.path.exists(path): get_default_ca_certs._path = path break else: get_default_ca_certs._path = None return get_default_ca_certs._path
[ "def", "get_default_ca_certs", "(", ")", ":", "if", "(", "not", "hasattr", "(", "get_default_ca_certs", ",", "'_path'", ")", ")", ":", "for", "path", "in", "(", "'/etc/pki/ca-trust/extracted/openssl/ca-bundle.trust.crt'", ",", "'/etc/ssl/certs'", ",", "'/etc/ssl/certificates'", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "get_default_ca_certs", ".", "_path", "=", "path", "break", "else", ":", "get_default_ca_certs", ".", "_path", "=", "None", "return", "get_default_ca_certs", ".", "_path" ]
gets the default ca certificates if found .
train
true
36,758
def resolve_url(to, *args, **kwargs): if hasattr(to, 'get_absolute_url'): return to.get_absolute_url() try: return urlresolvers.reverse(to, args=args, kwargs=kwargs) except urlresolvers.NoReverseMatch: if callable(to): raise if (('/' not in to) and ('.' not in to)): raise return to
[ "def", "resolve_url", "(", "to", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "hasattr", "(", "to", ",", "'get_absolute_url'", ")", ":", "return", "to", ".", "get_absolute_url", "(", ")", "try", ":", "return", "urlresolvers", ".", "reverse", "(", "to", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")", "except", "urlresolvers", ".", "NoReverseMatch", ":", "if", "callable", "(", "to", ")", ":", "raise", "if", "(", "(", "'/'", "not", "in", "to", ")", "and", "(", "'.'", "not", "in", "to", ")", ")", ":", "raise", "return", "to" ]
return a url appropriate for the arguments passed .
train
false