text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def patch_certificate_signing_request(self, name, body, **kwargs): """ partially update the specified CertificateSigningRequest This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_certifi...
[ "def", "patch_certificate_signing_request", "(", "self", ",", "name", ",", "body", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", "...
78.8
49.84
def guard_submit(obj): """Returns if 'submit' transition can be applied to the worksheet passed in. By default, the target state for the 'submit' transition for a worksheet is 'to_be_verified', so this guard returns true if all the analyses assigned to the worksheet have already been submitted. Those an...
[ "def", "guard_submit", "(", "obj", ")", ":", "analyses", "=", "obj", ".", "getAnalyses", "(", ")", "if", "not", "analyses", ":", "# An empty worksheet cannot be submitted", "return", "False", "can_submit", "=", "False", "for", "analysis", "in", "obj", ".", "ge...
45.3125
21.28125
def configure_profile(msg_type, profile_name, data, auth): """ Create the profile entry. Args: :msg_type: (str) message type to create config entry. :profile_name: (str) name of the profile entry :data: (dict) dict values for the 'settings' :auth: (dict) auth parameters ...
[ "def", "configure_profile", "(", "msg_type", ",", "profile_name", ",", "data", ",", "auth", ")", ":", "with", "jsonconfig", ".", "Config", "(", "\"messages\"", ",", "indent", "=", "4", ")", "as", "cfg", ":", "write_data", "(", "msg_type", ",", "profile_nam...
38.0625
17.8125
def get_config(cfg, number, name, connection_name): """Initialize a new consumer thread, setting defaults and config values :param dict cfg: Consumer config section from YAML File :param int number: The identification number for the consumer :param str name: The name of the consumer ...
[ "def", "get_config", "(", "cfg", ",", "number", ",", "name", ",", "connection_name", ")", ":", "return", "{", "'connection'", ":", "cfg", "[", "'Connections'", "]", "[", "connection_name", "]", ",", "'consumer_name'", ":", "name", ",", "'process_name'", ":",...
39.933333
20.733333
def db(self, db_alias, shard_key=None): """ Получить экземпляр работы с БД :type db_alias: basestring Альяс БД из меты :type shard_key: Любой тип. Некоторый идентификатор, который поможет мете найти нужную шарду. Тип зависи от принимающей стороны :rtype: DbQueryService ""...
[ "def", "db", "(", "self", ",", "db_alias", ",", "shard_key", "=", "None", ")", ":", "if", "shard_key", "is", "None", ":", "shard_key", "=", "''", "db_key", "=", "db_alias", "+", "'__'", "+", "str", "(", "shard_key", ")", "if", "db_key", "not", "in", ...
48.142857
23.857143
def make_plot(time, config, step): """ create a three color and all composite images for a given time NOTE: channel mins and maxes are currently hardcoded since this is a very specific script :param i: the index to save the file as :param time: :param config: :return: """ fig, ax = p...
[ "def", "make_plot", "(", "time", ",", "config", ",", "step", ")", ":", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", ")", "try", ":", "result", "=", "Fetcher", "(", "time", ",", "products", "=", "config", ".", "products", ",", "suvi_composite_p...
39.125
18.875
def kill_definitions(self, atom, code_loc, data=None, dummy=True): """ Overwrite existing definitions w.r.t 'atom' with a dummy definition instance. A dummy definition will not be removed during simplification. :param Atom atom: :param CodeLocation code_loc: :param objec...
[ "def", "kill_definitions", "(", "self", ",", "atom", ",", "code_loc", ",", "data", "=", "None", ",", "dummy", "=", "True", ")", ":", "if", "data", "is", "None", ":", "data", "=", "DataSet", "(", "Undefined", "(", "atom", ".", "size", ")", ",", "ato...
33.733333
22.666667
def remove(self, items): """Remove messages from lease management.""" # Remove the ack ID from lease management, and decrement the # byte counter. for item in items: if self._leased_messages.pop(item.ack_id, None) is not None: self._bytes -= item.byte_size ...
[ "def", "remove", "(", "self", ",", "items", ")", ":", "# Remove the ack ID from lease management, and decrement the", "# byte counter.", "for", "item", "in", "items", ":", "if", "self", ".", "_leased_messages", ".", "pop", "(", "item", ".", "ack_id", ",", "None", ...
40.615385
20.615385
def QA_SU_save_stock_xdxr(client=DATABASE, ui_log=None, ui_progress=None): """[summary] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ stock_list = QA_fetch_get_stock_list().code.unique().tolist() # client.drop_collection('stock_xdxr') try: coll =...
[ "def", "QA_SU_save_stock_xdxr", "(", "client", "=", "DATABASE", ",", "ui_log", "=", "None", ",", "ui_progress", "=", "None", ")", ":", "stock_list", "=", "QA_fetch_get_stock_list", "(", ")", ".", "code", ".", "unique", "(", ")", ".", "tolist", "(", ")", ...
27.822581
19.096774
def handle_heartbeat(queue_name): """Updates the heartbeat message for a task.""" task_id = request.form.get('task_id', type=str) message = request.form.get('message', type=str) index = request.form.get('index', type=int) try: work_queue.heartbeat( queue_name, task_id...
[ "def", "handle_heartbeat", "(", "queue_name", ")", ":", "task_id", "=", "request", ".", "form", ".", "get", "(", "'task_id'", ",", "type", "=", "str", ")", "message", "=", "request", ".", "form", ".", "get", "(", "'message'", ",", "type", "=", "str", ...
35.894737
16.368421
def _handle_report(self, report): """Try to emit a report and possibly keep a copy of it""" keep_report = True if self.report_callback is not None: keep_report = self.report_callback(report, self.context) if keep_report: self.reports.append(report)
[ "def", "_handle_report", "(", "self", ",", "report", ")", ":", "keep_report", "=", "True", "if", "self", ".", "report_callback", "is", "not", "None", ":", "keep_report", "=", "self", ".", "report_callback", "(", "report", ",", "self", ".", "context", ")", ...
29.8
19.1
def GetHasherNamesFromString(cls, hasher_names_string): """Retrieves a list of a hasher names from a comma separated string. Takes a string of comma separated hasher names transforms it to a list of hasher names. Args: hasher_names_string (str): comma separated names of hashers to enable, ...
[ "def", "GetHasherNamesFromString", "(", "cls", ",", "hasher_names_string", ")", ":", "hasher_names", "=", "[", "]", "if", "not", "hasher_names_string", "or", "hasher_names_string", ".", "strip", "(", ")", "==", "'none'", ":", "return", "hasher_names", "if", "has...
30.363636
22.575758
def file_delete(context, id, file_id): """file_delete(context, id, path) Delete a job file >>> dcictl job-delete-file [OPTIONS] :param string id: ID of the job to delete file [required] :param string file_id: ID for the file to delete [required] """ dci_file.delete(context, id=file_id) ...
[ "def", "file_delete", "(", "context", ",", "id", ",", "file_id", ")", ":", "dci_file", ".", "delete", "(", "context", ",", "id", "=", "file_id", ")", "result", "=", "dci_file", ".", "delete", "(", "context", ",", "id", "=", "file_id", ")", "utils", "...
31
15.461538
def _build_matrix_non_uniform(p, q, coords, k): """Constructs the equation matrix for the finite difference coefficients of non-uniform grids at location k""" A = [[1] * (p+q+1)] for i in range(1, p + q + 1): line = [(coords[k+j] - coords[k])**i for j in range(-p, q+1)] A.append(line) re...
[ "def", "_build_matrix_non_uniform", "(", "p", ",", "q", ",", "coords", ",", "k", ")", ":", "A", "=", "[", "[", "1", "]", "*", "(", "p", "+", "q", "+", "1", ")", "]", "for", "i", "in", "range", "(", "1", ",", "p", "+", "q", "+", "1", ")", ...
47.142857
13.714286
def aptknt(tau, order): """Create an acceptable knot vector. Minimal emulation of MATLAB's ``aptknt``. The returned knot vector can be used to generate splines of desired `order` that are suitable for interpolation to the collocation sites `tau`. Note that this is only possible when ``len(tau)`` >= `order` + 1. ...
[ "def", "aptknt", "(", "tau", ",", "order", ")", ":", "tau", "=", "np", ".", "atleast_1d", "(", "tau", ")", "k", "=", "order", "+", "1", "if", "tau", ".", "ndim", ">", "1", ":", "raise", "ValueError", "(", "\"tau must be a list or a rank-1 array\"", ")"...
29.523077
24.553846
def obtain(self, dest): # type: (str) -> None """ Install or update in editable mode the package represented by this VersionControl object. Args: dest: the repository directory in which to install or update. """ url, rev_options = self.get_url_rev_optio...
[ "def", "obtain", "(", "self", ",", "dest", ")", ":", "# type: (str) -> None", "url", ",", "rev_options", "=", "self", ".", "get_url_rev_options", "(", "self", ".", "url", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dest", ")", ":", "self"...
32.543478
17.304348
def sampleLocationFromFeature(self, feature): """ Samples a location from one specific feature. This is only supported with three dimensions. """ if feature == "face": return self._sampleFromFaces() elif feature == "edge": return self._sampleFromEdges() elif feature == "vertex":...
[ "def", "sampleLocationFromFeature", "(", "self", ",", "feature", ")", ":", "if", "feature", "==", "\"face\"", ":", "return", "self", ".", "_sampleFromFaces", "(", ")", "elif", "feature", "==", "\"edge\"", ":", "return", "self", ".", "_sampleFromEdges", "(", ...
30.8125
11.9375
def translate_to_arpabet(self): ''' 转换成arpabet :return: ''' translations = [] for phoneme in self._phoneme_list: if phoneme.is_vowel: translations.append(phoneme.arpabet + self.stress.mark_arpabet()) else: translat...
[ "def", "translate_to_arpabet", "(", "self", ")", ":", "translations", "=", "[", "]", "for", "phoneme", "in", "self", ".", "_phoneme_list", ":", "if", "phoneme", ".", "is_vowel", ":", "translations", ".", "append", "(", "phoneme", ".", "arpabet", "+", "self...
24.866667
22.466667
def breaks_from_binwidth(x_range, binwidth=None, center=None, boundary=None): """ Calculate breaks given binwidth Parameters ---------- x_range : array_like Range over with to calculate the breaks. Must be of size 2. binwidth : float Separation b...
[ "def", "breaks_from_binwidth", "(", "x_range", ",", "binwidth", "=", "None", ",", "center", "=", "None", ",", "boundary", "=", "None", ")", ":", "if", "binwidth", "<=", "0", ":", "raise", "PlotnineError", "(", "\"The 'binwidth' must be positive.\"", ")", "if",...
30.555556
16.511111
def start_process(parser_args): """ Start up specific daemon """ import psutil import process_starter from synergy.system import process_helper try: pid = process_helper.get_process_pid(parser_args.process_name) if pid is not None: if psutil.pid_exists(pid): ...
[ "def", "start_process", "(", "parser_args", ")", ":", "import", "psutil", "import", "process_starter", "from", "synergy", ".", "system", "import", "process_helper", "try", ":", "pid", "=", "process_helper", ".", "get_process_pid", "(", "parser_args", ".", "process...
44.681818
25.954545
def readiterinit(d): """ Prepare to read data with ms.iter* """ # set requested time range based on given parameters starttime_mjd = d['starttime_mjd'] timeskip = d['inttime']*d['nskip'] starttime = qa.getvalue(qa.convert(qa.time(qa.quantity(starttime_mjd+timeskip/(24.*60*60),'d'),form=['ymd'],...
[ "def", "readiterinit", "(", "d", ")", ":", "# set requested time range based on given parameters", "starttime_mjd", "=", "d", "[", "'starttime_mjd'", "]", "timeskip", "=", "d", "[", "'inttime'", "]", "*", "d", "[", "'nskip'", "]", "starttime", "=", "qa", ".", ...
66.695652
44.043478
def unlink_reference(self, source, target): """Unlink the target from the source """ target_uid = api.get_uid(target) # get the storage key key = self.get_relationship_key(target) # get all backreferences from the source # N.B. only like this we get the persistent...
[ "def", "unlink_reference", "(", "self", ",", "source", ",", "target", ")", ":", "target_uid", "=", "api", ".", "get_uid", "(", "target", ")", "# get the storage key", "key", "=", "self", ".", "get_relationship_key", "(", "target", ")", "# get all backreferences ...
41.25
11.4
def post_optimization_step(self, batch_info, device, model, rollout): """ Steps to take after optimization has been done""" # Update target model for model_param, target_param in zip(model.parameters(), self.target_model.parameters()): # EWMA average model update target_p...
[ "def", "post_optimization_step", "(", "self", ",", "batch_info", ",", "device", ",", "model", ",", "rollout", ")", ":", "# Update target model", "for", "model_param", ",", "target_param", "in", "zip", "(", "model", ".", "parameters", "(", ")", ",", "self", "...
62.833333
23.333333
def new_histogram(name, reservoir=None): """ Build a new histogram metric with a given reservoir object If the reservoir is not provided, a uniform reservoir with the default size is used """ if reservoir is None: reservoir = histogram.UniformReservoir(histogram.DEFAULT_UNIFORM_RESERVOIR_SI...
[ "def", "new_histogram", "(", "name", ",", "reservoir", "=", "None", ")", ":", "if", "reservoir", "is", "None", ":", "reservoir", "=", "histogram", ".", "UniformReservoir", "(", "histogram", ".", "DEFAULT_UNIFORM_RESERVOIR_SIZE", ")", "return", "new_metric", "(",...
37.5
23.1
def _find_day_section_from_indices(indices, split_interval): """ Returns a list with [weekday, section] identifiers found using a list of indices. """ cells_day = 24 * 60 // split_interval rv = [[int(math.floor(i / cells_day)), i % cells_day] for i in indices] return rv
[ "def", "_find_day_section_from_indices", "(", "indices", ",", "split_interval", ")", ":", "cells_day", "=", "24", "*", "60", "//", "split_interval", "rv", "=", "[", "[", "int", "(", "math", ".", "floor", "(", "i", "/", "cells_day", ")", ")", ",", "i", ...
32.333333
17.222222
def check_elements(self): """ Checks element definitions. """ # ELEMENT TYPE CHECKING existing_types = set(self.elements.type.argiope.values.flatten()) allowed_types = set(ELEMENTS.keys()) if (existing_types <= allowed_types) == False: raise ValueError("Element types {0} not in know el...
[ "def", "check_elements", "(", "self", ")", ":", "# ELEMENT TYPE CHECKING", "existing_types", "=", "set", "(", "self", ".", "elements", ".", "type", ".", "argiope", ".", "values", ".", "flatten", "(", ")", ")", "allowed_types", "=", "set", "(", "ELEMENTS", ...
38.909091
14
def get_surface_boundaries(self): """ Returns the boundaries in the same format as a multiplanar surface, with two one-element lists of lons and lats """ mesh = self.mesh lons = numpy.concatenate((mesh.lons[0, :], mesh.lons[1:, -1], ...
[ "def", "get_surface_boundaries", "(", "self", ")", ":", "mesh", "=", "self", ".", "mesh", "lons", "=", "numpy", ".", "concatenate", "(", "(", "mesh", ".", "lons", "[", "0", ",", ":", "]", ",", "mesh", ".", "lons", "[", "1", ":", ",", "-", "1", ...
44.933333
13.333333
def run(self): """Runs server""" try: self._start() running = True while running: msg = '' name = '' client_id = '' request_id = '' request = self._socket.recv_string() s...
[ "def", "run", "(", "self", ")", ":", "try", ":", "self", ".", "_start", "(", ")", "running", "=", "True", "while", "running", ":", "msg", "=", "''", "name", "=", "''", "client_id", "=", "''", "request_id", "=", "''", "request", "=", "self", ".", ...
33.14
20.88
def newChannelOpened_channel_(self, notif, newChannel): """ Handle when a client connects to the server channel. (This method is called for both RFCOMM and L2CAP channels.) """ if newChannel is not None and newChannel.isIncoming(): # not sure if delegate really needs ...
[ "def", "newChannelOpened_channel_", "(", "self", ",", "notif", ",", "newChannel", ")", ":", "if", "newChannel", "is", "not", "None", "and", "newChannel", ".", "isIncoming", "(", ")", ":", "# not sure if delegate really needs to be set", "newChannel", ".", "setDelega...
44.545455
17.090909
def get_hierarchy_traversal_session(self, proxy): """Gets the ``OsidSession`` associated with the hierarchy traversal service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.hierarchy.HierarchyTraversalSession) - a ``HierarchyTraversalSession`` raise: NullArgum...
[ "def", "get_hierarchy_traversal_session", "(", "self", ",", "proxy", ")", ":", "if", "not", "self", ".", "supports_hierarchy_traversal", "(", ")", ":", "raise", "errors", ".", "Unimplemented", "(", ")", "# pylint: disable=no-member", "return", "sessions", ".", "Hi...
46.666667
16.944444
async def get_reviews(self, **params): """Receives all reviews by cid Accepts: - cid - coinid """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"} cid = params.get("cid", 0) coinid = params.get("...
[ "async", "def", "get_reviews", "(", "self", ",", "*", "*", "params", ")", ":", "if", "params", ".", "get", "(", "\"message\"", ")", ":", "params", "=", "json", ".", "loads", "(", "params", ".", "get", "(", "\"message\"", ",", "\"{}\"", ")", ")", "i...
26.416667
20.375
def get_shapes_intersecting_geometry( feed: "Feed", geometry, geo_shapes=None, *, geometrized: bool = False ) -> DataFrame: """ Return the slice of ``feed.shapes`` that contains all shapes that intersect the given Shapely geometry, e.g. a Polygon or LineString. Parameters ---------- feed : ...
[ "def", "get_shapes_intersecting_geometry", "(", "feed", ":", "\"Feed\"", ",", "geometry", ",", "geo_shapes", "=", "None", ",", "*", ",", "geometrized", ":", "bool", "=", "False", ")", "->", "DataFrame", ":", "if", "geo_shapes", "is", "not", "None", ":", "f...
27.866667
21.2
def folderitem(self, obj, item, index): """Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by ...
[ "def", "folderitem", "(", "self", ",", "obj", ",", "item", ",", "index", ")", ":", "cat", "=", "obj", ".", "getCategoryTitle", "(", ")", "cat_order", "=", "self", ".", "an_cats_order", ".", "get", "(", "cat", ")", "if", "self", ".", "do_cats", ":", ...
34.704225
16.661972
def push(self, request): """Push a request""" self.server.basic_publish( exchange='', routing_key=self.key, body=self._encode_request(request) )
[ "def", "push", "(", "self", ",", "request", ")", ":", "self", ".", "server", ".", "basic_publish", "(", "exchange", "=", "''", ",", "routing_key", "=", "self", ".", "key", ",", "body", "=", "self", ".", "_encode_request", "(", "request", ")", ")" ]
28.285714
11.714286
async def get_vm(self, vm_id): """ Dummy get_vm func """ if vm_id not in self._vms: raise DummyIaasVmNotFound() return self._vms[vm_id]
[ "async", "def", "get_vm", "(", "self", ",", "vm_id", ")", ":", "if", "vm_id", "not", "in", "self", ".", "_vms", ":", "raise", "DummyIaasVmNotFound", "(", ")", "return", "self", ".", "_vms", "[", "vm_id", "]" ]
33.4
5.2
def add_base_type_dynamically(error_type, additional_type): """ Utility method to create a new type dynamically, inheriting from both error_type (first) and additional_type (second). The class representation (repr(cls)) of the resulting class reflects this by displaying both names (fully qualified for t...
[ "def", "add_base_type_dynamically", "(", "error_type", ",", "additional_type", ")", ":", "# the new type created dynamically, with the same name", "class", "new_error_type", "(", "with_metaclass", "(", "MetaReprForValidator", ",", "error_type", ",", "additional_type", ",", "o...
42.875
31.291667
def status(self): """ The status of the container. For example, ``running``, or ``exited``. """ if isinstance(self.attrs['State'], dict): return self.attrs['State']['Status'] return self.attrs['State']
[ "def", "status", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "attrs", "[", "'State'", "]", ",", "dict", ")", ":", "return", "self", ".", "attrs", "[", "'State'", "]", "[", "'Status'", "]", "return", "self", ".", "attrs", "[", "'Sta...
35.285714
11.857143
def patText(s0): '''make text pattern''' arr = np.zeros((s0,s0), dtype=np.uint8) s = int(round(s0/100.)) p1 = 0 pp1 = int(round(s0/10.)) for pos0 in np.linspace(0,s0,10): cv2.putText(arr, 'helloworld', (p1,int(round(pos0))), cv2.FONT_HERSHEY_COMPLEX_SMALL, fo...
[ "def", "patText", "(", "s0", ")", ":", "arr", "=", "np", ".", "zeros", "(", "(", "s0", ",", "s0", ")", ",", "dtype", "=", "np", ".", "uint8", ")", "s", "=", "int", "(", "round", "(", "s0", "/", "100.", ")", ")", "p1", "=", "0", "pp1", "="...
31.6875
15.6875
def _generate_values_with_variability_and_constraints(self, symbols, starting_values, variable_parameters): """ Generates the `values_with_variability` formatted list from the provided symbols, starting values and variable parameters :param symbols: The symbols defining each of the valu...
[ "def", "_generate_values_with_variability_and_constraints", "(", "self", ",", "symbols", ",", "starting_values", ",", "variable_parameters", ")", ":", "values_with_variability", "=", "[", "]", "constraints", "=", "[", "]", "if", "not", "isinstance", "(", "variable_par...
47.076923
26.25641
def decompile(f): """ Decompile a function. Parameters ---------- f : function The function to decompile. Returns ------- ast : ast.FunctionDef A FunctionDef node that compiles to f. """ co = f.__code__ args, kwonly, varargs, varkwargs = paramnames(co) a...
[ "def", "decompile", "(", "f", ")", ":", "co", "=", "f", ".", "__code__", "args", ",", "kwonly", ",", "varargs", ",", "varkwargs", "=", "paramnames", "(", "co", ")", "annotations", "=", "f", ".", "__annotations__", "or", "{", "}", "defaults", "=", "li...
25.021739
17.978261
def get_filebase(path, pattern): """Get the end of *path* of same length as *pattern*.""" # A pattern can include directories tail_len = len(pattern.split(os.path.sep)) return os.path.join(*str(path).split(os.path.sep)[-tail_len:])
[ "def", "get_filebase", "(", "path", ",", "pattern", ")", ":", "# A pattern can include directories", "tail_len", "=", "len", "(", "pattern", ".", "split", "(", "os", ".", "path", ".", "sep", ")", ")", "return", "os", ".", "path", ".", "join", "(", "*", ...
48.6
8.2
def setHidden(self, state): """ Marks this item as hidden based on the state. This will affect all its children as well. :param state | <bool> """ super(XListGroupItem, self).setHidden(state) for child in self.children(): ...
[ "def", "setHidden", "(", "self", ",", "state", ")", ":", "super", "(", "XListGroupItem", ",", "self", ")", ".", "setHidden", "(", "state", ")", "for", "child", "in", "self", ".", "children", "(", ")", ":", "child", ".", "setHidden", "(", "state", "or...
32.818182
14.454545
def _get_firmware_update_xml_for_file_and_component( self, filename, component): """Creates the dynamic xml for flashing the device firmware via iLO. This method creates the dynamic xml for flashing the firmware, based on the component type so passed. :param filename: locati...
[ "def", "_get_firmware_update_xml_for_file_and_component", "(", "self", ",", "filename", ",", "component", ")", ":", "if", "component", "==", "'ilo'", ":", "cmd_name", "=", "'UPDATE_RIB_FIRMWARE'", "else", ":", "# Note(deray): Not explicitly checking for all other supported", ...
47.535714
17.214286
def example_lchab_to_lchuv(): """ This function shows very complex chain of conversions in action. LCHab to LCHuv involves four different calculations, making this the conversion requiring the most steps. """ print("=== Complex Example: LCHab->LCHuv ===") # Instantiate an LCHab color objec...
[ "def", "example_lchab_to_lchuv", "(", ")", ":", "print", "(", "\"=== Complex Example: LCHab->LCHuv ===\"", ")", "# Instantiate an LCHab color object with the given values.", "lchab", "=", "LCHabColor", "(", "0.903", ",", "16.447", ",", "352.252", ")", "# Show a string represe...
32.294118
15.823529
def _jacobian_both(nodes, degree, dimension): r"""Compute :math:`s` and :math:`t` partial of :math:`B`. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): Array of nodes in a surface. degree ...
[ "def", "_jacobian_both", "(", "nodes", ",", "degree", ",", "dimension", ")", ":", "_", ",", "num_nodes", "=", "nodes", ".", "shape", "result", "=", "np", ".", "empty", "(", "(", "2", "*", "dimension", ",", "num_nodes", "-", "degree", "-", "1", ")", ...
34.5
21.136364
def persist_trie_data_dict(self, trie_data_dict: Dict[Hash32, bytes]) -> None: """ Store raw trie data to db from a dict """ with self.db.atomic_batch() as db: for key, value in trie_data_dict.items(): db[key] = value
[ "def", "persist_trie_data_dict", "(", "self", ",", "trie_data_dict", ":", "Dict", "[", "Hash32", ",", "bytes", "]", ")", "->", "None", ":", "with", "self", ".", "db", ".", "atomic_batch", "(", ")", "as", "db", ":", "for", "key", ",", "value", "in", "...
38.714286
9.571429
def keys_breadth_first(self, include_dicts=False): """a generator that returns all the keys in a set of nested DotDict instances. The keys take the form X.Y.Z""" namespaces = [] for key in self._key_order: if isinstance(getattr(self, key), DotDict): namespace...
[ "def", "keys_breadth_first", "(", "self", ",", "include_dicts", "=", "False", ")", ":", "namespaces", "=", "[", "]", "for", "key", "in", "self", ".", "_key_order", ":", "if", "isinstance", "(", "getattr", "(", "self", ",", "key", ")", ",", "DotDict", "...
42.428571
10.857143
def cdd(d, k): """ Conditionally delete key (or list of keys) 'k' from dict 'd' """ if not isinstance(k, list): k = [k] for i in k: if i in d: d.pop(i)
[ "def", "cdd", "(", "d", ",", "k", ")", ":", "if", "not", "isinstance", "(", "k", ",", "list", ")", ":", "k", "=", "[", "k", "]", "for", "i", "in", "k", ":", "if", "i", "in", "d", ":", "d", ".", "pop", "(", "i", ")" ]
26.428571
18.142857
def consume(self, callback, queue): """ Register a new consumer. This consumer will be configured for every protocol this factory produces so it will be reconfigured on network failures. If a connection is already active, the consumer will be added to it. Args: ...
[ "def", "consume", "(", "self", ",", "callback", ",", "queue", ")", ":", "self", ".", "consumers", "[", "queue", "]", "=", "callback", "if", "self", ".", "_client_ready", ".", "called", ":", "return", "self", ".", "client", ".", "consume", "(", "callbac...
39.2
19.466667
def mangle_name(name): """Mangles a column name to a standard form, remoing illegal characters. :param name: :return: """ import re try: return re.sub('_+', '_', re.sub('[^\w_]', '_', name).lower()).rstrip('_') except TypeError: r...
[ "def", "mangle_name", "(", "name", ")", ":", "import", "re", "try", ":", "return", "re", ".", "sub", "(", "'_+'", ",", "'_'", ",", "re", ".", "sub", "(", "'[^\\w_]'", ",", "'_'", ",", "name", ")", ".", "lower", "(", ")", ")", ".", "rstrip", "("...
28.857143
23.357143
def set(self, key, value, time=0, compress_level=-1): """ Set a value for a key on server. :param key: Key's name :type key: str :param value: A value to be stored on server. :type value: object :param time: Time in seconds that your key will expire. :typ...
[ "def", "set", "(", "self", ",", "key", ",", "value", ",", "time", "=", "0", ",", "compress_level", "=", "-", "1", ")", ":", "server", "=", "self", ".", "_get_server", "(", "key", ")", "return", "server", ".", "set", "(", "key", ",", "value", ",",...
37.526316
13.947368
def draw_char_screen(self): """ Draws the output buffered in the char_buffer. """ self.screen = Image.new("RGB", (self.height, self.width)) self.drawer = ImageDraw.Draw(self.screen) for sy, line in enumerate(self.char_buffer): for sx, tinfo in enumerate(line): self.drawer.text((sx * 6, sy * 9), tinf...
[ "def", "draw_char_screen", "(", "self", ")", ":", "self", ".", "screen", "=", "Image", ".", "new", "(", "\"RGB\"", ",", "(", "self", ".", "height", ",", "self", ".", "width", ")", ")", "self", ".", "drawer", "=", "ImageDraw", ".", "Draw", "(", "sel...
33.090909
11.272727
def group(self): """(re-)group all logevents by the given group.""" if hasattr(self, 'group_by'): group_by = self.group_by else: group_by = self.default_group_by if self.args['group'] is not None: group_by = self.args['group'] self.gro...
[ "def", "group", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'group_by'", ")", ":", "group_by", "=", "self", ".", "group_by", "else", ":", "group_by", "=", "self", ".", "default_group_by", "if", "self", ".", "args", "[", "'group'", "]", ...
41.384615
15.076923
def delete_records(self, zone_name, record_type, subdomain): """ Delete record from have fieldType=type and subDomain=subdomain :param zone_name: Name of the zone :param record_type: fieldType :param subdomain: subDomain """ records = self._client.get('/domain/zon...
[ "def", "delete_records", "(", "self", ",", "zone_name", ",", "record_type", ",", "subdomain", ")", ":", "records", "=", "self", ".", "_client", ".", "get", "(", "'/domain/zone/{}/record'", ".", "format", "(", "zone_name", ")", ",", "fieldType", "=", "record_...
45.545455
14.090909
def get_list(list_type=None, search_term=None, page=None, page_size=None, sort_by=None): ''' Returns a list of domains for the particular user as a list of objects offset by ``page`` length of ``page_size`` list_type : ALL One of ``ALL``, ``EX...
[ "def", "get_list", "(", "list_type", "=", "None", ",", "search_term", "=", "None", ",", "page", "=", "None", ",", "page_size", "=", "None", ",", "sort_by", "=", "None", ")", ":", "opts", "=", "salt", ".", "utils", ".", "namecheap", ".", "get_opts", "...
29.835616
23.178082
def drop_pathlist(self, pathlist): """Drop path list""" if pathlist: files = ["r'%s'" % path for path in pathlist] if len(files) == 1: text = files[0] else: text = "[" + ", ".join(files) + "]" if self.new_input_line:...
[ "def", "drop_pathlist", "(", "self", ",", "pathlist", ")", ":", "if", "pathlist", ":", "files", "=", "[", "\"r'%s'\"", "%", "path", "for", "path", "in", "pathlist", "]", "if", "len", "(", "files", ")", "==", "1", ":", "text", "=", "files", "[", "0"...
34.166667
9.916667
def resume(self): """Resumes the pool and reindex all objects processed """ self.num_calls -= 1 if self.num_calls > 0: return logger.info("Resume actions for {} objects".format(len(self))) # Fetch the objects from the pool processed = list() f...
[ "def", "resume", "(", "self", ")", ":", "self", ".", "num_calls", "-=", "1", "if", "self", ".", "num_calls", ">", "0", ":", "return", "logger", ".", "info", "(", "\"Resume actions for {} objects\"", ".", "format", "(", "len", "(", "self", ")", ")", ")"...
37.259259
16.814815
async def total_albums(self, *, market: str = None) -> int: """get the total amout of tracks in the album. Parameters ---------- market : Optional[str] An ISO 3166-1 alpha-2 country code. Returns ------- total : int The total amount of al...
[ "async", "def", "total_albums", "(", "self", ",", "*", ",", "market", ":", "str", "=", "None", ")", "->", "int", ":", "data", "=", "await", "self", ".", "__client", ".", "http", ".", "artist_albums", "(", "self", ".", "id", ",", "limit", "=", "1", ...
29.933333
20
def resettable(f): """A decorator to simplify the context management of simple object attributes. Gets the value of the attribute prior to setting it, and stores a function to set the value to the old value in the HistoryManager. """ def wrapper(self, new_value): context = get_context(self)...
[ "def", "resettable", "(", "f", ")", ":", "def", "wrapper", "(", "self", ",", "new_value", ")", ":", "context", "=", "get_context", "(", "self", ")", "if", "context", ":", "old_value", "=", "getattr", "(", "self", ",", "f", ".", "__name__", ")", "# Do...
33.166667
19
def match(self, ra, dec, radius, maxmatch=1): """*match a corrdinate set against this Matcher object's coordinate set* **Key Arguments:** - ``ra`` -- list, numpy array or single ra value - ``dec`` -- --list, numpy array or single dec value (must match ra array length) ...
[ "def", "match", "(", "self", ",", "ra", ",", "dec", ",", "radius", ",", "maxmatch", "=", "1", ")", ":", "if", "self", ".", "convertToArray", "==", "True", ":", "from", "astrocalc", ".", "coords", "import", "coordinates_to_array", "ra", ",", "dec", "=",...
39.045455
27.939394
def get_database(self, database_name=None, username=None, password=None): """ Get a pymongo database handle, after authenticating. Authenticates using the username/password in the DB URI given to __init__() unless username/password is supplied as arguments. :param database_name...
[ "def", "get_database", "(", "self", ",", "database_name", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ")", ":", "if", "database_name", "is", "None", ":", "database_name", "=", "self", ".", "_database_name", "if", "database_name",...
43.8125
18.6875
def write_channel(self, out_data): """Generic handler that will write to both SSH and telnet channel. :param out_data: data to be written to the channel :type out_data: str (can be either unicode/byte string) """ self._lock_netmiko_session() try: self._write_...
[ "def", "write_channel", "(", "self", ",", "out_data", ")", ":", "self", ".", "_lock_netmiko_session", "(", ")", "try", ":", "self", ".", "_write_channel", "(", "out_data", ")", "finally", ":", "# Always unlock the SSH channel, even on exception.", "self", ".", "_u...
37.5
14.083333
def create_tarfile(files, project_name): """Create a tar file based on the list of files passed""" fd, filename = tempfile.mkstemp(prefix="polyaxon_{}".format(project_name), suffix='.tar.gz') with tarfile.open(filename, "w:gz") as tar: for f in files: tar.add(f) yield filename ...
[ "def", "create_tarfile", "(", "files", ",", "project_name", ")", ":", "fd", ",", "filename", "=", "tempfile", ".", "mkstemp", "(", "prefix", "=", "\"polyaxon_{}\"", ".", "format", "(", "project_name", ")", ",", "suffix", "=", "'.tar.gz'", ")", "with", "tar...
29.75
22.5
def for_page(self, page, per_page): """ "Paginate" the collection by slicing it into a smaller collection. :param page: The current page :type page: int :param per_page: Number of items by slice :type per_page: int :rtype: Collection """ start =...
[ "def", "for_page", "(", "self", ",", "page", ",", "per_page", ")", ":", "start", "=", "(", "page", "-", "1", ")", "*", "per_page", "return", "self", "[", "start", ":", "start", "+", "per_page", "]" ]
24.866667
17.4
def create_storage_account(self, service_name, description, label, affinity_group=None, location=None, geo_replication_enabled=None, extended_properties=None, account_type='Standard_GRS'): ...
[ "def", "create_storage_account", "(", "self", ",", "service_name", ",", "description", ",", "label", ",", "affinity_group", "=", "None", ",", "location", "=", "None", ",", "geo_replication_enabled", "=", "None", ",", "extended_properties", "=", "None", ",", "acc...
48.21875
20.46875
def exttype(suffix): """Type for use with argument(... type=) that will force a specific suffix Especially for output files, so that we can enforce the use of appropriate file-type specific suffixes""" def inner(s): if s == '': return s first, last = os.path.splitext(s) ...
[ "def", "exttype", "(", "suffix", ")", ":", "def", "inner", "(", "s", ")", ":", "if", "s", "==", "''", ":", "return", "s", "first", ",", "last", "=", "os", ".", "path", ".", "splitext", "(", "s", ")", "return", "first", "+", "suffix", "return", ...
35.2
15.8
def visit_Call(self, node): """Replace function call by its correct iterator if it is possible.""" if node in self.potential_iterator: matched_path = self.find_matching_builtin(node) if matched_path is None: return self.generic_visit(node) # Special h...
[ "def", "visit_Call", "(", "self", ",", "node", ")", ":", "if", "node", "in", "self", ".", "potential_iterator", ":", "matched_path", "=", "self", ".", "find_matching_builtin", "(", "node", ")", "if", "matched_path", "is", "None", ":", "return", "self", "."...
41.035714
16.535714
def emit_event(project_slug, action_slug, payload, sender_name, sender_secret, event_uuid=None): """Emit Event. :param project_slug: the slug of the project :param action_slug: the slug of the action :param payload: the payload that emit with action :param sender_name: name that iden...
[ "def", "emit_event", "(", "project_slug", ",", "action_slug", ",", "payload", ",", "sender_name", ",", "sender_secret", ",", "event_uuid", "=", "None", ")", ":", "project_graph", "=", "graph", ".", "get_project_graph", "(", "project_slug", ")", "project_graph", ...
32.526316
20.815789
def _saveDB(self): """Overloaded - we don't have nextval() in mysql""" # We're a "fresh" copy now self._updated = time.time() if self._new: operation = 'INSERT' else: operation = 'UPDATE' (sql, fields) = self._prepareSQL(operation) values =...
[ "def", "_saveDB", "(", "self", ")", ":", "# We're a \"fresh\" copy now", "self", ".", "_updated", "=", "time", ".", "time", "(", ")", "if", "self", ".", "_new", ":", "operation", "=", "'INSERT'", "else", ":", "operation", "=", "'UPDATE'", "(", "sql", ","...
36.151515
13.939394
def getBirthdate(self, string=True): """ Returns the birthdate as string object Parameters ---------- None Examples -------- >>> import pyedflib >>> f = pyedflib.data.test_generator() >>> f.getBirthdate()=='30 jun 1969' True ...
[ "def", "getBirthdate", "(", "self", ",", "string", "=", "True", ")", ":", "if", "string", ":", "return", "self", ".", "_convert_string", "(", "self", ".", "birthdate", ".", "rstrip", "(", ")", ")", "else", ":", "return", "datetime", ".", "strptime", "(...
23.521739
22.130435
def networkOneMode(self, mode, nodeCount = True, edgeWeight = True, stemmer = None, edgeAttribute = None, nodeAttribute = None): """Creates a network of the objects found by one tag _mode_. This is the same as [networkMultiLevel()](#metaknowledge.CollectionWithIDs.networkMultiLevel) with only one tag. ...
[ "def", "networkOneMode", "(", "self", ",", "mode", ",", "nodeCount", "=", "True", ",", "edgeWeight", "=", "True", ",", "stemmer", "=", "None", ",", "edgeAttribute", "=", "None", ",", "nodeAttribute", "=", "None", ")", ":", "return", "self", ".", "network...
66.222222
63.166667
def left_to_right(self): """This is for text that flows Left to Right""" self._entry_mode |= Command.MODE_INCREMENT self.command(self._entry_mode)
[ "def", "left_to_right", "(", "self", ")", ":", "self", ".", "_entry_mode", "|=", "Command", ".", "MODE_INCREMENT", "self", ".", "command", "(", "self", ".", "_entry_mode", ")" ]
41.75
7
def copyidfintoidf(toidf, fromidf): """copy fromidf completely into toidf""" idfobjlst = getidfobjectlist(fromidf) for idfobj in idfobjlst: toidf.copyidfobject(idfobj)
[ "def", "copyidfintoidf", "(", "toidf", ",", "fromidf", ")", ":", "idfobjlst", "=", "getidfobjectlist", "(", "fromidf", ")", "for", "idfobj", "in", "idfobjlst", ":", "toidf", ".", "copyidfobject", "(", "idfobj", ")" ]
36.6
4.6
def rbdd(*keywords): """ Run story matching keywords and rewrite story if code changed. """ settings = _personal_settings().data settings["engine"]["rewrite"] = True _storybook(settings["engine"]).with_params( **{"python version": settings["params"]["python version"]} ).only_uninheri...
[ "def", "rbdd", "(", "*", "keywords", ")", ":", "settings", "=", "_personal_settings", "(", ")", ".", "data", "settings", "[", "\"engine\"", "]", "[", "\"rewrite\"", "]", "=", "True", "_storybook", "(", "settings", "[", "\"engine\"", "]", ")", ".", "with_...
38.222222
10
def add_request_session(self): """Add a request session for current thread.""" session = new_request_session(self.config, self.cookies) self.request_sessions[thread.get_ident()] = session
[ "def", "add_request_session", "(", "self", ")", ":", "session", "=", "new_request_session", "(", "self", ".", "config", ",", "self", ".", "cookies", ")", "self", ".", "request_sessions", "[", "thread", ".", "get_ident", "(", ")", "]", "=", "session" ]
52
13.25
def minimize_one_step(gradient_unregularized_loss, hessian_unregularized_loss_outer, hessian_unregularized_loss_middle, x_start, tolerance, l1_regularizer, l2_regularizer=None, ...
[ "def", "minimize_one_step", "(", "gradient_unregularized_loss", ",", "hessian_unregularized_loss_outer", ",", "hessian_unregularized_loss_middle", ",", "x_start", ",", "tolerance", ",", "l1_regularizer", ",", "l2_regularizer", "=", "None", ",", "maximum_full_sweeps", "=", "...
46.025714
24.08
def _build_request(self, path, params=None): """Build API request""" _url = '{scheme}://{host}{port}/{version}{path}'.format( scheme=self._scheme, host=self._host, port=':{}'.format(self._port) if self._port != 80 else '', version=self._api_version, ...
[ "def", "_build_request", "(", "self", ",", "path", ",", "params", "=", "None", ")", ":", "_url", "=", "'{scheme}://{host}{port}/{version}{path}'", ".", "format", "(", "scheme", "=", "self", ".", "_scheme", ",", "host", "=", "self", ".", "_host", ",", "port...
36.470588
17.5
def plot_full(candsfile, cands, mode='im'): """ Plot 'full' features, such as cutout image and spectrum. """ loc, prop, d = read_candidates(candsfile, returnstate=True) npixx, npixy = prop[0][4].shape nints, nchan, npol = prop[0][5].shape bin = 10 plt.figure(1) for i in cands: ...
[ "def", "plot_full", "(", "candsfile", ",", "cands", ",", "mode", "=", "'im'", ")", ":", "loc", ",", "prop", ",", "d", "=", "read_candidates", "(", "candsfile", ",", "returnstate", "=", "True", ")", "npixx", ",", "npixy", "=", "prop", "[", "0", "]", ...
40.047619
23.047619
def _fromiter(it, dtype, count, progress, log): """Utility function to load an array from an iterator.""" if progress > 0: it = _iter_withprogress(it, progress, log) if count is not None: a = np.fromiter(it, dtype=dtype, count=count) else: a = np.fromiter(it, dtype=dtype) ret...
[ "def", "_fromiter", "(", "it", ",", "dtype", ",", "count", ",", "progress", ",", "log", ")", ":", "if", "progress", ">", "0", ":", "it", "=", "_iter_withprogress", "(", "it", ",", "progress", ",", "log", ")", "if", "count", "is", "not", "None", ":"...
35.222222
13.777778
def get_feats(self, doc): ''' Parameters ---------- doc, Spacy Doc Returns ------- Counter noun chunk -> count ''' # ngram_counter = phrasemachine.get_phrases(str(doc), tagger='spacy')['counts'] ngram_counter = Counter() for sent in doc.sents: unigrams = self._get_unigram_feats(sent) ngram_...
[ "def", "get_feats", "(", "self", ",", "doc", ")", ":", "# ngram_counter = phrasemachine.get_phrases(str(doc), tagger='spacy')['counts']", "ngram_counter", "=", "Counter", "(", ")", "for", "sent", "in", "doc", ".", "sents", ":", "unigrams", "=", "self", ".", "_get_un...
23.6875
24.3125
def contrast(self, value): """ Sets the LED intensity to the desired level, in the range 0-255. :param level: Desired contrast level in the range of 0-255. :type level: int """ assert(0x00 <= value <= 0xFF) self._brightness = value >> 4 if self._last_imag...
[ "def", "contrast", "(", "self", ",", "value", ")", ":", "assert", "(", "0x00", "<=", "value", "<=", "0xFF", ")", "self", ".", "_brightness", "=", "value", ">>", "4", "if", "self", ".", "_last_image", "is", "not", "None", ":", "self", ".", "display", ...
33.363636
12.454545
def Suzuki_LFL(Hc=None): r'''Calculates lower flammability limit, using the Suzuki [1]_ correlation. Uses heat of combustion only. The lower flammability limit of a gas is air is: .. math:: \text{LFL} = \frac{-3.42}{\Delta H_c^{\circ}} + 0.569 \Delta H_c^{\circ} + 0.0538\Delta H_c^{\ci...
[ "def", "Suzuki_LFL", "(", "Hc", "=", "None", ")", ":", "Hc", "=", "Hc", "/", "1E6", "LFL", "=", "-", "3.42", "/", "Hc", "+", "0.569", "*", "Hc", "+", "0.0538", "*", "Hc", "*", "Hc", "+", "1.80", "return", "LFL", "/", "100." ]
30.34
25.58
def predict(self, a, b, **kwargs): """Perform the independence test. :param a: input data :param b: input data :type a: array-like, numerical data :type b: array-like, numerical data :return: dependency statistic (1=Highly dependent, 0=Not dependent) :rtype: floa...
[ "def", "predict", "(", "self", ",", "a", ",", "b", ",", "*", "*", "kwargs", ")", ":", "binning_alg", "=", "kwargs", ".", "get", "(", "'bins'", ",", "'fd'", ")", "return", "metrics", ".", "adjusted_mutual_info_score", "(", "bin_variable", "(", "a", ",",...
41.384615
17.230769
def transform_dataframe(self, dataframe): """ Unstack the dataframe so header consists of a composite 'value' header plus any other header fields. """ coord_fields = self.get_coord_fields() header_fields = self.get_header_fields() # Remove any pairs that don't ha...
[ "def", "transform_dataframe", "(", "self", ",", "dataframe", ")", ":", "coord_fields", "=", "self", ".", "get_coord_fields", "(", ")", "header_fields", "=", "self", ".", "get_header_fields", "(", ")", "# Remove any pairs that don't have data for both x & y", "for", "i...
35.525
13.975
def geo_description(self): """Return a description of the geographic extents, using the largest scale space and grain coverages""" sc = self._p.space_coverage gc = self._p.grain_coverage if sc and gc: if parse_to_gvid(gc[0]).level == 'state' and parse_to_gvid(sc[0])...
[ "def", "geo_description", "(", "self", ")", ":", "sc", "=", "self", ".", "_p", ".", "space_coverage", "gc", "=", "self", ".", "_p", ".", "grain_coverage", "if", "sc", "and", "gc", ":", "if", "parse_to_gvid", "(", "gc", "[", "0", "]", ")", ".", "lev...
36.8
18.9
def sample(self, n_samples=1, random_state=None): """Generate random samples from the model. Parameters ---------- n_samples : int, optional Number of samples to generate. Defaults to 1. Returns ------- X : array_like, shape (n_samples, n_features) ...
[ "def", "sample", "(", "self", ",", "n_samples", "=", "1", ",", "random_state", "=", "None", ")", ":", "check_is_fitted", "(", "self", ",", "'means_'", ")", "if", "random_state", "is", "None", ":", "random_state", "=", "self", ".", "random_state", "random_s...
36.878049
13.780488
def at_time(self, time, asof=False, axis=None): """ Select values at particular time of day (e.g. 9:30AM). Parameters ---------- time : datetime.time or str axis : {0 or 'index', 1 or 'columns'}, default 0 .. versionadded:: 0.24.0 Returns --...
[ "def", "at_time", "(", "self", ",", "time", ",", "asof", "=", "False", ",", "axis", "=", "None", ")", ":", "if", "axis", "is", "None", ":", "axis", "=", "self", ".", "_stat_axis_number", "axis", "=", "self", ".", "_get_axis_number", "(", "axis", ")",...
29.454545
20.327273
def __parse_stream(self, stream, parse_line): """Generic method to parse gitdm streams""" if not stream: raise InvalidFormatError(cause='stream cannot be empty or None') nline = 0 lines = stream.split('\n') for line in lines: nline += 1 # I...
[ "def", "__parse_stream", "(", "self", ",", "stream", ",", "parse_line", ")", ":", "if", "not", "stream", ":", "raise", "InvalidFormatError", "(", "cause", "=", "'stream cannot be empty or None'", ")", "nline", "=", "0", "lines", "=", "stream", ".", "split", ...
32.285714
21.392857
def get_current_status(self): """Returns the current state of the local spotify client""" url = get_url("/remote/status.json") params = {"oauth": self._oauth_token, "csrf": self._csrf_token} r = self._request(url=url, params=params) return r.json()
[ "def", "get_current_status", "(", "self", ")", ":", "url", "=", "get_url", "(", "\"/remote/status.json\"", ")", "params", "=", "{", "\"oauth\"", ":", "self", ".", "_oauth_token", ",", "\"csrf\"", ":", "self", ".", "_csrf_token", "}", "r", "=", "self", ".",...
47.166667
12
def _evaluate(self,R,phi=0.,t=0.): """ NAME: _evaluate PURPOSE: evaluate the potential INPUT: R phi t OUTPUT: Pot(R(,\phi,t)) HISTORY: 2010-07-13 - Written - Bovy (NYU) """ return ...
[ "def", "_evaluate", "(", "self", ",", "R", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "return", "self", ".", "_Pot", "(", "R", ",", "0.", ",", "t", "=", "t", ",", "use_physical", "=", "False", ")" ]
21.4375
17.0625
def _wave(self): """Return a wave.Wave_read instance from the ``wave`` module.""" try: return wave.open(StringIO(self.contents)) except wave.Error, err: err.message += "\nInvalid wave file: %s" % self err.args = (err.message,) raise
[ "def", "_wave", "(", "self", ")", ":", "try", ":", "return", "wave", ".", "open", "(", "StringIO", "(", "self", ".", "contents", ")", ")", "except", "wave", ".", "Error", ",", "err", ":", "err", ".", "message", "+=", "\"\\nInvalid wave file: %s\"", "%"...
37.125
14.875
def SInt64(value, min_value=None, max_value=None, encoder=ENC_INT_DEFAULT, fuzzable=True, name=None, full_range=False): '''Signed 64-bit field''' return BitField(value, 64, signed=True, min_value=min_value, max_value=max_value, encoder=encoder, fuzzable=fuzzable, name=name, full_range=full_range)
[ "def", "SInt64", "(", "value", ",", "min_value", "=", "None", ",", "max_value", "=", "None", ",", "encoder", "=", "ENC_INT_DEFAULT", ",", "fuzzable", "=", "True", ",", "name", "=", "None", ",", "full_range", "=", "False", ")", ":", "return", "BitField", ...
101
68.333333
def get_uid(path, follow_symlinks=True): ''' Return the id of the user that owns a given file Symlinks are followed by default to mimic Unix behavior. Specify `follow_symlinks=False` to turn off this behavior. Args: path (str): The path to the file or directory follow_symlinks (bo...
[ "def", "get_uid", "(", "path", ",", "follow_symlinks", "=", "True", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "CommandExecutionError", "(", "'Path not found: {0}'", ".", "format", "(", "path", ")", ")", "# U...
35.026316
26.184211
def present( name, subscriptions=None, region=None, key=None, keyid=None, profile=None): ''' Ensure the SNS topic exists. name Name of the SNS topic. subscriptions List of SNS subscriptions. Each subscription is a dictionary with...
[ "def", "present", "(", "name", ",", "subscriptions", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", ...
33.311594
21.76087
def create(self, id, seq, resource): # pylint: disable=invalid-name,redefined-builtin """Create a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param resource: :class:`highlights.Highlight <highlights.Highlight>` object :return: :class...
[ "def", "create", "(", "self", ",", "id", ",", "seq", ",", "resource", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "return", "self", ".", "create_or_edit", "(", "id", ",", "seq", ",", "resource", ")" ]
46.7
19.6
def _grid_distance(self, index): """ Calculate the distance grid for a single index position. This is pre-calculated for fast neighborhood calculations later on (see _calc_influence). """ # Take every dimension but the first in reverse # then reverse that list ag...
[ "def", "_grid_distance", "(", "self", ",", "index", ")", ":", "# Take every dimension but the first in reverse", "# then reverse that list again.", "dimensions", "=", "np", ".", "cumprod", "(", "self", ".", "map_dimensions", "[", "1", ":", ":", "]", "[", ":", ":",...
32.30303
17.030303
async def start_timeout(self): """Start timeout.""" self.timeout_handle = self.pyvlx.connection.loop.call_later( self.timeout_in_seconds, self.timeout)
[ "async", "def", "start_timeout", "(", "self", ")", ":", "self", ".", "timeout_handle", "=", "self", ".", "pyvlx", ".", "connection", ".", "loop", ".", "call_later", "(", "self", ".", "timeout_in_seconds", ",", "self", ".", "timeout", ")" ]
44
12
def prepend(exception, message, end=': '): """Prepends the first argument (i.e., the exception message) of the a BaseException with the provided message. Useful for reraising exceptions with additional information. :param BaseException exception: the exception to prepend :param str message: the message...
[ "def", "prepend", "(", "exception", ",", "message", ",", "end", "=", "': '", ")", ":", "exception", ".", "args", "=", "exception", ".", "args", "or", "(", "''", ",", ")", "exception", ".", "args", "=", "(", "message", "+", "end", "+", "exception", ...
48.166667
16.916667
def get_octahedra(self, atoms, periodicity=3): ''' Extract octahedra as lists of sequence numbers of corner atoms ''' octahedra = [] for n, i in enumerate(atoms): found = [] if i.symbol in Perovskite_Structure.B: for m, j in enumerate(self....
[ "def", "get_octahedra", "(", "self", ",", "atoms", ",", "periodicity", "=", "3", ")", ":", "octahedra", "=", "[", "]", "for", "n", ",", "i", "in", "enumerate", "(", "atoms", ")", ":", "found", "=", "[", "]", "if", "i", ".", "symbol", "in", "Perov...
46.235294
29.058824
def backend_from_fobj(f): """Determine backend module object from a file object.""" if magic is None: warn("magic lib is not installed; assuming mime type %r" % ( DEFAULT_MIME)) return backend_from_mime(DEFAULT_MIME) else: offset = f.tell() try: f.seek...
[ "def", "backend_from_fobj", "(", "f", ")", ":", "if", "magic", "is", "None", ":", "warn", "(", "\"magic lib is not installed; assuming mime type %r\"", "%", "(", "DEFAULT_MIME", ")", ")", "return", "backend_from_mime", "(", "DEFAULT_MIME", ")", "else", ":", "offse...
33.133333
15.6