text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def version(): """Return version string.""" with io.open('pgmagick/_version.py') as input_file: for line in input_file: if line.startswith('__version__'): return ast.parse(line).body[0].value.s
[ "def", "version", "(", ")", ":", "with", "io", ".", "open", "(", "'pgmagick/_version.py'", ")", "as", "input_file", ":", "for", "line", "in", "input_file", ":", "if", "line", ".", "startswith", "(", "'__version__'", ")", ":", "return", "ast", ".", "parse...
38.666667
11.666667
def imshow_z(data, name): """2D color plot of the quasiparticle weight as a function of interaction and doping""" zmes = pick_flat_z(data) plt.figure() plt.imshow(zmes.T, origin='lower', \ extent=[data['doping'].min(), data['doping'].max(), \ 0, data['u_int'].max()], asp...
[ "def", "imshow_z", "(", "data", ",", "name", ")", ":", "zmes", "=", "pick_flat_z", "(", "data", ")", "plt", ".", "figure", "(", ")", "plt", ".", "imshow", "(", "zmes", ".", "T", ",", "origin", "=", "'lower'", ",", "extent", "=", "[", "data", "[",...
35.533333
16.133333
def _change_splitlevel(self, ttype, value): """Get the new split level (increase, decrease or remain equal)""" # parenthesis increase/decrease a level if ttype is T.Punctuation and value == '(': return 1 elif ttype is T.Punctuation and value == ')': return -1 ...
[ "def", "_change_splitlevel", "(", "self", ",", "ttype", ",", "value", ")", ":", "# parenthesis increase/decrease a level", "if", "ttype", "is", "T", ".", "Punctuation", "and", "value", "==", "'('", ":", "return", "1", "elif", "ttype", "is", "T", ".", "Punctu...
35.27451
21.196078
def all_settings(self, uppercase_keys=False): """Return all settings as a `dict`.""" d = {} for k in self.all_keys(uppercase_keys): d[k] = self.get(k) return d
[ "def", "all_settings", "(", "self", ",", "uppercase_keys", "=", "False", ")", ":", "d", "=", "{", "}", "for", "k", "in", "self", ".", "all_keys", "(", "uppercase_keys", ")", ":", "d", "[", "k", "]", "=", "self", ".", "get", "(", "k", ")", "return...
24.75
19
def revoke_user_token(self, user_id): """ Revoke user token Erases user token on file forcing them to re-login and obtain a new one. :param user_id: int :return: """ user = self.get(user_id) user._token = None self.save(user)
[ "def", "revoke_user_token", "(", "self", ",", "user_id", ")", ":", "user", "=", "self", ".", "get", "(", "user_id", ")", "user", ".", "_token", "=", "None", "self", ".", "save", "(", "user", ")" ]
28.8
13.4
def _set_matplotlib_default_backend(): """ matplotlib will try to print to a display if it is available, but don't want to run it in interactive mode. we tried setting the backend to 'Agg'' before importing, but it was still resulting in issues. we replace the existing backend with 'agg' in the defa...
[ "def", "_set_matplotlib_default_backend", "(", ")", ":", "if", "_matplotlib_installed", "(", ")", ":", "import", "matplotlib", "matplotlib", ".", "use", "(", "'Agg'", ",", "force", "=", "True", ")", "config", "=", "matplotlib", ".", "matplotlib_fname", "(", ")...
47.8
16.4
def getParameter(self, objID, param): """getParameter(string, string) -> string Returns the value of the given parameter for the given objID """ self._connection._beginMessage( self._cmdGetID, tc.VAR_PARAMETER, objID, 1 + 4 + len(param)) self._connection._packString(...
[ "def", "getParameter", "(", "self", ",", "objID", ",", "param", ")", ":", "self", ".", "_connection", ".", "_beginMessage", "(", "self", ".", "_cmdGetID", ",", "tc", ".", "VAR_PARAMETER", ",", "objID", ",", "1", "+", "4", "+", "len", "(", "param", ")...
41.090909
12
def DOMDebugger_setDOMBreakpoint(self, nodeId, type): """ Function path: DOMDebugger.setDOMBreakpoint Domain: DOMDebugger Method name: setDOMBreakpoint Parameters: Required arguments: 'nodeId' (type: DOM.NodeId) -> Identifier of the node to set breakpoint on. 'type' (type: DOMBreakpointTyp...
[ "def", "DOMDebugger_setDOMBreakpoint", "(", "self", ",", "nodeId", ",", "type", ")", ":", "subdom_funcs", "=", "self", ".", "synchronous_command", "(", "'DOMDebugger.setDOMBreakpoint'", ",", "nodeId", "=", "nodeId", ",", "type", "=", "type", ")", "return", "subd...
33.411765
20.352941
def parse_include(self, start): """ Extract include from text based on start position of token Returns ------- (end, incl_path) - end: last char in include - incl_path: Resolved path to include """ # Seek back to start of line i = ...
[ "def", "parse_include", "(", "self", ",", "start", ")", ":", "# Seek back to start of line", "i", "=", "start", "while", "i", ":", "if", "self", ".", "text", "[", "i", "]", "==", "'\\n'", ":", "i", "+=", "1", "break", "i", "-=", "1", "line_start", "=...
38.24359
19.371795
async def setRemoteDescription(self, sessionDescription): """ Changes the remote description associated with the connection. :param: sessionDescription: An :class:`RTCSessionDescription` created from information received over the signaling channel. ""...
[ "async", "def", "setRemoteDescription", "(", "self", ",", "sessionDescription", ")", ":", "# parse and validate description", "description", "=", "sdp", ".", "SessionDescription", ".", "parse", "(", "sessionDescription", ".", "sdp", ")", "description", ".", "type", ...
44.147059
17.705882
def users_identity(self, **kwargs) -> SlackResponse: """Get a user's identity.""" self._validate_xoxp_token() return self.api_call("users.identity", http_verb="GET", params=kwargs)
[ "def", "users_identity", "(", "self", ",", "*", "*", "kwargs", ")", "->", "SlackResponse", ":", "self", ".", "_validate_xoxp_token", "(", ")", "return", "self", ".", "api_call", "(", "\"users.identity\"", ",", "http_verb", "=", "\"GET\"", ",", "params", "=",...
50.25
13.75
def drawBackground( self, painter, rect ): """ Draws the background of the scene using painter. :param painter | <QPainter> rect | <QRectF> """ if ( self._rebuildRequired ): self.rebuild() super(XCalendarScene, ...
[ "def", "drawBackground", "(", "self", ",", "painter", ",", "rect", ")", ":", "if", "(", "self", ".", "_rebuildRequired", ")", ":", "self", ".", "rebuild", "(", ")", "super", "(", "XCalendarScene", ",", "self", ")", ".", "drawBackground", "(", "painter", ...
35.113636
13.227273
def require_dataset(self, name, shape, dtype=None, exact=False, **kwargs): """Obtain an array, creating if it doesn't exist. Other `kwargs` are as per :func:`zarr.hierarchy.Group.create_dataset`. Parameters ---------- name : string Array name. shape : int or ...
[ "def", "require_dataset", "(", "self", ",", "name", ",", "shape", ",", "dtype", "=", "None", ",", "exact", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_write_op", "(", "self", ".", "_require_dataset_nosync", ",", "name", ",...
35.95
20.2
def process_equations(key, value, fmt, meta): """Processes the attributed equations.""" if key == 'Math' and len(value) == 3: # Process the equation eq = _process_equation(value, fmt) # Get the attributes and label attrs = eq['attrs'] label = attrs[0] if eq['is...
[ "def", "process_equations", "(", "key", ",", "value", ",", "fmt", ",", "meta", ")", ":", "if", "key", "==", "'Math'", "and", "len", "(", "value", ")", "==", "3", ":", "# Process the equation", "eq", "=", "_process_equation", "(", "value", ",", "fmt", "...
44.745098
18.72549
def align(time, time2, magnitude, magnitude2, error, error2): """Synchronizes the light-curves in the two different bands. Returns ------- aligned_time aligned_magnitude aligned_magnitude2 aligned_error aligned_error2 """ error = np.zeros(time.shape) if error is None else err...
[ "def", "align", "(", "time", ",", "time2", ",", "magnitude", ",", "magnitude2", ",", "error", ",", "error2", ")", ":", "error", "=", "np", ".", "zeros", "(", "time", ".", "shape", ")", "if", "error", "is", "None", "else", "error", "error2", "=", "n...
30.131579
23.473684
def _new_pool(self, scheme, host, port): """ Create a new :class:`ConnectionPool` based on host, port and scheme. This method is used to actually create the connection pools handed out by :meth:`connection_from_url` and companion methods. It is intended to be overridden for cust...
[ "def", "_new_pool", "(", "self", ",", "scheme", ",", "host", ",", "port", ")", ":", "pool_cls", "=", "pool_classes_by_scheme", "[", "scheme", "]", "kwargs", "=", "self", ".", "connection_pool_kw", "if", "scheme", "==", "'http'", ":", "kwargs", "=", "self",...
38.6875
14.9375
def _check_default_index(items, default_index): '''Check that the default is in the list, and not empty''' num_items = len(items) if default_index is not None and not isinstance(default_index, int): raise TypeError("The default index ({}) is not an integer".format(default_index)) if default_inde...
[ "def", "_check_default_index", "(", "items", ",", "default_index", ")", ":", "num_items", "=", "len", "(", "items", ")", "if", "default_index", "is", "not", "None", "and", "not", "isinstance", "(", "default_index", ",", "int", ")", ":", "raise", "TypeError",...
69.181818
31.727273
def density_between_circular_annuli_in_angular_units(self, inner_annuli_radius, outer_annuli_radius): """Calculate the mass between two circular annuli and compute the density by dividing by the annuli surface area. The value returned by the mass integral is dimensionless, therefore the density...
[ "def", "density_between_circular_annuli_in_angular_units", "(", "self", ",", "inner_annuli_radius", ",", "outer_annuli_radius", ")", ":", "annuli_area", "=", "(", "np", ".", "pi", "*", "outer_annuli_radius", "**", "2.0", ")", "-", "(", "np", ".", "pi", "*", "inn...
57.052632
32.736842
def estimate_reduce(interface, state, label, inp): """Estimate the cluster centers for each cluster.""" centers = {} for i, c in inp: centers[i] = c if i not in centers else state['update'](centers[i], c) out = interface.output(0) for i, c in centers.items(): out.add(i, state['final...
[ "def", "estimate_reduce", "(", "interface", ",", "state", ",", "label", ",", "inp", ")", ":", "centers", "=", "{", "}", "for", "i", ",", "c", "in", "inp", ":", "centers", "[", "i", "]", "=", "c", "if", "i", "not", "in", "centers", "else", "state"...
35.666667
16.777778
def generateRevision(self): """ Generates the revision file for this builder. """ revpath = self.sourcePath() if not os.path.exists(revpath): return # determine the revision location revfile = os.path.join(revpath, self.revisionFilename()) mod...
[ "def", "generateRevision", "(", "self", ")", ":", "revpath", "=", "self", ".", "sourcePath", "(", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "revpath", ")", ":", "return", "# determine the revision location", "revfile", "=", "os", ".", "path"...
29.682927
16.463415
async def _handle_container_timeout(self, container_id, timeout): """ Check timeout with docker stats :param container_id: :param timeout: in seconds (cpu time) """ try: docker_stats = await self._docker_interface.get_stats(container_id) source = A...
[ "async", "def", "_handle_container_timeout", "(", "self", ",", "container_id", ",", "timeout", ")", ":", "try", ":", "docker_stats", "=", "await", "self", ".", "_docker_interface", ".", "get_stats", "(", "container_id", ")", "source", "=", "AsyncIteratorWrapper", ...
49.695652
22.565217
async def popHiveKey(self, path): ''' Remove and return the value of a key in the cell default hive ''' perm = ('hive:pop',) + path self.user.allowed(perm) return await self.cell.hive.pop(path)
[ "async", "def", "popHiveKey", "(", "self", ",", "path", ")", ":", "perm", "=", "(", "'hive:pop'", ",", ")", "+", "path", "self", ".", "user", ".", "allowed", "(", "perm", ")", "return", "await", "self", ".", "cell", ".", "hive", ".", "pop", "(", ...
44.2
12.6
def update_coordinates(self, new_coordinates): """ new_coordinates : dict """ for k, v in new_coordinates.items(): if k in self.coordinates: self.coordinates[k] = v for svertex in self.spawn_list: verts = tuple([self.coordinates.get(ch, No...
[ "def", "update_coordinates", "(", "self", ",", "new_coordinates", ")", ":", "for", "k", ",", "v", "in", "new_coordinates", ".", "items", "(", ")", ":", "if", "k", "in", "self", ".", "coordinates", ":", "self", ".", "coordinates", "[", "k", "]", "=", ...
37.1875
15.5625
def add_comment(self, comment): """ Add a comment to the database. Args: comment (hotdoc.core.Comment): comment to add """ if not comment: return self.__comments[comment.name] = comment self.comment_added_signal(self, comment)
[ "def", "add_comment", "(", "self", ",", "comment", ")", ":", "if", "not", "comment", ":", "return", "self", ".", "__comments", "[", "comment", ".", "name", "]", "=", "comment", "self", ".", "comment_added_signal", "(", "self", ",", "comment", ")" ]
24.75
15.75
def manage_file(name, sfn, ret, source, source_sum, user, group, mode, attrs, saltenv, backup, makedirs=False, template=None, ...
[ "def", "manage_file", "(", "name", ",", "sfn", ",", "ret", ",", "source", ",", "source_sum", ",", "user", ",", "group", ",", "mode", ",", "attrs", ",", "saltenv", ",", "backup", ",", "makedirs", "=", "False", ",", "template", "=", "None", ",", "# pyl...
39.254826
21.158301
def _login(self, username, password): '''Authenticates a TissueMAPS user. Parameters ---------- username: str name password: str password ''' logger.debug('login in as user "%s"' % username) url = self._build_url('/auth') p...
[ "def", "_login", "(", "self", ",", "username", ",", "password", ")", ":", "logger", ".", "debug", "(", "'login in as user \"%s\"'", "%", "username", ")", "url", "=", "self", ".", "_build_url", "(", "'/auth'", ")", "payload", "=", "{", "'username'", ":", ...
31.736842
17.421053
def serialize_seeds(seeds, block): """ Serialize the seeds in peer instruction XBlock to xml Args: seeds (lxml.etree.Element): The <seeds> XML element. block (PeerInstructionXBlock): The XBlock with configuration to serialize. Returns: None """ for seed_dict in block.se...
[ "def", "serialize_seeds", "(", "seeds", ",", "block", ")", ":", "for", "seed_dict", "in", "block", ".", "seeds", ":", "seed", "=", "etree", ".", "SubElement", "(", "seeds", ",", "'seed'", ")", "# options in xml starts with 1", "seed", ".", "set", "(", "'op...
32.125
19
def manufacturer(self): """Returns the name of the manufacturer of the device. Args: self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance Returns: Manufacturer name. """ buf = ctypes.cast(self.sManu, ctypes.c_char_p).value return buf.decode() if ...
[ "def", "manufacturer", "(", "self", ")", ":", "buf", "=", "ctypes", ".", "cast", "(", "self", ".", "sManu", ",", "ctypes", ".", "c_char_p", ")", ".", "value", "return", "buf", ".", "decode", "(", ")", "if", "buf", "else", "None" ]
29.363636
19.090909
def is_expired(self): """ Indicates if connection has expired. """ if time.time() - self.last_ping > HB_PING_TIME: self.ping() return (time.time() - self.last_pong) > HB_PING_TIME + HB_PONG_TIME
[ "def", "is_expired", "(", "self", ")", ":", "if", "time", ".", "time", "(", ")", "-", "self", ".", "last_ping", ">", "HB_PING_TIME", ":", "self", ".", "ping", "(", ")", "return", "(", "time", ".", "time", "(", ")", "-", "self", ".", "last_pong", ...
37.666667
21
def get_licenses(self): """ :calls: `GET /licenses <https://developer.github.com/v3/licenses/#list-all-licenses>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.License.License` """ url_parameters = dict() return github.PaginatedList.PaginatedLis...
[ "def", "get_licenses", "(", "self", ")", ":", "url_parameters", "=", "dict", "(", ")", "return", "github", ".", "PaginatedList", ".", "PaginatedList", "(", "github", ".", "License", ".", "License", ",", "self", ".", "__requester", ",", "\"/licenses\"", ",", ...
31.214286
21.5
def to_dict(self, in_dict=None): """ Turn the Namespace and sub Namespaces back into a native python dictionary. :param in_dict: Do not use, for self recursion :return: python dictionary of this Namespace """ in_dict = in_dict if in_dict else self out_dic...
[ "def", "to_dict", "(", "self", ",", "in_dict", "=", "None", ")", ":", "in_dict", "=", "in_dict", "if", "in_dict", "else", "self", "out_dict", "=", "dict", "(", ")", "for", "k", ",", "v", "in", "in_dict", ".", "items", "(", ")", ":", "if", "isinstan...
31.866667
11.733333
def get_load(jid): ''' Included for API consistency ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id...
[ "def", "get_load", "(", "jid", ")", ":", "options", "=", "_get_options", "(", "ret", "=", "None", ")", "_response", "=", "_request", "(", "\"GET\"", ",", "options", "[", "'url'", "]", "+", "options", "[", "'db'", "]", "+", "'/'", "+", "jid", ")", "...
32.5
19.7
def transform_data(from_client, from_project, from_logstore, from_time, to_time=None, to_client=None, to_project=None, to_logstore=None, shard_list=None, config=None, batch_size=None, compress=None, cg_name...
[ "def", "transform_data", "(", "from_client", ",", "from_project", ",", "from_logstore", ",", "from_time", ",", "to_time", "=", "None", ",", "to_client", "=", "None", ",", "to_project", "=", "None", ",", "to_logstore", "=", "None", ",", "shard_list", "=", "No...
48.818182
28.690909
def grid_prep(self): """ prepare grid-based parameterizations """ if len(self.grid_props) == 0: return if self.grid_geostruct is None: self.logger.warn("grid_geostruct is None,"\ " using ExpVario with contribution=1 and a=(max(delc,delr)*10") ...
[ "def", "grid_prep", "(", "self", ")", ":", "if", "len", "(", "self", ".", "grid_props", ")", "==", "0", ":", "return", "if", "self", ".", "grid_geostruct", "is", "None", ":", "self", ".", "logger", ".", "warn", "(", "\"grid_geostruct is None,\"", "\" usi...
41.357143
20.857143
def select(self, crit, axis=0): """ Return data corresponding to axis labels matching criteria. .. deprecated:: 0.21.0 Use df.loc[df.index.map(crit)] to select via labels Parameters ---------- crit : function To be called on each index (label). S...
[ "def", "select", "(", "self", ",", "crit", ",", "axis", "=", "0", ")", ":", "warnings", ".", "warn", "(", "\"'select' is deprecated and will be removed in a \"", "\"future release. You can use \"", "\".loc[labels.map(crit)] as a replacement\"", ",", "FutureWarning", ",", ...
31.515152
19.878788
def create_object(container, portal_type, **data): """Creates an object slug :returns: The new created content object :rtype: object """ if "id" in data: # always omit the id as senaite LIMS generates a proper one id = data.pop("id") logger.warn("Passed in ID '{}' omitted! ...
[ "def", "create_object", "(", "container", ",", "portal_type", ",", "*", "*", "data", ")", ":", "if", "\"id\"", "in", "data", ":", "# always omit the id as senaite LIMS generates a proper one", "id", "=", "data", ".", "pop", "(", "\"id\"", ")", "logger", ".", "...
34.463415
20.170732
def reset(self): """ Reset this Task to a clean state prior to execution. """ logger.debug('Resetting task {0}'.format(self.name)) self.stdout_file = os.tmpfile() self.stderr_file = os.tmpfile() self.stdout = "" self.stderr = "" self.started_at = None ...
[ "def", "reset", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Resetting task {0}'", ".", "format", "(", "self", ".", "name", ")", ")", "self", ".", "stdout_file", "=", "os", ".", "tmpfile", "(", ")", "self", ".", "stderr_file", "=", "os", "."...
25.666667
18.111111
def get_old_sha(diff_part): """ Returns the SHA for the original file that was changed in a diff part. """ r = re.compile(r'index ([a-fA-F\d]*)') return r.search(diff_part).groups()[0]
[ "def", "get_old_sha", "(", "diff_part", ")", ":", "r", "=", "re", ".", "compile", "(", "r'index ([a-fA-F\\d]*)'", ")", "return", "r", ".", "search", "(", "diff_part", ")", ".", "groups", "(", ")", "[", "0", "]" ]
33.166667
8.5
def main(): """Command line interface for the ``coloredlogs`` program.""" actions = [] try: # Parse the command line arguments. options, arguments = getopt.getopt(sys.argv[1:], 'cdh', [ 'convert', 'to-html', 'demo', 'help', ]) # Map command line options to actions...
[ "def", "main", "(", ")", ":", "actions", "=", "[", "]", "try", ":", "# Parse the command line arguments.", "options", ",", "arguments", "=", "getopt", ".", "getopt", "(", "sys", ".", "argv", "[", "1", ":", "]", ",", "'cdh'", ",", "[", "'convert'", ",",...
35.571429
16.821429
def get_user(self, username): """Get user information. :param str username: User to get info on. """ r = self._query_('/users/%s' % username, 'GET') result = User(r.json()) return result
[ "def", "get_user", "(", "self", ",", "username", ")", ":", "r", "=", "self", ".", "_query_", "(", "'/users/%s'", "%", "username", ",", "'GET'", ")", "result", "=", "User", "(", "r", ".", "json", "(", ")", ")", "return", "result" ]
22.8
18.3
def _setup_output_metrics(self, engine): """Helper method to setup metrics to log """ metrics = {} if self.metric_names is not None: for name in self.metric_names: if name not in engine.state.metrics: warnings.warn("Provided metric name '{}...
[ "def", "_setup_output_metrics", "(", "self", ",", "engine", ")", ":", "metrics", "=", "{", "}", "if", "self", ".", "metric_names", "is", "not", "None", ":", "for", "name", "in", "self", ".", "metric_names", ":", "if", "name", "not", "in", "engine", "."...
42.2
20.25
def get(cls, user_id, client_id): """Get RemoteAccount object for user. :param user_id: User id :param client_id: Client id. :returns: A :class:`invenio_oauthclient.models.RemoteAccount` instance. """ return cls.query.filter_by( user_id=user_id, c...
[ "def", "get", "(", "cls", ",", "user_id", ",", "client_id", ")", ":", "return", "cls", ".", "query", ".", "filter_by", "(", "user_id", "=", "user_id", ",", "client_id", "=", "client_id", ",", ")", ".", "first", "(", ")" ]
31.545455
13.363636
def set_verbosity(v): """Sets the logging verbosity. Causes all messages of level <= v to be logged, and all messages of level > v to be silently discarded. Args: v: int|str, the verbosity level as an integer or string. Legal string values are those that can be coerced to an integer as well as cas...
[ "def", "set_verbosity", "(", "v", ")", ":", "try", ":", "new_level", "=", "int", "(", "v", ")", "except", "ValueError", ":", "new_level", "=", "converter", ".", "ABSL_NAMES", "[", "v", ".", "upper", "(", ")", "]", "FLAGS", ".", "verbosity", "=", "new...
31.9375
21.5
def _audience_condition_deserializer(obj_dict): """ Deserializer defining how dict objects need to be decoded for audience conditions. Args: obj_dict: Dict representing one audience condition. Returns: List consisting of condition key with corresponding value, type and match. """ return [ obj_di...
[ "def", "_audience_condition_deserializer", "(", "obj_dict", ")", ":", "return", "[", "obj_dict", ".", "get", "(", "'name'", ")", ",", "obj_dict", ".", "get", "(", "'value'", ")", ",", "obj_dict", ".", "get", "(", "'type'", ")", ",", "obj_dict", ".", "get...
26.933333
21.933333
def getMaskArray(self, signature): """ Returns the appropriate StaticMask array for the image. """ if signature in self.masklist: mask = self.masklist[signature] else: mask = None return mask
[ "def", "getMaskArray", "(", "self", ",", "signature", ")", ":", "if", "signature", "in", "self", ".", "masklist", ":", "mask", "=", "self", ".", "masklist", "[", "signature", "]", "else", ":", "mask", "=", "None", "return", "mask" ]
34.571429
11
def detach_usb_device(self, id_p, done): """Notification that a VM is going to detach (@a done = @c false) or has already detached (@a done = @c true) the given USB device. When the @a done = @c true request is completed, the VM process will get a :py:func:`IInternalSessionControl.on_usb...
[ "def", "detach_usb_device", "(", "self", ",", "id_p", ",", "done", ")", ":", "if", "not", "isinstance", "(", "id_p", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"id_p can only be an instance of type basestring\"", ")", "if", "not", "isinstance", "(...
42.363636
20.227273
def _check_consumer(self): """ Validates the :attr:`.consumer`. """ # 'magic' using _kwarg method # pylint:disable=no-member if not self.consumer.key: raise ConfigError( 'Consumer key not specified for provider {0}!'.format( ...
[ "def", "_check_consumer", "(", "self", ")", ":", "# 'magic' using _kwarg method", "# pylint:disable=no-member", "if", "not", "self", ".", "consumer", ".", "key", ":", "raise", "ConfigError", "(", "'Consumer key not specified for provider {0}!'", ".", "format", "(", "sel...
30.8125
13.4375
def to_meme(self): """Return motif formatted in MEME format Returns ------- m : str String of motif in MEME format. """ motif_id = self.id.replace(" ", "_") m = "MOTIF %s\n" % motif_id m += "BL MOTIF %s width=0 seqs=0\n"% motif_id ...
[ "def", "to_meme", "(", "self", ")", ":", "motif_id", "=", "self", ".", "id", ".", "replace", "(", "\" \"", ",", "\"_\"", ")", "m", "=", "\"MOTIF %s\\n\"", "%", "motif_id", "m", "+=", "\"BL MOTIF %s width=0 seqs=0\\n\"", "%", "motif_id", "m", "+=", "\"let...
36.642857
20.714286
def extract(self, high_bit, low_bit): """ Operation extract - A cheap hack is implemented: a copy of self is returned if (high_bit - low_bit + 1 == self.bits), which is a ValueSet instance. Otherwise a StridedInterval is returned. :param high_bit: :param low_bit: ...
[ "def", "extract", "(", "self", ",", "high_bit", ",", "low_bit", ")", ":", "if", "high_bit", "-", "low_bit", "+", "1", "==", "self", ".", "bits", ":", "return", "self", ".", "copy", "(", ")", "if", "(", "'global'", "in", "self", ".", "_regions", "an...
31.714286
23.071429
def update_membership(self, contact, group): ''' input: gdata ContactEntry and GroupEntry objects ''' if not contact: log.debug('Not updating membership for EMPTY contact.') return None _uid = contact.email[0].address _gtitle = group.title.text ...
[ "def", "update_membership", "(", "self", ",", "contact", ",", "group", ")", ":", "if", "not", "contact", ":", "log", ".", "debug", "(", "'Not updating membership for EMPTY contact.'", ")", "return", "None", "_uid", "=", "contact", ".", "email", "[", "0", "]"...
37.681818
18.681818
def _handle_inventory(self, inventory_path): """ Scan inventory. As Ansible is a big mess without any kind of preconceived notion of design, there are several (and I use that word lightly) different ways inventory_path can be handled: - a non-executable file: handled as a Ansi...
[ "def", "_handle_inventory", "(", "self", ",", "inventory_path", ")", ":", "self", ".", "log", ".", "debug", "(", "\"Determining type of inventory_path {}\"", ".", "format", "(", "inventory_path", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "inventor...
54.157895
29.789474
def in_dateheure(objet, pattern): """ abstractSearch dans une date-heure datetime.datetime (cf abstractRender.dateheure) """ if objet: pattern = re.sub(" ", '', pattern) objet_str = abstractRender.dateheure(objet) return bool(re.search(pattern, objet_str)) ret...
[ "def", "in_dateheure", "(", "objet", ",", "pattern", ")", ":", "if", "objet", ":", "pattern", "=", "re", ".", "sub", "(", "\" \"", ",", "''", ",", "pattern", ")", "objet_str", "=", "abstractRender", ".", "dateheure", "(", "objet", ")", "return", "bool"...
46.142857
12.142857
def get_dc_inventory(pbclient, dc=None): ''' gets inventory of one data center''' if pbclient is None: raise ValueError("argument 'pbclient' must not be None") if dc is None: raise ValueError("argument 'dc' must not be None") dc_inv = [] # inventory list to return dcid = dc['id'] ...
[ "def", "get_dc_inventory", "(", "pbclient", ",", "dc", "=", "None", ")", ":", "if", "pbclient", "is", "None", ":", "raise", "ValueError", "(", "\"argument 'pbclient' must not be None\"", ")", "if", "dc", "is", "None", ":", "raise", "ValueError", "(", "\"argume...
42.886076
19.341772
def find_enclosing_bracket_left(self, left_ch, right_ch, start_pos=None): """ Find the left bracket enclosing current position. Return the relative position to the cursor position. When `start_pos` is given, don't look past the position. """ if self.current_char == left_...
[ "def", "find_enclosing_bracket_left", "(", "self", ",", "left_ch", ",", "right_ch", ",", "start_pos", "=", "None", ")", ":", "if", "self", ".", "current_char", "==", "left_ch", ":", "return", "0", "if", "start_pos", "is", "None", ":", "start_pos", "=", "0"...
27.321429
19.892857
def from_time( year=None, month=None, day=None, hours=None, minutes=None, seconds=None, microseconds=None, timezone=None ): """Convenience wrapper to take a series of date/time elements and return a WMI time of the form `yyyymmddHHMMSS.mmmmmm+UUU`. All elements may be int, string or omitted altogether. ...
[ "def", "from_time", "(", "year", "=", "None", ",", "month", "=", "None", ",", "day", "=", "None", ",", "hours", "=", "None", ",", "minutes", "=", "None", ",", "seconds", "=", "None", ",", "microseconds", "=", "None", ",", "timezone", "=", "None", "...
36.163265
17.755102
def cut_into_parts(self): # pylint: disable=too-many-branches, too-many-locals, too-many-statements """Cut conf into part for scheduler dispatch. Basically it provides a set of host/services for each scheduler that have no dependencies between them :return: None """ ...
[ "def", "cut_into_parts", "(", "self", ")", ":", "# pylint: disable=too-many-branches, too-many-locals, too-many-statements", "# User must have set a spare if he needed one", "logger", ".", "info", "(", "\"Splitting the configuration into parts:\"", ")", "nb_parts", "=", "0", "for",...
47.711957
21.570652
def update_all(self, *args, **kwargs): """Updates all objects with details given if they match a set of conditions supplied. This method forwards filters and updates directly to the repository. It does not instantiate entities and it does not trigger Entity callbacks or validations. Up...
[ "def", "update_all", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "updated_item_count", "=", "0", "repository", "=", "repo_factory", ".", "get_repository", "(", "self", ".", "_entity_cls", ")", "try", ":", "updated_item_count", "=", "r...
38.818182
27.909091
def update(self, obj, set_fields = None, unset_fields = None, update_obj = True): """ We return the result of the save method (updates are not yet implemented here). """ if set_fields: if isinstance(set_fields,(list,tuple)): set_attributes = {} ...
[ "def", "update", "(", "self", ",", "obj", ",", "set_fields", "=", "None", ",", "unset_fields", "=", "None", ",", "update_obj", "=", "True", ")", ":", "if", "set_fields", ":", "if", "isinstance", "(", "set_fields", ",", "(", "list", ",", "tuple", ")", ...
33.933333
16.333333
def _make_postfixes_2( words_layer ): ''' Provides some post-fixes after the disambiguation. ''' for word_dict in words_layer: for analysis in word_dict[ANALYSIS]: analysis[FORM] = re.sub( '(Sg|Pl)([123])', '\\1 \\2', analysis[FORM] ) return words_layer
[ "def", "_make_postfixes_2", "(", "words_layer", ")", ":", "for", "word_dict", "in", "words_layer", ":", "for", "analysis", "in", "word_dict", "[", "ANALYSIS", "]", ":", "analysis", "[", "FORM", "]", "=", "re", ".", "sub", "(", "'(Sg|Pl)([123])'", ",", "'\\...
46.333333
15.666667
def most_confused(self, min_val:int=1, slice_size:int=1)->Collection[Tuple[str,str,int]]: "Sorted descending list of largest non-diagonal entries of confusion matrix, presented as actual, predicted, number of occurrences." cm = self.confusion_matrix(slice_size=slice_size) np.fill_diagonal(cm, 0)...
[ "def", "most_confused", "(", "self", ",", "min_val", ":", "int", "=", "1", ",", "slice_size", ":", "int", "=", "1", ")", "->", "Collection", "[", "Tuple", "[", "str", ",", "str", ",", "int", "]", "]", ":", "cm", "=", "self", ".", "confusion_matrix"...
71
33.571429
def get_fld2val(self, name, vals): """Describe summary statistics for a list of numbers.""" if vals: return self._init_fld2val_stats(name, vals) return self._init_fld2val_null(name)
[ "def", "get_fld2val", "(", "self", ",", "name", ",", "vals", ")", ":", "if", "vals", ":", "return", "self", ".", "_init_fld2val_stats", "(", "name", ",", "vals", ")", "return", "self", ".", "_init_fld2val_null", "(", "name", ")" ]
42.6
9.8
def _tupleload(l: Loader, value, type_) -> Tuple: """ This loads into something like Tuple[int,str] """ if HAS_TUPLEARGS: args = type_.__args__ else: args = type_.__tuple_params__ if len(args) == 2 and args[1] == ...: # Tuple[something, ...] return tuple(l.load(i, args[0...
[ "def", "_tupleload", "(", "l", ":", "Loader", ",", "value", ",", "type_", ")", "->", "Tuple", ":", "if", "HAS_TUPLEARGS", ":", "args", "=", "type_", ".", "__args__", "else", ":", "args", "=", "type_", ".", "__tuple_params__", "if", "len", "(", "args", ...
47.411765
24
def plotMDS(data, theOrders, theLabels, theColors, theAlphas, theSizes, theMarkers, options): """Plot the MDS data. :param data: the data to plot (MDS values). :param theOrders: the order of the populations to plot. :param theLabels: the names of the populations to plot. :param theColor...
[ "def", "plotMDS", "(", "data", ",", "theOrders", ",", "theLabels", ",", "theColors", ",", "theAlphas", ",", "theSizes", ",", "theMarkers", ",", "options", ")", ":", "# Do the import", "import", "matplotlib", "as", "mpl", "if", "options", ".", "format", "!=",...
35.383838
17.747475
def unload(self, core): """http://wiki.apache.org/solr/CoreAdmin#head-f5055a885932e2c25096a8856de840b06764d143""" params = { 'action': 'UNLOAD', 'core': core, } return self._get_url(self.url, params=params)
[ "def", "unload", "(", "self", ",", "core", ")", ":", "params", "=", "{", "'action'", ":", "'UNLOAD'", ",", "'core'", ":", "core", ",", "}", "return", "self", ".", "_get_url", "(", "self", ".", "url", ",", "params", "=", "params", ")" ]
36.571429
15.285714
def is_extracted(self, file_path): """ Check if the data file is already extracted. """ if os.path.isdir(file_path): self.chatbot.logger.info('File is already extracted') return True return False
[ "def", "is_extracted", "(", "self", ",", "file_path", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "file_path", ")", ":", "self", ".", "chatbot", ".", "logger", ".", "info", "(", "'File is already extracted'", ")", "return", "True", "return", "F...
28
13.777778
def _set_gre_dscp(self, v, load=False): """ Setter method for gre_dscp, mapped from YANG variable /interface/tunnel/gre_dscp (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_gre_dscp is considered as a private method. Backends looking to populate this variabl...
[ "def", "_set_gre_dscp", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base"...
88.545455
41.681818
def ingest_memory(self, memory): """ Transform the memory into bytes :param memory: Compose memory definition. (1g, 24k) :type memory: memory string or integer :return: The memory in bytes :rtype: int """ def lshift(num, shift): return num << ...
[ "def", "ingest_memory", "(", "self", ",", "memory", ")", ":", "def", "lshift", "(", "num", ",", "shift", ")", ":", "return", "num", "<<", "shift", "def", "rshift", "(", "num", ",", "shift", ")", ":", "return", "num", ">>", "shift", "if", "isinstance"...
31.107143
15.107143
def venn2_unweighted(subsets, set_labels=('A', 'B'), set_colors=('r', 'g'), alpha=0.4, normalize_to=1.0, subset_areas=(1, 1, 1), ax=None, subset_label_formatter=None): ''' The version of venn2 without area-weighting. It is implemented as a wrapper around venn2. Namely, venn2 is invoked as usual, but with al...
[ "def", "venn2_unweighted", "(", "subsets", ",", "set_labels", "=", "(", "'A'", ",", "'B'", ")", ",", "set_colors", "=", "(", "'r'", ",", "'g'", ")", ",", "alpha", "=", "0.4", ",", "normalize_to", "=", "1.0", ",", "subset_areas", "=", "(", "1", ",", ...
50.916667
26.666667
def f_get_results(self, fast_access=False, copy=True): """ Returns a dictionary containing the full result names as keys and the corresponding result objects or result data items as values. :param fast_access: Determines whether the result objects or their values are returned ...
[ "def", "f_get_results", "(", "self", ",", "fast_access", "=", "False", ",", "copy", "=", "True", ")", ":", "return", "self", ".", "_return_item_dictionary", "(", "self", ".", "_results", ",", "fast_access", ",", "copy", ")" ]
37.625
27.458333
def _get_dependencies_from_kwargs(self, args): """ Parse keyed arguments """ if not isinstance(args, dict): raise TypeError('"kwargs" must be a dictionary') dependency_names = set() for arg in args.values(): new_names = self._check_arg(arg) dependency...
[ "def", "_get_dependencies_from_kwargs", "(", "self", ",", "args", ")", ":", "if", "not", "isinstance", "(", "args", ",", "dict", ")", ":", "raise", "TypeError", "(", "'\"kwargs\" must be a dictionary'", ")", "dependency_names", "=", "set", "(", ")", "for", "ar...
36.7
10.2
def compose_dynamic_tree(src, target_tree_alias=None, parent_tree_item_alias=None, include_trees=None): """Returns a structure describing a dynamic sitetree.utils The structure can be built from various sources, :param str|iterable src: If a string is passed to `src`, it'll be treated as the name of an app...
[ "def", "compose_dynamic_tree", "(", "src", ",", "target_tree_alias", "=", "None", ",", "parent_tree_item_alias", "=", "None", ",", "include_trees", "=", "None", ")", ":", "def", "result", "(", "sitetrees", "=", "src", ")", ":", "if", "include_trees", "is", "...
40.947368
29.078947
def parse_hpo_phenotypes(hpo_lines): """Parse hpo phenotypes Group the genes that a phenotype is associated to in 'genes' Args: hpo_lines(iterable(str)): A file handle to the hpo phenotypes file Returns: hpo_terms(dict): A dictionary with hpo_ids as keys and terms as v...
[ "def", "parse_hpo_phenotypes", "(", "hpo_lines", ")", ":", "hpo_terms", "=", "{", "}", "LOG", ".", "info", "(", "\"Parsing hpo phenotypes...\"", ")", "for", "index", ",", "line", "in", "enumerate", "(", "hpo_lines", ")", ":", "if", "index", ">", "0", "and"...
32.5
17.722222
def load_zae(file_obj, resolver=None, **kwargs): """ Load a ZAE file, which is just a zipped DAE file. Parameters ------------- file_obj : file object Contains ZAE data resolver : trimesh.visual.Resolver Resolver to load additional assets kwargs : dict Passed to load_colla...
[ "def", "load_zae", "(", "file_obj", ",", "resolver", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# a dict, {file name : file object}", "archive", "=", "util", ".", "decompress", "(", "file_obj", ",", "file_type", "=", "'zip'", ")", "# load the first file wi...
26.771429
16.257143
def check_requires_python(requires_python): # type: (Optional[str]) -> bool """ Check if the python version in use match the `requires_python` specifier. Returns `True` if the version of python in use matches the requirement. Returns `False` if the version of python in use does not matches the ...
[ "def", "check_requires_python", "(", "requires_python", ")", ":", "# type: (Optional[str]) -> bool", "if", "requires_python", "is", "None", ":", "# The package provides no information", "return", "True", "requires_python_specifier", "=", "specifiers", ".", "SpecifierSet", "("...
39.052632
21.894737
def raw_separation(self,mag_1,mag_2,steps=10000): """ Calculate the separation in magnitude-magnitude space between points and isochrone. Uses a dense sampling of the isochrone and calculates the metric distance from any isochrone sample point. Parameters: ----------- mag_1 : T...
[ "def", "raw_separation", "(", "self", ",", "mag_1", ",", "mag_2", ",", "steps", "=", "10000", ")", ":", "# http://stackoverflow.com/q/12653120/", "mag_1", "=", "np", ".", "array", "(", "mag_1", ",", "copy", "=", "False", ",", "ndmin", "=", "1", ")", "mag...
41.15625
24.3125
def plot_sector_exposures_gross(gross_exposures, sector_dict=None, ax=None): """ Plots output of compute_sector_exposures as area charts Parameters ---------- gross_exposures : arrays Arrays of gross sector exposures (output of compute_sector_exposures). sector_dict : dict or OrderedDi...
[ "def", "plot_sector_exposures_gross", "(", "gross_exposures", ",", "sector_dict", "=", "None", ",", "ax", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "if", "sector_dict", "is", "None", ":", "sector_names"...
29.71875
21.34375
def write(url, content, **args): """Put an object into a ftps URL.""" with FTPSResource(url, **args) as resource: resource.write(content)
[ "def", "write", "(", "url", ",", "content", ",", "*", "*", "args", ")", ":", "with", "FTPSResource", "(", "url", ",", "*", "*", "args", ")", "as", "resource", ":", "resource", ".", "write", "(", "content", ")" ]
37.5
6
def spin_z(particles, index): """Generates the spin_z projection operator for a system of N=particles and for the selected spin index name. where index=0..N-1""" mat = np.zeros((2**particles, 2**particles)) for i in range(2**particles): ispin = btest(i, index) if ispin == 1: ...
[ "def", "spin_z", "(", "particles", ",", "index", ")", ":", "mat", "=", "np", ".", "zeros", "(", "(", "2", "**", "particles", ",", "2", "**", "particles", ")", ")", "for", "i", "in", "range", "(", "2", "**", "particles", ")", ":", "ispin", "=", ...
32.333333
14.166667
def convert_filename(txtfilename, outdir='.'): """Convert a .TXT filename to a Therion .TH filename""" return os.path.join(outdir, os.path.basename(txtfilename)).rsplit('.', 1)[0] + '.th'
[ "def", "convert_filename", "(", "txtfilename", ",", "outdir", "=", "'.'", ")", ":", "return", "os", ".", "path", ".", "join", "(", "outdir", ",", "os", ".", "path", ".", "basename", "(", "txtfilename", ")", ")", ".", "rsplit", "(", "'.'", ",", "1", ...
64.333333
18
def determine_inst(i_info, param_str, command): """Determine the instance-id of the target instance. Inspect the number of instance-ids collected and take the appropriate action: exit if no ids, return if single id, and call user_picklist function if multiple ids exist. Args: i_info (dict)...
[ "def", "determine_inst", "(", "i_info", ",", "param_str", ",", "command", ")", ":", "qty_instances", "=", "len", "(", "i_info", ")", "if", "not", "qty_instances", ":", "print", "(", "\"No instances found with parameters: {}\"", ".", "format", "(", "param_str", "...
35.40625
21.8125
def receptive_field(self, X, identities, max_len=10, threshold=0.9, batch_size=1): """ Calculate the receptive field of the SOM on some data. The receptive field is the common...
[ "def", "receptive_field", "(", "self", ",", "X", ",", "identities", ",", "max_len", "=", "10", ",", "threshold", "=", "0.9", ",", "batch_size", "=", "1", ")", ":", "receptive_fields", "=", "defaultdict", "(", "list", ")", "predictions", "=", "self", ".",...
37.558824
20.588235
def mscoco_generator(data_dir, tmp_dir, training, how_many, start_from=0, eos_list=None, vocab_filename=None): """Image generator for MSCOCO captioning problem with token-wise captions. Arg...
[ "def", "mscoco_generator", "(", "data_dir", ",", "tmp_dir", ",", "training", ",", "how_many", ",", "start_from", "=", "0", ",", "eos_list", "=", "None", ",", "vocab_filename", "=", "None", ")", ":", "eos_list", "=", "[", "1", "]", "if", "eos_list", "is",...
42.216867
17.156627
def get_accounts(self, **params): """https://developers.coinbase.com/api/v2#list-accounts""" response = self._get('v2', 'accounts', params=params) return self._make_api_object(response, Account)
[ "def", "get_accounts", "(", "self", ",", "*", "*", "params", ")", ":", "response", "=", "self", ".", "_get", "(", "'v2'", ",", "'accounts'", ",", "params", "=", "params", ")", "return", "self", ".", "_make_api_object", "(", "response", ",", "Account", ...
53.75
10.75
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 _init_client(self, from_archive=False): """Init client""" return AskbotClient(self.url, self.archive, from_archive)
[ "def", "_init_client", "(", "self", ",", "from_archive", "=", "False", ")", ":", "return", "AskbotClient", "(", "self", ".", "url", ",", "self", ".", "archive", ",", "from_archive", ")" ]
33.25
17
def mBank_set_iph_id(transactions, tag, tag_dict, *args): """ mBank Collect uses ID IPH to distinguish between virtual accounts, adding iph_id may be helpful in further processing """ matches = iph_id_re.search(tag_dict[tag.slug]) if matches: # pragma no branch tag_dict['iph_id'] = mat...
[ "def", "mBank_set_iph_id", "(", "transactions", ",", "tag", ",", "tag_dict", ",", "*", "args", ")", ":", "matches", "=", "iph_id_re", ".", "search", "(", "tag_dict", "[", "tag", ".", "slug", "]", ")", "if", "matches", ":", "# pragma no branch", "tag_dict",...
32.454545
17.727273
def pystr(self, min_chars=None, max_chars=20): """ Generates a random string of upper and lowercase letters. :type min_chars: int :type max_chars: int :return: String. Random of random length between min and max characters. """ if min_chars is None: re...
[ "def", "pystr", "(", "self", ",", "min_chars", "=", "None", ",", "max_chars", "=", "20", ")", ":", "if", "min_chars", "is", "None", ":", "return", "\"\"", ".", "join", "(", "self", ".", "random_letters", "(", "length", "=", "max_chars", ")", ")", "el...
39.588235
20.411765
def _to_bel_lines_footer(graph) -> Iterable[str]: """Iterate the lines of a BEL graph's corresponding BEL script's footer. :param pybel.BELGraph graph: A BEL graph """ unqualified_edges_to_serialize = [ (u, v, d) for u, v, d in graph.edges(data=True) if d[RELATION] in UNQUALIFIE...
[ "def", "_to_bel_lines_footer", "(", "graph", ")", "->", "Iterable", "[", "str", "]", ":", "unqualified_edges_to_serialize", "=", "[", "(", "u", ",", "v", ",", "d", ")", "for", "u", ",", "v", ",", "d", "in", "graph", ".", "edges", "(", "data", "=", ...
34.233333
21.2
def cache(self, obj): ''' Store an object in the cache (this allows temporarily assigning a new cache for exploring the DB without affecting the stored version ''' # Check cache path exists for current obj write_path = os.path.join( self.cache_path, obj.org_id ) i...
[ "def", "cache", "(", "self", ",", "obj", ")", ":", "# Check cache path exists for current obj", "write_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "cache_path", ",", "obj", ".", "org_id", ")", "if", "not", "os", ".", "path", ".", "exist...
39
20.875
def set_setting(key, value, qsettings=None): """Set value to QSettings based on key in InaSAFE scope. :param key: Unique key for setting. :type key: basestring :param value: Value to be saved. :type value: QVariant :param qsettings: A custom QSettings to use. If it's not defined, it will ...
[ "def", "set_setting", "(", "key", ",", "value", ",", "qsettings", "=", "None", ")", ":", "full_key", "=", "'%s/%s'", "%", "(", "APPLICATION_NAME", ",", "key", ")", "set_general_setting", "(", "full_key", ",", "value", ",", "qsettings", ")" ]
32.466667
15.6
def to_json(self, include_id: bool = False) -> Mapping[str, str]: """Return the most useful entries as a dictionary. :param include_id: If true, includes the model identifier """ result = { 'keyword': self.keyword, 'name': self.name, 'version'...
[ "def", "to_json", "(", "self", ",", "include_id", ":", "bool", "=", "False", ")", "->", "Mapping", "[", "str", ",", "str", "]", ":", "result", "=", "{", "'keyword'", ":", "self", ".", "keyword", ",", "'name'", ":", "self", ".", "name", ",", "'versi...
26.85
18.4
def jhk_to_imag(jmag,hmag,kmag): '''Converts given J, H, Ks mags to an I magnitude value. Parameters ---------- jmag,hmag,kmag : float 2MASS J, H, Ks mags of the object. Returns ------- float The converted I band magnitude. ''' return convert_constants(jmag,hmag...
[ "def", "jhk_to_imag", "(", "jmag", ",", "hmag", ",", "kmag", ")", ":", "return", "convert_constants", "(", "jmag", ",", "hmag", ",", "kmag", ",", "IJHK", ",", "IJH", ",", "IJK", ",", "IHK", ",", "IJ", ",", "IH", ",", "IK", ")" ]
20.285714
22.47619
def load(self, path): """Load a set of constructs into the CLIPS data base. Constructs can be in text or binary format. The Python equivalent of the CLIPS load command. """ try: self._load_binary(path) except CLIPSError: self._load_text(path)
[ "def", "load", "(", "self", ",", "path", ")", ":", "try", ":", "self", ".", "_load_binary", "(", "path", ")", "except", "CLIPSError", ":", "self", ".", "_load_text", "(", "path", ")" ]
25.5
18.333333
def group_permissions(permissions): """ Groups a permissions list Returns a dictionary, with permission types as keys and sets of entities with access to the resource as values, e.g.: { 'organisation_id': { 'org1': set(['rw', 'r', 'w']), 'org2': set(...
[ "def", "group_permissions", "(", "permissions", ")", ":", "groups", "=", "defaultdict", "(", "lambda", ":", "defaultdict", "(", "set", ")", ")", "for", "p", "in", "sorted", "(", "permissions", ",", "key", "=", "itemgetter", "(", "'type'", ")", ")", ":", ...
32.051282
21.025641
def _unknown_data_size_handler(self, cfg, irsb, irsb_addr, stmt_idx, data_addr, max_size): # pylint:disable=unused-argument """ Return the maximum number of bytes until a potential pointer or a potential sequence is found. :param angr.analyses.CFG cfg: The control flow graph. :param py...
[ "def", "_unknown_data_size_handler", "(", "self", ",", "cfg", ",", "irsb", ",", "irsb_addr", ",", "stmt_idx", ",", "data_addr", ",", "max_size", ")", ":", "# pylint:disable=unused-argument", "sequence_offset", "=", "None", "for", "offset", "in", "range", "(", "1...
37.931818
20.886364
def save(self, data, xparent=None): """ Parses the element from XML to Python. :param data | <variant> xparent | <xml.etree.ElementTree.Element> || None :return <xml.etree.ElementTree.Element> """ if xparent is not None: ...
[ "def", "save", "(", "self", ",", "data", ",", "xparent", "=", "None", ")", ":", "if", "xparent", "is", "not", "None", ":", "elem", "=", "ElementTree", ".", "SubElement", "(", "xparent", ",", "'list'", ")", "else", ":", "elem", "=", "ElementTree", "."...
28.277778
16.277778
def validate(self, validation_instances, metrics, iteration=None): ''' Evaluate this model on `validation_instances` during training and output a report. :param validation_instances: The data to use to validate the model. :type validation_instances: list(instance.Instance) ...
[ "def", "validate", "(", "self", ",", "validation_instances", ",", "metrics", ",", "iteration", "=", "None", ")", ":", "if", "not", "validation_instances", "or", "not", "metrics", ":", "return", "{", "}", "split_id", "=", "'val%s'", "%", "iteration", "if", ...
45.363636
26.090909
def _process_sasl_response(self, stream, element): """Process incoming <sasl:response/> element. [receiving entity only] """ if not self.authenticator: logger.debug("Unexpected SASL response") return False content = element.text.encode("us-ascii") ...
[ "def", "_process_sasl_response", "(", "self", ",", "stream", ",", "element", ")", ":", "if", "not", "self", ".", "authenticator", ":", "logger", ".", "debug", "(", "\"Unexpected SASL response\"", ")", "return", "False", "content", "=", "element", ".", "text", ...
38.62069
16
def _add_file_mask(self, start, method_str, method): """Adds a raw file mask for dynamic requests. Parameters ---------- start : string The URL prefix that must be matched to perform this request. method_str : string The HTTP method for which to trigger ...
[ "def", "_add_file_mask", "(", "self", ",", "start", ",", "method_str", ",", "method", ")", ":", "fm", "=", "self", ".", "_f_mask", ".", "get", "(", "method_str", ",", "[", "]", ")", "fm", ".", "append", "(", "(", "start", ",", "method", ")", ")", ...
45.75
22.821429
def usufyToTextExport(d, fPath=None): """ Workaround to export to a .txt file or to show the information. Args: ----- d: Data to export. fPath: File path for the output file. If None was provided, it will assume that it has to print it. Returns: -------- uni...
[ "def", "usufyToTextExport", "(", "d", ",", "fPath", "=", "None", ")", ":", "# Manual check...", "if", "d", "==", "[", "]", ":", "return", "\"+------------------+\\n| No data found... |\\n+------------------+\"", "import", "pyexcel", "as", "pe", "import", "pyexcel", ...
28.836735
22.714286