text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def clone_exception(error, args): """ return a new cloned error when do: ``` try: do_sth() except BaseException as e: handle(e) def handle(error): # do sth with error raise e # <- won't work! This can ge...
[ "def", "clone_exception", "(", "error", ",", "args", ")", ":", "new_error", "=", "error", ".", "__class__", "(", "*", "args", ")", "new_error", ".", "__dict__", "=", "error", ".", "__dict__", "return", "new_error" ]
21.666667
18.933333
def create_password(self, data): """Create a password.""" # http://teampasswordmanager.com/docs/api-passwords/#create_password log.info('Create new password %s' % data) NewID = self.post('passwords.json', data).get('id') log.info('Password has been created with ID %s' % NewID) ...
[ "def", "create_password", "(", "self", ",", "data", ")", ":", "# http://teampasswordmanager.com/docs/api-passwords/#create_password", "log", ".", "info", "(", "'Create new password %s'", "%", "data", ")", "NewID", "=", "self", ".", "post", "(", "'passwords.json'", ","...
47.428571
16.571429
def watch(self, path, action, *args, **kwargs): """ Called by the Server instance when a new watch task is requested. """ if action is None: action = _set_changed event_handler = _WatchdogHandler(self, action) self._observer.schedule(event_handler, path=path, ...
[ "def", "watch", "(", "self", ",", "path", ",", "action", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "action", "is", "None", ":", "action", "=", "_set_changed", "event_handler", "=", "_WatchdogHandler", "(", "self", ",", "action", ")", ...
41
13.5
def deprecated(comment=None, replacement=None): """Flags a function as deprecated. A warning will be emitted. :param comment: A human-friendly string, such as 'This function will be removed soon' :type comment: string :param replacement: The function to be used instead :type re...
[ "def", "deprecated", "(", "comment", "=", "None", ",", "replacement", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "message", "=", "\"Call to deprecated function ...
42.464286
14.178571
def check(self, check_all=True, do_reload=True): """Check whether some modules need to be reloaded.""" with enaml.imports(): super(EnamlReloader, self).check(check_all=check_all, do_reload=do_reload)
[ "def", "check", "(", "self", ",", "check_all", "=", "True", ",", "do_reload", "=", "True", ")", ":", "with", "enaml", ".", "imports", "(", ")", ":", "super", "(", "EnamlReloader", ",", "self", ")", ".", "check", "(", "check_all", "=", "check_all", ",...
56
16.25
def set_yaxis(self, param, unit=None, label=None): """ Sets the value of use on the yaxis :param param: value to use on the yaxis, should be a variable or function of the objects in objectList. ie 'R' for the radius variable and 'calcDensity()' for the calcDensity function :param unit: ...
[ "def", "set_yaxis", "(", "self", ",", "param", ",", "unit", "=", "None", ",", "label", "=", "None", ")", ":", "if", "unit", "is", "None", ":", "unit", "=", "self", ".", "_getParLabelAndUnit", "(", "param", ")", "[", "1", "]", "# use the default unit de...
42.2
24.55
def _add_supplemental_bams(data): """Add supplemental files produced by alignment, useful for structural variant calling. """ file_key = "work_bam" if data.get(file_key): for supext in ["disc", "sr"]: base, ext = os.path.splitext(data[file_key]) test_file = "%s-%s%s" ...
[ "def", "_add_supplemental_bams", "(", "data", ")", ":", "file_key", "=", "\"work_bam\"", "if", "data", ".", "get", "(", "file_key", ")", ":", "for", "supext", "in", "[", "\"disc\"", ",", "\"sr\"", "]", ":", "base", ",", "ext", "=", "os", ".", "path", ...
37.266667
8.8
def from_class(metacls, cls, auto_store=True): """Create proper PySchema class from cls Any methods and attributes will be transferred to the new object """ if auto_store: def wrap(cls): return cls else: wrap = no_auto_store() ...
[ "def", "from_class", "(", "metacls", ",", "cls", ",", "auto_store", "=", "True", ")", ":", "if", "auto_store", ":", "def", "wrap", "(", "cls", ")", ":", "return", "cls", "else", ":", "wrap", "=", "no_auto_store", "(", ")", "return", "wrap", "(", "met...
24.888889
16.944444
def from_id_gaussian_draw(cls,pst,num_reals): """ this is an experiemental method to help speed up independent draws for a really large (>1E6) ensemble sizes. Parameters ---------- pst : pyemu.Pst a control file instance num_reals : int number of ...
[ "def", "from_id_gaussian_draw", "(", "cls", ",", "pst", ",", "num_reals", ")", ":", "# set up some column names", "real_names", "=", "np", ".", "arange", "(", "num_reals", ",", "dtype", "=", "np", ".", "int64", ")", "#arr = np.empty((num_reals,len(pst.obs_names)))",...
35.65625
15.6875
def has_succeed(self): """ Check if the connection has succeed Returns: Returns True if connection has succeed. False otherwise. """ status_code = self._response.status_code if status_code in [HTTP_CODE_ZERO, HTTP_CODE_SUCCESS, HTTP_CODE_CRE...
[ "def", "has_succeed", "(", "self", ")", ":", "status_code", "=", "self", ".", "_response", ".", "status_code", "if", "status_code", "in", "[", "HTTP_CODE_ZERO", ",", "HTTP_CODE_SUCCESS", ",", "HTTP_CODE_CREATED", ",", "HTTP_CODE_EMPTY", ",", "HTTP_CODE_MULTIPLE_CHOI...
45.294118
39.411765
def _add_to_checksum(self, checksum, value): """Add a byte to the checksum.""" checksum = self._byte_rot_left(checksum, 1) checksum = checksum + value if (checksum > 255): checksum = checksum - 255 self._debug(PROP_LOGLEVEL_TRACE, "C: " + str(checksum) + " V: " + str(...
[ "def", "_add_to_checksum", "(", "self", ",", "checksum", ",", "value", ")", ":", "checksum", "=", "self", ".", "_byte_rot_left", "(", "checksum", ",", "1", ")", "checksum", "=", "checksum", "+", "value", "if", "(", "checksum", ">", "255", ")", ":", "ch...
43
12.125
def change_columns(self, model, **fields): """Change fields.""" for name, field in fields.items(): old_field = model._meta.fields.get(name, field) old_column_name = old_field and old_field.column_name model._meta.add_field(name, field) if isinstance(old_...
[ "def", "change_columns", "(", "self", ",", "model", ",", "*", "*", "fields", ")", ":", "for", "name", ",", "field", "in", "fields", ".", "items", "(", ")", ":", "old_field", "=", "model", ".", "_meta", ".", "fields", ".", "get", "(", "name", ",", ...
43.547619
23.595238
def add_class(self, cls, include_bases=True): """Add the specified class (which should be a class object, _not_ a string). By default all base classes for which is_backup_class returns True will also be added. `include_bases=False` may be spcified to suppress this behavior. The total num...
[ "def", "add_class", "(", "self", ",", "cls", ",", "include_bases", "=", "True", ")", ":", "if", "not", "is_backup_class", "(", "cls", ")", ":", "return", "0", "added", "=", "0", "cls_name", "=", "backup_name", "(", "cls", ")", "if", "cls_name", "not", ...
42.692308
21.230769
def find_by_id(self, team, params={}, **options): """Returns the full record for a single team. Parameters ---------- team : {Id} Globally unique identifier for the team. [params] : {Object} Parameters for the request """ path = "/teams/%s" % (team) retu...
[ "def", "find_by_id", "(", "self", ",", "team", ",", "params", "=", "{", "}", ",", "*", "*", "options", ")", ":", "path", "=", "\"/teams/%s\"", "%", "(", "team", ")", "return", "self", ".", "client", ".", "get", "(", "path", ",", "params", ",", "*...
35.4
14.8
def produce_upgrade_operations( ctx=None, metadata=None, include_symbol=None, include_object=None, **kwargs): """Produce a list of upgrade statements.""" if metadata is None: # Note, all SQLAlchemy models must have been loaded to produce # accurate results. metadata = db....
[ "def", "produce_upgrade_operations", "(", "ctx", "=", "None", ",", "metadata", "=", "None", ",", "include_symbol", "=", "None", ",", "include_object", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "metadata", "is", "None", ":", "# Note, all SQLAlchem...
28.954545
19.909091
def get_subgraph(graph, seed_method: Optional[str] = None, seed_data: Optional[Any] = None, expand_nodes: Optional[List[BaseEntity]] = None, remove_nodes: Optional[List[BaseEntity]] = None, ): """Run a pipeline query on graph with ...
[ "def", "get_subgraph", "(", "graph", ",", "seed_method", ":", "Optional", "[", "str", "]", "=", "None", ",", "seed_data", ":", "Optional", "[", "Any", "]", "=", "None", ",", "expand_nodes", ":", "Optional", "[", "List", "[", "BaseEntity", "]", "]", "="...
35.934783
23.782609
def reset(name, soft=False, call=None): ''' To reset a VM using its name .. note:: If ``soft=True`` then issues a command to the guest operating system asking it to perform a reboot. Otherwise hypervisor will terminate VM and start it again. Default is soft=False For ``sof...
[ "def", "reset", "(", "name", ",", "soft", "=", "False", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The reset action must be called with '", "'-a or --action.'", ")", "vm_properties", "=", "[", ...
31.927273
23.927273
def json_rpc_format(self): """Return the Exception data in a format for JSON-RPC """ error = { 'name': text_type(self.__class__.__name__), 'code': self.code, 'message': '{0}'.format(text_type(self.message)), 'data': self.data } if...
[ "def", "json_rpc_format", "(", "self", ")", ":", "error", "=", "{", "'name'", ":", "text_type", "(", "self", ".", "__class__", ".", "__name__", ")", ",", "'code'", ":", "self", ".", "code", ",", "'message'", ":", "'{0}'", ".", "format", "(", "text_type...
28.823529
17.176471
def commdct2grouplist(gcommdct): """extract embedded group data from commdct. return gdict -> {g1:[obj1, obj2, obj3], g2:[obj4, ..]}""" gdict = {} for objidd in gcommdct: group = objidd[0]['group'] objname = objidd[0]['idfobj'] if group in gdict: gdict[group].append(o...
[ "def", "commdct2grouplist", "(", "gcommdct", ")", ":", "gdict", "=", "{", "}", "for", "objidd", "in", "gcommdct", ":", "group", "=", "objidd", "[", "0", "]", "[", "'group'", "]", "objname", "=", "objidd", "[", "0", "]", "[", "'idfobj'", "]", "if", ...
32.166667
10.25
def set_image(self): """Parses image element and set values""" temp_soup = self.full_soup for item in temp_soup.findAll('item'): item.decompose() image = temp_soup.find('image') try: self.image_title = image.find('title').string except AttributeErr...
[ "def", "set_image", "(", "self", ")", ":", "temp_soup", "=", "self", ".", "full_soup", "for", "item", "in", "temp_soup", ".", "findAll", "(", "'item'", ")", ":", "item", ".", "decompose", "(", ")", "image", "=", "temp_soup", ".", "find", "(", "'image'"...
33.846154
13.192308
def new(template, target=None, name=None): """ Function for creating a template script or tool. :param template: template to be used ; one of TEMPLATES :param target: type of script/tool to be created :param name: name of the new script/tool """ if template not in TEMPLATES: ...
[ "def", "new", "(", "template", ",", "target", "=", "None", ",", "name", "=", "None", ")", ":", "if", "template", "not", "in", "TEMPLATES", ":", "raise", "ValueError", "(", "\"Template argument must be one of the followings: {}\"", ".", "format", "(", "\", \"", ...
49.192308
17.423077
def _last_of_quarter(self, day_of_week=None): """ Modify to the last occurrence of a given day of the week in the current quarter. If no day_of_week is provided, modify to the last day of the quarter. Use the supplied consts to indicate the desired day_of_week, ex. pendulum.MONDA...
[ "def", "_last_of_quarter", "(", "self", ",", "day_of_week", "=", "None", ")", ":", "return", "self", ".", "set", "(", "self", ".", "year", ",", "self", ".", "quarter", "*", "3", ",", "1", ")", ".", "last_of", "(", "\"month\"", ",", "day_of_week", ")"...
39.25
21.083333
def as_template(value): """Convert a simple "shorthand" Python value to a `Template`. """ if isinstance(value, Template): # If it's already a Template, pass it through. return value elif isinstance(value, abc.Mapping): # Dictionaries work as templates. return MappingTempl...
[ "def", "as_template", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Template", ")", ":", "# If it's already a Template, pass it through.", "return", "value", "elif", "isinstance", "(", "value", ",", "abc", ".", "Mapping", ")", ":", "# Dictionar...
34.243243
11.594595
def get_subnet(context, id, fields=None): """Retrieve a subnet. : param context: neutron api request context : param id: UUID representing the subnet to fetch. : param fields: a list of strings that are valid keys in a subnet dictionary as listed in the RESOURCE_ATTRIBUTE_MAP object in ...
[ "def", "get_subnet", "(", "context", ",", "id", ",", "fields", "=", "None", ")", ":", "LOG", ".", "info", "(", "\"get_subnet %s for tenant %s with fields %s\"", "%", "(", "id", ",", "context", ".", "tenant_id", ",", "fields", ")", ")", "subnet", "=", "db_a...
43.64
16.92
def get_instance(self, payload): """ Build an instance of MachineToMachineInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineInstance :rtype: twilio.rest.api.v2010.account...
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "MachineToMachineInstance", "(", "self", ".", "_version", ",", "payload", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", "country_code", "=", "self", ...
39.733333
24
def clouds(opts): ''' Return the cloud functions ''' # Let's bring __active_provider_name__, defaulting to None, to all cloud # drivers. This will get temporarily updated/overridden with a context # manager when needed. functions = LazyLoader( _module_dirs(opts, ...
[ "def", "clouds", "(", "opts", ")", ":", "# Let's bring __active_provider_name__, defaulting to None, to all cloud", "# drivers. This will get temporarily updated/overridden with a context", "# manager when needed.", "functions", "=", "LazyLoader", "(", "_module_dirs", "(", "opts", ",...
34.36
19.8
def decode(obj, content_type): # type: (np.array or Iterable or int or float, str) -> np.array """Decode an object ton a one of the default content types to a numpy array. Args: obj (object): to be decoded. content_type (str): content type to be used. Returns: np.array: decoded...
[ "def", "decode", "(", "obj", ",", "content_type", ")", ":", "# type: (np.array or Iterable or int or float, str) -> np.array", "try", ":", "decoder", "=", "_decoders_map", "[", "content_type", "]", "return", "decoder", "(", "obj", ")", "except", "KeyError", ":", "ra...
30.25
17.9375
def resolve_config(self): '''Resolve configuration params to native instances''' conf = self.load_config(self.force_default) for k in conf['hues']: conf['hues'][k] = getattr(KEYWORDS, conf['hues'][k]) as_tuples = lambda name, obj: namedtuple(name, obj.keys())(**obj) self.hues = as_tuples('Hue...
[ "def", "resolve_config", "(", "self", ")", ":", "conf", "=", "self", ".", "load_config", "(", "self", ".", "force_default", ")", "for", "k", "in", "conf", "[", "'hues'", "]", ":", "conf", "[", "'hues'", "]", "[", "k", "]", "=", "getattr", "(", "KEY...
43.6
17.4
def load_import_keychain( cls, working_dir, namespace_id ): """ Get an import keychain from disk. Return None if it doesn't exist. """ # do we have a cached one on disk? cached_keychain = os.path.join(working_dir, "%s.keychain" % namespace_id) if os.path.ex...
[ "def", "load_import_keychain", "(", "cls", ",", "working_dir", ",", "namespace_id", ")", ":", "# do we have a cached one on disk?", "cached_keychain", "=", "os", ".", "path", ".", "join", "(", "working_dir", ",", "\"%s.keychain\"", "%", "namespace_id", ")", "if", ...
32.806452
20.741935
def parent(self): """ Return the parent device. """ if self._has_parent is None: _parent = self._ctx.backend.get_parent(self._ctx.dev) self._has_parent = _parent is not None if self._has_parent: self._parent = Device(_parent, self._ctx.backend) ...
[ "def", "parent", "(", "self", ")", ":", "if", "self", ".", "_has_parent", "is", "None", ":", "_parent", "=", "self", ".", "_ctx", ".", "backend", ".", "get_parent", "(", "self", ".", "_ctx", ".", "dev", ")", "self", ".", "_has_parent", "=", "_parent"...
38.5
13.6
def fwhm(x, y, k=10): # http://stackoverflow.com/questions/10582795/finding-the-full-width-half-maximum-of-a-peak """ Determine full-with-half-maximum of a peaked set of points, x and y. Assumes that there is only one peak present in the datasset. The function uses a spline interpolation of order k. ...
[ "def", "fwhm", "(", "x", ",", "y", ",", "k", "=", "10", ")", ":", "# http://stackoverflow.com/questions/10582795/finding-the-full-width-half-maximum-of-a-peak", "class", "MultiplePeaks", "(", "Exception", ")", ":", "pass", "class", "NoPeaksFound", "(", "Exception", ")...
33.653846
25.115385
def build_attrs(self, *args, **kwargs): """Add select2 data attributes.""" attrs = super(Select2Mixin, self).build_attrs(*args, **kwargs) if self.is_required: attrs.setdefault('data-allow-clear', 'false') else: attrs.setdefault('data-allow-clear', 'true') ...
[ "def", "build_attrs", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "attrs", "=", "super", "(", "Select2Mixin", ",", "self", ")", ".", "build_attrs", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "self", ".", "is_require...
37.733333
16.133333
def update(self): """Update |KD1| based on |EQD1| and |TInd|. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> eqd1(0.5) >>> tind.value = 10.0 >>> derived.kd1.update() >>> derived.kd1 kd1(5.0) """ con = self.subpars.pars.co...
[ "def", "update", "(", "self", ")", ":", "con", "=", "self", ".", "subpars", ".", "pars", ".", "control", "self", "(", "con", ".", "eqd1", "*", "con", ".", "tind", ")" ]
26.538462
12.692308
def fuzzy(cls, field, value, boost=None, min_similarity=None, prefix_length=None): ''' http://www.elasticsearch.org/guide/reference/query-dsl/fuzzy-query.html A fuzzy based query that uses similarity based on Levenshtein (edit distance) algorithm. ''' instance = cls(fuzzy={field:...
[ "def", "fuzzy", "(", "cls", ",", "field", ",", "value", ",", "boost", "=", "None", ",", "min_similarity", "=", "None", ",", "prefix_length", "=", "None", ")", ":", "instance", "=", "cls", "(", "fuzzy", "=", "{", "field", ":", "{", "'value'", ":", "...
50.307692
24.307692
def variants(vcf_fn, region=None, fields=None, exclude_fields=None, dtypes=None, arities=None, fills=None, transformers=None, vcf_types=None, count=None, progress=0, logstream=None, condition=None, slice_args=None, flatten_filter=False, verbose=True, cache=False, cach...
[ "def", "variants", "(", "vcf_fn", ",", "region", "=", "None", ",", "fields", "=", "None", ",", "exclude_fields", "=", "None", ",", "dtypes", "=", "None", ",", "arities", "=", "None", ",", "fills", "=", "None", ",", "transformers", "=", "None", ",", "...
54.990476
28.685714
def build_statusbar(self): """construct and return statusbar widget""" info = {} cb = self.current_buffer btype = None if cb is not None: info = cb.get_info() btype = cb.modename info['buffer_no'] = self.buffers.index(cb) info['buf...
[ "def", "build_statusbar", "(", "self", ")", ":", "info", "=", "{", "}", "cb", "=", "self", ".", "current_buffer", "btype", "=", "None", "if", "cb", "is", "not", "None", ":", "info", "=", "cb", ".", "get_info", "(", ")", "btype", "=", "cb", ".", "...
39.545455
16.060606
def _display_layers(circ: Circuit, qubits: Qubits) -> Circuit: """Separate a circuit into groups of gates that do not visually overlap""" N = len(qubits) qubit_idx = dict(zip(qubits, range(N))) gate_layers = DAGCircuit(circ).layers() layers = [] lcirc = Circuit() layers.append(lcirc) un...
[ "def", "_display_layers", "(", "circ", ":", "Circuit", ",", "qubits", ":", "Qubits", ")", "->", "Circuit", ":", "N", "=", "len", "(", "qubits", ")", "qubit_idx", "=", "dict", "(", "zip", "(", "qubits", ",", "range", "(", "N", ")", ")", ")", "gate_l...
30.518519
17.925926
def lines_without_stdlib(self): """Filters code from standard library from self.lines.""" prev_line = None current_module_path = inspect.getabsfile(inspect.currentframe()) for module_path, lineno, runtime in self.lines: module_abspath = os.path.abspath(module_path) ...
[ "def", "lines_without_stdlib", "(", "self", ")", ":", "prev_line", "=", "None", "current_module_path", "=", "inspect", ".", "getabsfile", "(", "inspect", ".", "currentframe", "(", ")", ")", "for", "module_path", ",", "lineno", ",", "runtime", "in", "self", "...
45
15.9375
def fill(self, name_or_slot, value): """Fills an output slot required by this Pipeline. Args: name_or_slot: The name of the slot (a string) or Slot record to fill. value: The serializable value to assign to this slot. Raises: UnexpectedPipelineError if the Slot no longer exists. SlotNotD...
[ "def", "fill", "(", "self", ",", "name_or_slot", ",", "value", ")", ":", "if", "isinstance", "(", "name_or_slot", ",", "basestring", ")", ":", "slot", "=", "getattr", "(", "self", ".", "outputs", ",", "name_or_slot", ")", "elif", "isinstance", "(", "name...
36.4
20.92
def transitively_reduce(self): """ Performs a transitive reduction on the graph. """ removals = set() for from_node, neighbors in self._edges.items(): childpairs = \ [(c1, c2) for c1 in neighbors for c2 in neighbors if c1 != c2] for child...
[ "def", "transitively_reduce", "(", "self", ")", ":", "removals", "=", "set", "(", ")", "for", "from_node", ",", "neighbors", "in", "self", ".", "_edges", ".", "items", "(", ")", ":", "childpairs", "=", "[", "(", "c1", ",", "c2", ")", "for", "c1", "...
33.647059
17.176471
def load_plugins(self, plugins): """ Loads plugins that match the `Plugin` interface and are instantiated. :param plugins: A list of plugin instances. """ def instantiate(plugin): return plugin() if inspect.isclass(plugin) else plugin loaded_plugins = [] ...
[ "def", "load_plugins", "(", "self", ",", "plugins", ")", ":", "def", "instantiate", "(", "plugin", ")", ":", "return", "plugin", "(", ")", "if", "inspect", ".", "isclass", "(", "plugin", ")", "else", "plugin", "loaded_plugins", "=", "[", "]", "plugins_se...
33.347826
20.913043
def stream_has_colours(stream): """ True if stream supports colours. Python cookbook, #475186 """ if not hasattr(stream, "isatty"): return False if not stream.isatty(): return False # auto color only on TTYs try: import curses curses.setupterm() return c...
[ "def", "stream_has_colours", "(", "stream", ")", ":", "if", "not", "hasattr", "(", "stream", ",", "\"isatty\"", ")", ":", "return", "False", "if", "not", "stream", ".", "isatty", "(", ")", ":", "return", "False", "# auto color only on TTYs", "try", ":", "i...
24.466667
15.4
def list_pool(self): """ List pools and return JSON encoded result. """ # fetch attributes from request.json attr = XhrController.extract_pool_attr(request.json) try: pools = Pool.list(attr) except NipapError, e: return json.dumps({'error': 1, 'm...
[ "def", "list_pool", "(", "self", ")", ":", "# fetch attributes from request.json", "attr", "=", "XhrController", ".", "extract_pool_attr", "(", "request", ".", "json", ")", "try", ":", "pools", "=", "Pool", ".", "list", "(", "attr", ")", "except", "NipapError"...
31.307692
20.769231
def redefined_by_decorator(node): """return True if the object is a method redefined via decorator. For example: @property def x(self): return self._x @x.setter def x(self, value): self._x = value """ if node.decorators: for decorator in node.decorators.nodes: ...
[ "def", "redefined_by_decorator", "(", "node", ")", ":", "if", "node", ".", "decorators", ":", "for", "decorator", "in", "node", ".", "decorators", ".", "nodes", ":", "if", "(", "isinstance", "(", "decorator", ",", "astroid", ".", "Attribute", ")", "and", ...
29.764706
16.588235
def fetch_query_from_pgdb(self, qname, query, con, cxn, limit=None, force=False): """ Supply either an already established connection, or connection parameters. The supplied connection will override any separate cxn parameter :param qname: The name of the query to save the output to ...
[ "def", "fetch_query_from_pgdb", "(", "self", ",", "qname", ",", "query", ",", "con", ",", "cxn", ",", "limit", "=", "None", ",", "force", "=", "False", ")", ":", "if", "con", "is", "None", "and", "cxn", "is", "None", ":", "LOG", ".", "error", "(", ...
44.16
18.933333
def get_history(self, i=None): """ Get a history item by index. You can toggle whether history is recorded using * :meth:`enable_history` * :meth:`disable_history` :parameter int i: integer for indexing (can be positive or negative). If i is None or...
[ "def", "get_history", "(", "self", ",", "i", "=", "None", ")", ":", "ps", "=", "self", ".", "filter", "(", "context", "=", "'history'", ")", "# if not len(ps):", "# raise ValueError(\"no history recorded\")", "if", "i", "is", "not", "None", ":", "return", ...
35.583333
17.666667
def max_dimension(cellmap, sheet = None): """ This function calculates the maximum dimension of the workbook or optionally the worksheet. It returns a tupple of two integers, the first being the rows and the second being the columns. :param cellmap: all the cells that should be used to calculate the ma...
[ "def", "max_dimension", "(", "cellmap", ",", "sheet", "=", "None", ")", ":", "cells", "=", "list", "(", "cellmap", ".", "values", "(", ")", ")", "rows", "=", "0", "cols", "=", "0", "for", "cell", "in", "cells", ":", "if", "sheet", "is", "None", "...
38.526316
24.842105
def unlock(self, time=3): """ unlock the door\n thanks to https://github.com/SoftwareHouseMerida/pyzk/ :param time: define delay in seconds :return: bool """ command = const.CMD_UNLOCK command_string = pack("I",int(time)*10) cmd_response = self.__...
[ "def", "unlock", "(", "self", ",", "time", "=", "3", ")", ":", "command", "=", "const", ".", "CMD_UNLOCK", "command_string", "=", "pack", "(", "\"I\"", ",", "int", "(", "time", ")", "*", "10", ")", "cmd_response", "=", "self", ".", "__send_command", ...
31.533333
14.2
def status_message(self): """Return friendly response from API based on response code. """ msg = None if self.last_ddns_response in response_messages.keys(): return response_messages.get(self.last_ddns_response) if 'good' in self.last_ddns_response: ip = re.sear...
[ "def", "status_message", "(", "self", ")", ":", "msg", "=", "None", "if", "self", ".", "last_ddns_response", "in", "response_messages", ".", "keys", "(", ")", ":", "return", "response_messages", ".", "get", "(", "self", ".", "last_ddns_response", ")", "if", ...
45.555556
26.666667
def makeNetwork(self): """Makes graph object from .gdf loaded data""" if "weight" in self.data_friendships.keys(): self.G=G=x.DiGraph() else: self.G=G=x.Graph() F=self.data_friends for friendn in range(self.n_friends): if "posts" in F.keys(): ...
[ "def", "makeNetwork", "(", "self", ")", ":", "if", "\"weight\"", "in", "self", ".", "data_friendships", ".", "keys", "(", ")", ":", "self", ".", "G", "=", "G", "=", "x", ".", "DiGraph", "(", ")", "else", ":", "self", ".", "G", "=", "G", "=", "x...
45.689655
14.931034
def _addr_in_exec_memory_regions(self, addr): """ Test if the address belongs to an executable memory region. :param int addr: The address to test :return: True if the address belongs to an exectubale memory region, False otherwise :rtype: bool """ for start, en...
[ "def", "_addr_in_exec_memory_regions", "(", "self", ",", "addr", ")", ":", "for", "start", ",", "end", "in", "self", ".", "_exec_mem_regions", ":", "if", "start", "<=", "addr", "<", "end", ":", "return", "True", "return", "False" ]
32.384615
18.076923
def feed(self, data): """ Feed data to the parser. """ assert isinstance(data, binary_type) for b in iterbytes(data): self._parser.send(int2byte(b))
[ "def", "feed", "(", "self", ",", "data", ")", ":", "assert", "isinstance", "(", "data", ",", "binary_type", ")", "for", "b", "in", "iterbytes", "(", "data", ")", ":", "self", ".", "_parser", ".", "send", "(", "int2byte", "(", "b", ")", ")" ]
27.714286
5.714286
def strip_chr(bt): """Strip 'chr' from chromosomes for BedTool object Parameters ---------- bt : pybedtools.BedTool BedTool to strip 'chr' from. Returns ------- out : pybedtools.BedTool New BedTool with 'chr' stripped from chromosome names. """ try: df = pd...
[ "def", "strip_chr", "(", "bt", ")", ":", "try", ":", "df", "=", "pd", ".", "read_table", "(", "bt", ".", "fn", ",", "header", "=", "None", ",", "dtype", "=", "str", ")", "# If the try fails, I assume that's because the file has a trackline. Note", "# that I don'...
32.16
21.64
def tangle(*args, **kwargs): """ Shortcut to create a new, custom Tangle model. Use instead of directly subclassing `Tangle`. A new, custom Widget class is created, with each of `kwargs` as a traitlet. Returns an instance of the new class with default values. `kwargs` options - primitive ...
[ "def", "tangle", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "class_attrs", "=", "{", "\"_links\"", ":", "[", "]", ",", "\"_dlinks\"", ":", "[", "]", ",", "\"_derived\"", ":", "{", "}", "}", "for", "value", "in", "args", ":", "if", "isin...
34.432099
20.82716
def compile_ui(self, namespace, unknown): """Compile qt designer files :param namespace: namespace containing arguments from the launch parser :type namespace: Namespace :param unknown: list of unknown arguments :type unknown: list :returns: None :rtype: None ...
[ "def", "compile_ui", "(", "self", ",", "namespace", ",", "unknown", ")", ":", "uifiles", "=", "namespace", ".", "uifile", "for", "f", "in", "uifiles", ":", "qtcompile", ".", "compile_ui", "(", "f", ".", "name", ")" ]
31.357143
13.285714
def heptad_register(self): """Returns the calculated register of the coiled coil and the fit quality.""" base_reg = 'abcdefg' exp_base = base_reg * (self.cc_len//7+2) ave_ca_layers = self.calc_average_parameters(self.ca_layers)[0][:-1] reg_fit = fit_heptad_register(ave_ca_layers)...
[ "def", "heptad_register", "(", "self", ")", ":", "base_reg", "=", "'abcdefg'", "exp_base", "=", "base_reg", "*", "(", "self", ".", "cc_len", "//", "7", "+", "2", ")", "ave_ca_layers", "=", "self", ".", "calc_average_parameters", "(", "self", ".", "ca_layer...
51.75
14.875
def ps_ball(radius): r""" Creates spherical ball structuring element for morphological operations Parameters ---------- radius : float or int The desired radius of the structuring element Returns ------- strel : 3D-array A 3D numpy array of the structuring element "...
[ "def", "ps_ball", "(", "radius", ")", ":", "rad", "=", "int", "(", "sp", ".", "ceil", "(", "radius", ")", ")", "other", "=", "sp", ".", "ones", "(", "(", "2", "*", "rad", "+", "1", ",", "2", "*", "rad", "+", "1", ",", "2", "*", "rad", "+"...
26.947368
20.684211
def read(self, prompt='', clean=lambda x: x): """ Display a prompt and ask user for input A function to clean the user input can be passed as ``clean`` argument. This function takes a single value, which is the string user entered, and returns a cleaned value. Default is a pass-through ...
[ "def", "read", "(", "self", ",", "prompt", "=", "''", ",", "clean", "=", "lambda", "x", ":", "x", ")", ":", "ans", "=", "read", "(", "prompt", "+", "' '", ")", "return", "clean", "(", "ans", ")" ]
36.923077
20
def get_etree_root(doc, encoding=None): """Returns an instance of lxml.etree._Element for the given `doc` input. Args: doc: The input XML document. Can be an instance of ``lxml.etree._Element``, ``lxml.etree._ElementTree``, a file-like object, or a string filename. encod...
[ "def", "get_etree_root", "(", "doc", ",", "encoding", "=", "None", ")", ":", "tree", "=", "get_etree", "(", "doc", ",", "encoding", ")", "root", "=", "tree", ".", "getroot", "(", ")", "return", "root" ]
31.608696
22.347826
def _diff(self, x, th, eps): """ Differentiation function. Numerical approximation of a Rosenblatt transformation created from copula formulation. """ foo = lambda y: self.igen(numpy.sum(self.gen(y, th), 0), th) out1 = out2 = 0. sign = 1 - 2*(x > .5).T ...
[ "def", "_diff", "(", "self", ",", "x", ",", "th", ",", "eps", ")", ":", "foo", "=", "lambda", "y", ":", "self", ".", "igen", "(", "numpy", ".", "sum", "(", "self", ".", "gen", "(", "y", ",", "th", ")", ",", "0", ")", ",", "th", ")", "out1...
26.363636
18.181818
def keyPressEvent(self, event): """Reimplement Qt method to allow cyclic behavior.""" if event.key() == Qt.Key_Down: self.select_row(1) elif event.key() == Qt.Key_Up: self.select_row(-1)
[ "def", "keyPressEvent", "(", "self", ",", "event", ")", ":", "if", "event", ".", "key", "(", ")", "==", "Qt", ".", "Key_Down", ":", "self", ".", "select_row", "(", "1", ")", "elif", "event", ".", "key", "(", ")", "==", "Qt", ".", "Key_Up", ":", ...
39
4.666667
def add_to_manifest(dynamodb_client, table_name, run_id): """Add run_id into DynamoDB manifest table Arguments: dynamodb_client - boto3 DynamoDB client (not service) table_name - string representing existing table name run_id - string representing run_id to store """ dynamodb_client.put_ite...
[ "def", "add_to_manifest", "(", "dynamodb_client", ",", "table_name", ",", "run_id", ")", ":", "dynamodb_client", ".", "put_item", "(", "TableName", "=", "table_name", ",", "Item", "=", "{", "DYNAMODB_RUNID_ATTRIBUTE", ":", "{", "'S'", ":", "run_id", "}", "}", ...
28.125
17.4375
def is_sms_service_for_region(numobj, region_dialing_from): """Given a valid short number, determines whether it is an SMS service (however, nothing is implied about its validity). An SMS service is where the primary or only intended usage is to receive and/or send text messages (SMSs). This includes MM...
[ "def", "is_sms_service_for_region", "(", "numobj", ",", "region_dialing_from", ")", ":", "if", "not", "_region_dialing_from_matches_number", "(", "numobj", ",", "region_dialing_from", ")", ":", "return", "False", "metadata", "=", "PhoneMetadata", ".", "short_metadata_fo...
54.454545
27.136364
async def unloadmodule(self, module, ignoreDependencies = False): ''' Unload a module class ''' self._logger.debug('Try to unload module %r', module) if hasattr(module, '_instance'): self._logger.debug('Module %r is loaded, module state is %r', module, module._instanc...
[ "async", "def", "unloadmodule", "(", "self", ",", "module", ",", "ignoreDependencies", "=", "False", ")", ":", "self", ".", "_logger", ".", "debug", "(", "'Try to unload module %r'", ",", "module", ")", "if", "hasattr", "(", "module", ",", "'_instance'", ")"...
63.222222
30.333333
def get_service_dependencies_for(service): """Calculate the dependencies for the given service. """ dependants = get_calculation_dependants_for(service) dependencies = get_calculation_dependencies_for(service) return { "dependencies": dependencies.values(), "dependants": dependants...
[ "def", "get_service_dependencies_for", "(", "service", ")", ":", "dependants", "=", "get_calculation_dependants_for", "(", "service", ")", "dependencies", "=", "get_calculation_dependencies_for", "(", "service", ")", "return", "{", "\"dependencies\"", ":", "dependencies",...
29.636364
17.181818
def _setup_phantomjs(self, capabilities): """Setup phantomjs webdriver :param capabilities: capabilities object :returns: a new local phantomjs driver """ phantomjs_driver = self.config.get('Driver', 'phantomjs_driver_path') self.logger.debug("Phantom driver path given i...
[ "def", "_setup_phantomjs", "(", "self", ",", "capabilities", ")", ":", "phantomjs_driver", "=", "self", ".", "config", ".", "get", "(", "'Driver'", ",", "'phantomjs_driver_path'", ")", "self", ".", "logger", ".", "debug", "(", "\"Phantom driver path given in prope...
50.222222
22.777778
def check_img(image, make_it_3d=False): """Check that image is a proper img. Turn filenames into objects. Parameters ---------- image: img-like object or str Can either be: - a file path to a Nifti image - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1...
[ "def", "check_img", "(", "image", ",", "make_it_3d", "=", "False", ")", ":", "if", "isinstance", "(", "image", ",", "string_types", ")", ":", "# a filename, load it", "if", "not", "op", ".", "exists", "(", "image", ")", ":", "raise", "FileNotFound", "(", ...
35.767442
22.883721
def padded_to_same_length(seq1, seq2, item=0): """Return a pair of sequences of the same length by padding the shorter sequence with ``item``. The padded sequence is a tuple. The unpadded sequence is returned as-is. """ len1, len2 = len(seq1), len(seq2) if len1 == len2: return (seq1, s...
[ "def", "padded_to_same_length", "(", "seq1", ",", "seq2", ",", "item", "=", "0", ")", ":", "len1", ",", "len2", "=", "len", "(", "seq1", ")", ",", "len", "(", "seq2", ")", "if", "len1", "==", "len2", ":", "return", "(", "seq1", ",", "seq2", ")", ...
36.153846
17.307692
def select_event( event = None, selection = "all", required_variables = None, ensure_required_variables_present = False, verbose = True ): """ Select a HEP event. """ if required_variab...
[ "def", "select_event", "(", "event", "=", "None", ",", "selection", "=", "\"all\"", ",", "required_variables", "=", "None", ",", "ensure_required_variables_present", "=", "False", ",", "verbose", "=", "True", ")", ":", "if", "required_variables", "is", "None", ...
32.603376
18.518987
def save_assets(self, dest_path): """Save plot assets alongside dest_path. Some plots may have assets, like bitmap files, which need to be saved alongside the rendered plot file. :param dest_path: path of the main output file. """ for idx, subplot in enumerate(self.sub...
[ "def", "save_assets", "(", "self", ",", "dest_path", ")", ":", "for", "idx", ",", "subplot", "in", "enumerate", "(", "self", ".", "subplots", ")", ":", "subplot", ".", "save_assets", "(", "dest_path", ",", "suffix", "=", "'_%d'", "%", "idx", ")" ]
34.545455
19.545455
def _get_oauth_params(self, req_kwargs): '''Prepares OAuth params for signing.''' oauth_params = {} oauth_params['oauth_consumer_key'] = self.consumer_key oauth_params['oauth_nonce'] = sha1( str(random()).encode('ascii')).hexdigest() oauth_params['oauth_signature_met...
[ "def", "_get_oauth_params", "(", "self", ",", "req_kwargs", ")", ":", "oauth_params", "=", "{", "}", "oauth_params", "[", "'oauth_consumer_key'", "]", "=", "self", ".", "consumer_key", "oauth_params", "[", "'oauth_nonce'", "]", "=", "sha1", "(", "str", "(", ...
35.166667
20.5
def arrow(self, JOIN, _id): """Removes all previous assignments from JOIN that have the same left hand side. This represents the arrow id definition from Schwartzbach.""" r = JOIN for node in self.lattice.get_elements(JOIN): if node.left_hand_side == _id: r = ...
[ "def", "arrow", "(", "self", ",", "JOIN", ",", "_id", ")", ":", "r", "=", "JOIN", "for", "node", "in", "self", ".", "lattice", ".", "get_elements", "(", "JOIN", ")", ":", "if", "node", ".", "left_hand_side", "==", "_id", ":", "r", "=", "r", "^", ...
44.75
10.375
def get_pre_compute(self, s): ''' :param s: [src_sequence, batch_size, src_dim] :return: [src_sequence, batch_size. hidden_dim] ''' hidden_dim = self.hidden_dim src_dim = s.get_shape().as_list()[-1] assert src_dim is not None, 'src dim must be defined' W =...
[ "def", "get_pre_compute", "(", "self", ",", "s", ")", ":", "hidden_dim", "=", "self", ".", "hidden_dim", "src_dim", "=", "s", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "-", "1", "]", "assert", "src_dim", "is", "not", "None", ",", "...
42
15.272727
def step(self, state, clamping): """ Performs a simulation step from the given state and with respect to the given clamping Parameters ---------- state : dict The key-value mapping describing the current state of the logical network clamping : caspo.core.cla...
[ "def", "step", "(", "self", ",", "state", ",", "clamping", ")", ":", "ns", "=", "state", ".", "copy", "(", ")", "for", "var", "in", "state", ":", "if", "clamping", ".", "has_variable", "(", "var", ")", ":", "ns", "[", "var", "]", "=", "int", "(...
30.354839
21.774194
def _read_header(self, ccp4file): """Read header bytes""" bsaflag = self._detect_byteorder(ccp4file) # Parse the top of the header (4-byte words, 1 to 25). nheader = struct.calcsize(self._headerfmt) names = [r.key for r in self._header_struct] bintopheader = ccp4file.re...
[ "def", "_read_header", "(", "self", ",", "ccp4file", ")", ":", "bsaflag", "=", "self", ".", "_detect_byteorder", "(", "ccp4file", ")", "# Parse the top of the header (4-byte words, 1 to 25).", "nheader", "=", "struct", ".", "calcsize", "(", "self", ".", "_headerfmt"...
45.625
20.8125
def build_bucket(self, name, lifecycle_configuration=False, use_plain_name=False): """ Generate S3 bucket statement :param name: Name of the bucket :param lifecycle_configuration: Additional lifecycle configuration (default=False) :param use_plain_name: Just ...
[ "def", "build_bucket", "(", "self", ",", "name", ",", "lifecycle_configuration", "=", "False", ",", "use_plain_name", "=", "False", ")", ":", "if", "use_plain_name", ":", "name_aws", "=", "name_bucket", "=", "name", "name_aws", "=", "name_aws", ".", "title", ...
35.34375
14.71875
def location_2_json(self): """ transform ariane_clip3 location object to Ariane server JSON obj :return: Ariane JSON obj """ LOGGER.debug("Location.location_2_json") json_obj = { 'locationID': self.id, 'locationName': self.name, 'locati...
[ "def", "location_2_json", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "\"Location.location_2_json\"", ")", "json_obj", "=", "{", "'locationID'", ":", "self", ".", "id", ",", "'locationName'", ":", "self", ".", "name", ",", "'locationDescription'", ":",...
38.095238
9.428571
def encode(claims, key, algorithm=ALGORITHMS.HS256, headers=None, access_token=None): """Encodes a claims set and returns a JWT string. JWTs are JWS signed objects with a few reserved claims. Args: claims (dict): A claims set to sign key (str or dict): The key to use for signing the claim ...
[ "def", "encode", "(", "claims", ",", "key", ",", "algorithm", "=", "ALGORITHMS", ".", "HS256", ",", "headers", "=", "None", ",", "access_token", "=", "None", ")", ":", "for", "time_claim", "in", "[", "'exp'", ",", "'iat'", ",", "'nbf'", "]", ":", "# ...
39.52381
28.333333
def _assert_input_is_valid(input_value, # type: Any validators, # type: List[InputValidator] validated_func, # type: Callable input_name # type: str ): """ Called by the `validating_wrappe...
[ "def", "_assert_input_is_valid", "(", "input_value", ",", "# type: Any", "validators", ",", "# type: List[InputValidator]", "validated_func", ",", "# type: Callable", "input_name", "# type: str", ")", ":", "for", "validator", "in", "validators", ":", "validator", ".", "...
58.473684
30.263158
def replace(self, old_patch, new_patch): """ Replace old_patch with new_patch The method only replaces the patch and doesn't change any comments. """ self._check_patch(old_patch) old_patchline = self.patch2line[old_patch] index = self.patchlines.index(old_patchline) ...
[ "def", "replace", "(", "self", ",", "old_patch", ",", "new_patch", ")", ":", "self", ".", "_check_patch", "(", "old_patch", ")", "old_patchline", "=", "self", ".", "patch2line", "[", "old_patch", "]", "index", "=", "self", ".", "patchlines", ".", "index", ...
45.230769
9
def cli(family_file, family_type, to_json, to_madeline, to_ped, to_dict, outfile, logfile, loglevel): """Cli for testing the ped parser.""" from pprint import pprint as pp my_parser = FamilyParser(family_file, family_type) if to_json: if outfile: outfile.write(my_p...
[ "def", "cli", "(", "family_file", ",", "family_type", ",", "to_json", ",", "to_madeline", ",", "to_ped", ",", "to_dict", ",", "outfile", ",", "logfile", ",", "loglevel", ")", ":", "from", "pprint", "import", "pprint", "as", "pp", "my_parser", "=", "FamilyP...
28.142857
16.25
def import_model(self, source): """Import and return model instance.""" if not hasattr(source, 'read'): # Not a File-like object with open(self._resolve_source(source), 'r') as f: return self._import(f) else: return self._import(source)
[ "def", "import_model", "(", "self", ",", "source", ")", ":", "if", "not", "hasattr", "(", "source", ",", "'read'", ")", ":", "# Not a File-like object", "with", "open", "(", "self", ".", "_resolve_source", "(", "source", ")", ",", "'r'", ")", "as", "f", ...
42.142857
12.285714
def cached(f): """Decorator for caching/retrieving api calls request. Many calls to the API are getter on static parts (e.g site of a given cluster name won't change). By caching some responses we can avoid hammering the API server. """ @functools.wraps(f) def wrapped(*args, **kwargs): ...
[ "def", "cached", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "_cache_lock", ":", "identifier", "=", "(", "f", ".", "__name__", ",", "args", ",",...
36.380952
15.761905
def disassemble(self): """ disassembles the underlying bytecode instructions and generates a sequence of (offset, code, args) tuples """ dis = self._dis_code if dis is None: dis = tuple(disassemble(self.code)) self._dis_code = dis return ...
[ "def", "disassemble", "(", "self", ")", ":", "dis", "=", "self", ".", "_dis_code", "if", "dis", "is", "None", ":", "dis", "=", "tuple", "(", "disassemble", "(", "self", ".", "code", ")", ")", "self", ".", "_dis_code", "=", "dis", "return", "dis" ]
26
17
async def delete(self, key, param=None): """ delete cache corresponding to identity generated from key and param """ identity = self._gen_identity(key, param) return await self.client.delete(identity)
[ "async", "def", "delete", "(", "self", ",", "key", ",", "param", "=", "None", ")", ":", "identity", "=", "self", ".", "_gen_identity", "(", "key", ",", "param", ")", "return", "await", "self", ".", "client", ".", "delete", "(", "identity", ")" ]
34.571429
4
def goal_update(self, goal_id, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/goals#update-goal" api_path = "/api/v2/goals/{goal_id}" api_path = api_path.format(goal_id=goal_id) return self.call(api_path, method="PUT", data=data, **kwargs)
[ "def", "goal_update", "(", "self", ",", "goal_id", ",", "data", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/goals/{goal_id}\"", "api_path", "=", "api_path", ".", "format", "(", "goal_id", "=", "goal_id", ")", "return", "self", ".", "call...
57.4
17.4
def _validate_record_field_positions_global(record): """ Check if the global field positions in the record are valid. I.e., no duplicate global field positions and local field positions in the list of fields are ascending. :param record: the record data structure :return: the first error found...
[ "def", "_validate_record_field_positions_global", "(", "record", ")", ":", "all_fields", "=", "[", "]", "for", "tag", ",", "fields", "in", "record", ".", "items", "(", ")", ":", "previous_field_position_global", "=", "-", "1", "for", "field", "in", "fields", ...
40.857143
16.952381
def get_series(self, key): """Get a series object from TempoDB given its key. :param string key: a string name for the series :rtype: :class:`tempodb.response.Response` with a :class:`tempodb.protocol.objects.Series` data payload""" url = make_series_url(key) re...
[ "def", "get_series", "(", "self", ",", "key", ")", ":", "url", "=", "make_series_url", "(", "key", ")", "resp", "=", "self", ".", "session", ".", "get", "(", "url", ")", "return", "resp" ]
35.7
15.7
def RIBSystemRouteLimitExceeded_originator_switch_info_switchVcsId(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") RIBSystemRouteLimitExceeded = ET.SubElement(config, "RIBSystemRouteLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream") ...
[ "def", "RIBSystemRouteLimitExceeded_originator_switch_info_switchVcsId", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "RIBSystemRouteLimitExceeded", "=", "ET", ".", "SubElement", "(", "config", ",", "...
56.818182
29.818182
def datatype(field_decls, superclass_name=None, **kwargs): """A wrapper for `namedtuple` that accounts for the type of the object in equality. Field declarations can be a string, which declares a field with that name and no type checking. Field declarations can also be a tuple `('field_name', field_type)`, whi...
[ "def", "datatype", "(", "field_decls", ",", "superclass_name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "field_names", "=", "[", "]", "fields_with_constraints", "=", "OrderedDict", "(", ")", "for", "maybe_decl", "in", "field_decls", ":", "# ('field_name...
39.209877
19.697531
def nvmlDeviceGetInforomImageVersion(handle): r""" /** * Retrieves the global infoROM image version * * For all products with an inforom. * * Image version just like VBIOS version uniquely describes the exact version of the infoROM flashed on the board * in contrast to infoROM obje...
[ "def", "nvmlDeviceGetInforomImageVersion", "(", "handle", ")", ":", "c_version", "=", "create_string_buffer", "(", "NVML_DEVICE_INFOROM_VERSION_BUFFER_SIZE", ")", "fn", "=", "_nvmlGetFunctionPointer", "(", "\"nvmlDeviceGetInforomImageVersion\"", ")", "ret", "=", "fn", "(", ...
55.441176
33.705882
def save_sequence_rule(self, sequence_rule_form, *args, **kwargs): """Pass through to provider SequenceRuleAdminSession.update_sequence_rule""" # Implemented from kitosid template for - # osid.resource.ResourceAdminSession.update_resource if sequence_rule_form.is_for_update(): ...
[ "def", "save_sequence_rule", "(", "self", ",", "sequence_rule_form", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Implemented from kitosid template for -", "# osid.resource.ResourceAdminSession.update_resource", "if", "sequence_rule_form", ".", "is_for_update", "...
60
21.25
def play_mode(self, playmode): """Set the speaker's mode.""" playmode = playmode.upper() if playmode not in PLAY_MODES.keys(): raise KeyError("'%s' is not a valid play mode" % playmode) self.avTransport.SetPlayMode([ ('InstanceID', 0), ('NewPlayMode',...
[ "def", "play_mode", "(", "self", ",", "playmode", ")", ":", "playmode", "=", "playmode", ".", "upper", "(", ")", "if", "playmode", "not", "in", "PLAY_MODES", ".", "keys", "(", ")", ":", "raise", "KeyError", "(", "\"'%s' is not a valid play mode\"", "%", "p...
33.2
13.5
def peek(self) -> str: """Return the next character without advancing offset. Raises: EndOfInput: If past the end of `self.input`. """ try: return self.input[self.offset] except IndexError: raise EndOfInput(self)
[ "def", "peek", "(", "self", ")", "->", "str", ":", "try", ":", "return", "self", ".", "input", "[", "self", ".", "offset", "]", "except", "IndexError", ":", "raise", "EndOfInput", "(", "self", ")" ]
28
14.9
def _check_data(data): """ Check a data object for inconsistencies. Parameters ---------- data : `pandas.DataFrame` A `data` object, i.e., a table whose rows store information about chemical species, indexed by chemical species. Warns ----- UserWarning Warned if...
[ "def", "_check_data", "(", "data", ")", ":", "if", "\"vibfreqs\"", "in", "data", ".", "columns", ":", "for", "species", "in", "data", ".", "index", ":", "vibfreqs", "=", "data", ".", "loc", "[", "species", ",", "\"vibfreqs\"", "]", "nimagvibfreqs", "=", ...
40.731707
23.268293
def singleFactor(factors, chart, factor, obj, aspect=None): """" Single factor for the table. """ objID = obj if type(obj) == str else obj.id res = { 'factor': factor, 'objID': objID, 'aspect': aspect } # For signs (obj as string) return sign element if type(obj...
[ "def", "singleFactor", "(", "factors", ",", "chart", ",", "factor", ",", "obj", ",", "aspect", "=", "None", ")", ":", "objID", "=", "obj", "if", "type", "(", "obj", ")", "==", "str", "else", "obj", ".", "id", "res", "=", "{", "'factor'", ":", "fa...
29.75
17.454545
def should_stop_early(self) -> bool: """ Returns true if improvement has stopped for long enough. """ if self._patience is None: return False else: return self._epochs_with_no_improvement >= self._patience
[ "def", "should_stop_early", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "_patience", "is", "None", ":", "return", "False", "else", ":", "return", "self", ".", "_epochs_with_no_improvement", ">=", "self", ".", "_patience" ]
32.75
13.25
def _server_end_response_callback(self, respoonse: Response): '''Response callback handler.''' request = self._item_session.request response = self._item_session.response _logger.info(__( _('Fetched ‘{url}’: {status_code} {reason}. ' 'Length: {content_length} [...
[ "def", "_server_end_response_callback", "(", "self", ",", "respoonse", ":", "Response", ")", ":", "request", "=", "self", ".", "_item_session", ".", "request", "response", "=", "self", ".", "_item_session", ".", "response", "_logger", ".", "info", "(", "__", ...
47.2
23.533333
def register_child(self, child): """ Register a new child that will be closed whenever the current instance closes. :param child: The child instance. """ if self.closing: child.close() else: self._children.add(child) child.on_c...
[ "def", "register_child", "(", "self", ",", "child", ")", ":", "if", "self", ".", "closing", ":", "child", ".", "close", "(", ")", "else", ":", "self", ".", "_children", ".", "add", "(", "child", ")", "child", ".", "on_closed", ".", "connect", "(", ...
28.75
15.916667
def discover(): """ Import all experiments listed in *_PLUGINS_REPORTS. Tests: >>> from benchbuild.settings import CFG >>> from benchbuild.reports import discover >>> import logging as lg >>> import sys >>> l = lg.getLogger('benchbuild') >>> l.setLevel(lg.DEB...
[ "def", "discover", "(", ")", ":", "if", "CFG", "[", "\"plugins\"", "]", "[", "\"autoload\"", "]", ":", "report_plugins", "=", "CFG", "[", "\"plugins\"", "]", "[", "\"reports\"", "]", ".", "value", "for", "plugin", "in", "report_plugins", ":", "try", ":",...
36.76
14.52