text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def sos(self, year): """Returns the SOS (Strength of Schedule) for a team in a year, based on SRS. :year: The year for the season in question. :returns: A float of SOS. """ try: sos_text = self._year_info_pq(year, 'SOS').text() except ValueError: ...
[ "def", "sos", "(", "self", ",", "year", ")", ":", "try", ":", "sos_text", "=", "self", ".", "_year_info_pq", "(", "year", ",", "'SOS'", ")", ".", "text", "(", ")", "except", "ValueError", ":", "return", "None", "m", "=", "re", ".", "search", "(", ...
29.0625
16.8125
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = TextView(self.get_context(), None, d.style or '@attr/textViewStyle')
[ "def", "create_widget", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "self", ".", "widget", "=", "TextView", "(", "self", ".", "get_context", "(", ")", ",", "None", ",", "d", ".", "style", "or", "'@attr/textViewStyle'", ")" ]
32
15.428571
def _get_rvmat(d): ''' d = { 'x': { 'x2': 'x22', 'x1': 'x11' }, 'y': { 'y1': 'v1', 'y2': { 'y4': 'v4', 'y3': 'v3' ...
[ "def", "_get_rvmat", "(", "d", ")", ":", "km", ",", "vm", "=", "_d2kvmatrix", "(", "d", ")", "def", "map_func", "(", "ele", ",", "indexc", ",", "indexr", ")", ":", "return", "(", "_getitem_via_pathlist", "(", "d", ",", "ele", ")", ")", "rvmat", "="...
20.25
20
def CheckEnd(self, filename, clean_lines, linenum, error): """Check end of namespace comments.""" line = clean_lines.raw_lines[linenum] # Check how many lines is enclosed in this namespace. Don't issue # warning for missing namespace comments if there aren't enough # lines. However, do apply chec...
[ "def", "CheckEnd", "(", "self", ",", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "raw_lines", "[", "linenum", "]", "# Check how many lines is enclosed in this namespace. Don't issue", "# warning for missing n...
47.666667
24.215686
def _update_progress_bar(self): # type: (Downloader) -> None """Update progress bar :param Downloader self: this """ blobxfer.operations.progress.update_progress_bar( self._general_options, 'download', self._download_start_time, sel...
[ "def", "_update_progress_bar", "(", "self", ")", ":", "# type: (Downloader) -> None", "blobxfer", ".", "operations", ".", "progress", ".", "update_progress_bar", "(", "self", ".", "_general_options", ",", "'download'", ",", "self", ".", "_download_start_time", ",", ...
32.071429
7.571429
def makedirs(directory): """ Resursively create a named directory. """ parent = os.path.dirname(os.path.abspath(directory)) if not os.path.exists(parent): makedirs(parent) os.mkdir(directory)
[ "def", "makedirs", "(", "directory", ")", ":", "parent", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "directory", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "parent", ")", ":", "makedirs",...
35
11.833333
def set_unix_socket_params(self, abstract=None, permissions=None, owner=None, umask=None): """Sets Unix-socket related params. :param bool abstract: Force UNIX socket into abstract mode (Linux only). :param str permissions: UNIX sockets are filesystem objects that obey UNIX permiss...
[ "def", "set_unix_socket_params", "(", "self", ",", "abstract", "=", "None", ",", "permissions", "=", "None", ",", "owner", "=", "None", ",", "umask", "=", "None", ")", ":", "self", ".", "_set", "(", "'abstract-socket'", ",", "abstract", ",", "cast", "=",...
41.521739
28.652174
def _irc_upper(self, in_string): """Convert us to our upper-case equivalent, given our std.""" conv_string = self._translate(in_string) if self._upper_trans is not None: conv_string = in_string.translate(self._upper_trans) return str.upper(conv_string)
[ "def", "_irc_upper", "(", "self", ",", "in_string", ")", ":", "conv_string", "=", "self", ".", "_translate", "(", "in_string", ")", "if", "self", ".", "_upper_trans", "is", "not", "None", ":", "conv_string", "=", "in_string", ".", "translate", "(", "self",...
48.5
7.333333
def reset_ctx(self, ctx): """Re-assign Parameter to other contexts. Parameters ---------- ctx : Context or list of Context, default ``context.current_context()``. Assign Parameter to given context. If ctx is a list of Context, a copy will be made for each context...
[ "def", "reset_ctx", "(", "self", ",", "ctx", ")", ":", "if", "ctx", "is", "None", ":", "ctx", "=", "[", "context", ".", "current_context", "(", ")", "]", "if", "isinstance", "(", "ctx", ",", "Context", ")", ":", "ctx", "=", "[", "ctx", "]", "if",...
39.304348
17.73913
def _generateModel1(numCategories): """ Generate the initial, first order, and second order transition probabilities for 'model1'. For this model, we generate the following set of sequences: 0-10-15 (1X) 0-11-16 (1X) 0-12-17 (1X) 0-13-18 (1X) 0-14-19 (1X) 1-10-20 (1X) 1-11-21 (1X) 1-12-22 (1X)...
[ "def", "_generateModel1", "(", "numCategories", ")", ":", "# --------------------------------------------------------------------", "# Initial probabilities, 0 and 1 equally likely", "initProb", "=", "numpy", ".", "zeros", "(", "numCategories", ")", "initProb", "[", "0", "]", ...
32.184
19.904
def import_class(class_uri): """ Import a class by string 'from.path.module.class' """ parts = class_uri.split('.') class_name = parts.pop() module_uri = '.'.join(parts) try: module = import_module(module_uri) except ImportError as e: # maybe we are still in a module, t...
[ "def", "import_class", "(", "class_uri", ")", ":", "parts", "=", "class_uri", ".", "split", "(", "'.'", ")", "class_name", "=", "parts", ".", "pop", "(", ")", "module_uri", "=", "'.'", ".", "join", "(", "parts", ")", "try", ":", "module", "=", "impor...
26.1
16.4
def delete_expired_users(self): """ Checks for expired users and delete's the ``User`` associated with it. Skips if the user ``is_staff``. :return: A list containing the deleted users. """ deleted_users = [] for user in get_user_model().objects.filter(is_staff=F...
[ "def", "delete_expired_users", "(", "self", ")", ":", "deleted_users", "=", "[", "]", "for", "user", "in", "get_user_model", "(", ")", ".", "objects", ".", "filter", "(", "is_staff", "=", "False", ",", "is_active", "=", "False", ")", ":", "if", "user", ...
36.266667
16.933333
def getLCDType(self): """Returns LCD type as a string, either monochrome or rgb""" command = '$GE' settings = self.sendCommand(command) flags = int(settings[2], 16) if flags & 0x0100: lcdtype = 'monochrome' else: lcdtype = 'rgb' return lcdtype
[ "def", "getLCDType", "(", "self", ")", ":", "command", "=", "'$GE'", "settings", "=", "self", ".", "sendCommand", "(", "command", ")", "flags", "=", "int", "(", "settings", "[", "2", "]", ",", "16", ")", "if", "flags", "&", "0x0100", ":", "lcdtype", ...
27.4
15
def main(): """Run manager.""" from invenio_base.factory import create_app app = create_app() manager.app = app manager.run()
[ "def", "main", "(", ")", ":", "from", "invenio_base", ".", "factory", "import", "create_app", "app", "=", "create_app", "(", ")", "manager", ".", "app", "=", "app", "manager", ".", "run", "(", ")" ]
23.333333
16
def objects_patch(self, bucket, key, info): """Updates the metadata associated with an object. Args: bucket: the name of the bucket containing the object. key: the key of the object being updated. info: the metadata to update. Returns: A parsed object information dictionary. Rai...
[ "def", "objects_patch", "(", "self", ",", "bucket", ",", "key", ",", "info", ")", ":", "url", "=", "Api", ".", "_ENDPOINT", "+", "(", "Api", ".", "_OBJECT_PATH", "%", "(", "bucket", ",", "Api", ".", "_escape_key", "(", "key", ")", ")", ")", "return...
40.8
19.8
def _set_bucket_dns(self): """Create CNAME for S3 endpoint.""" # Different regions have different s3 endpoint formats dotformat_regions = ["eu-west-2", "eu-central-1", "ap-northeast-2", "ap-south-1", "ca-central-1", "us-east-2"] if self.region in dotformat_regions: s3_endpoin...
[ "def", "_set_bucket_dns", "(", "self", ")", ":", "# Different regions have different s3 endpoint formats", "dotformat_regions", "=", "[", "\"eu-west-2\"", ",", "\"eu-central-1\"", ",", "\"ap-northeast-2\"", ",", "\"ap-south-1\"", ",", "\"ca-central-1\"", ",", "\"us-east-2\"",...
45.95
24
def decode_offset_commit_response(cls, data): """ Decode bytes to an OffsetCommitResponse Arguments: data: bytes to decode """ ((correlation_id,), cur) = relative_unpack('>i', data, 0) ((num_topics,), cur) = relative_unpack('>i', data, cur) for _ in ...
[ "def", "decode_offset_commit_response", "(", "cls", ",", "data", ")", ":", "(", "(", "correlation_id", ",", ")", ",", "cur", ")", "=", "relative_unpack", "(", "'>i'", ",", "data", ",", "0", ")", "(", "(", "num_topics", ",", ")", ",", "cur", ")", "=",...
37.823529
19.235294
def sg_inject(path, mod_name): r"""Converts all functions in the given Python module to sugar functions so that they can be used in a chainable manner. Args: path: A string. Path to the Python module mod_name: A string. The name of the Python module to inject. Returns: None """ ...
[ "def", "sg_inject", "(", "path", ",", "mod_name", ")", ":", "# import module", "import", "sys", "if", "path", "not", "in", "list", "(", "sys", ".", "path", ")", ":", "sys", ".", "path", ".", "append", "(", "path", ")", "globals", "(", ")", "[", "mo...
37.791667
19.583333
def clean(self, initial_epoch): """ Remove entries from database that would get overwritten """ self.db.metrics.delete_many({'run_name': self.model_config.run_name, 'epoch_idx': {'$gt': initial_epoch}})
[ "def", "clean", "(", "self", ",", "initial_epoch", ")", ":", "self", ".", "db", ".", "metrics", ".", "delete_many", "(", "{", "'run_name'", ":", "self", ".", "model_config", ".", "run_name", ",", "'epoch_idx'", ":", "{", "'$gt'", ":", "initial_epoch", "}...
72
27.666667
def _print_stat(self): """ Occasionally print out stats about how fast the files are getting processed """ if ((timezone.utcnow() - self.last_stat_print_time).total_seconds() > self.print_stats_interval): if len(self._file_paths) > 0: self._log...
[ "def", "_print_stat", "(", "self", ")", ":", "if", "(", "(", "timezone", ".", "utcnow", "(", ")", "-", "self", ".", "last_stat_print_time", ")", ".", "total_seconds", "(", ")", ">", "self", ".", "print_stats_interval", ")", ":", "if", "len", "(", "self...
45.555556
16
def _plot_weights(self, show=True): ''' .. warning:: Untested! ''' # Set up the axes fig = pl.figure(figsize=(12, 12)) fig.subplots_adjust(top=0.95, bottom=0.025, left=0.1, right=0.92) fig.canvas.set_window_title( '%s %d' % (self._mission.IDSTRING, s...
[ "def", "_plot_weights", "(", "self", ",", "show", "=", "True", ")", ":", "# Set up the axes", "fig", "=", "pl", ".", "figure", "(", "figsize", "=", "(", "12", ",", "12", ")", ")", "fig", ".", "subplots_adjust", "(", "top", "=", "0.95", ",", "bottom",...
41.944751
17.160221
def enkf(self): """ Loop over time windows and apply da :return: """ for cycle_index, time_point in enumerate(self.timeline): if cycle_index >= len(self.timeline) - 1: # Logging : Last Update cycle has finished break print...
[ "def", "enkf", "(", "self", ")", ":", "for", "cycle_index", ",", "time_point", "in", "enumerate", "(", "self", ".", "timeline", ")", ":", "if", "cycle_index", ">=", "len", "(", "self", ".", "timeline", ")", "-", "1", ":", "# Logging : Last Update cycle has...
39.206897
24.034483
def maybe_reverse_features(self, feature_map): """Reverse features between inputs and targets if the problem is '_rev'.""" if not self._was_reversed: return inputs = feature_map.pop("inputs", None) targets = feature_map.pop("targets", None) inputs_seg = feature_map.pop("inputs_segmentation", N...
[ "def", "maybe_reverse_features", "(", "self", ",", "feature_map", ")", ":", "if", "not", "self", ".", "_was_reversed", ":", "return", "inputs", "=", "feature_map", ".", "pop", "(", "\"inputs\"", ",", "None", ")", "targets", "=", "feature_map", ".", "pop", ...
43.363636
11.5
def normalize_tag(tag): """ Normalize an XML element tree `tag` into the tuple format. The following input formats are accepted: * ElementTree namespaced string, e.g. ``{uri:bar}foo`` * Unnamespaced tags, e.g. ``foo`` * Two-tuples consisting of `namespace_uri` and `localpart`; `namespace_uri` ...
[ "def", "normalize_tag", "(", "tag", ")", ":", "if", "isinstance", "(", "tag", ",", "str", ")", ":", "namespace_uri", ",", "sep", ",", "localname", "=", "tag", ".", "partition", "(", "\"}\"", ")", "if", "sep", ":", "if", "not", "namespace_uri", ".", "...
40.741935
20.419355
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 itemFromLink(self, link): """ @type link: C{unicode} @param link: A webID to translate into an item. @rtype: L{Item} @return: The item to which the given link referred. """ return self.siteStore.getItemByID(self.webTranslator.linkFrom(link))
[ "def", "itemFromLink", "(", "self", ",", "link", ")", ":", "return", "self", ".", "siteStore", ".", "getItemByID", "(", "self", ".", "webTranslator", ".", "linkFrom", "(", "link", ")", ")" ]
32.666667
16.444444
def _unpack_storm_date(date): ''' given a packed storm date field, unpack and return 'YYYY-MM-DD' string. ''' year = (date & 0x7f) + 2000 # 7 bits day = (date >> 7) & 0x01f # 5 bits month = (date >> 12) & 0x0f # 4 bits return "%s-%s-%s" % (year, month, day)
[ "def", "_unpack_storm_date", "(", "date", ")", ":", "year", "=", "(", "date", "&", "0x7f", ")", "+", "2000", "# 7 bits", "day", "=", "(", "date", ">>", "7", ")", "&", "0x01f", "# 5 bits", "month", "=", "(", "date", ">>", "12", ")", "&", "0x0f", "...
38.625
15.875
def transformChildrenFromNative(self, clearBehavior=True): """ Recursively transform native children to vanilla representations. """ for childArray in self.contents.values(): for child in childArray: child = child.transformFromNative() child.tr...
[ "def", "transformChildrenFromNative", "(", "self", ",", "clearBehavior", "=", "True", ")", ":", "for", "childArray", "in", "self", ".", "contents", ".", "values", "(", ")", ":", "for", "child", "in", "childArray", ":", "child", "=", "child", ".", "transfor...
43.090909
10.363636
def drawGrid( self, painter ): """ Draws the rulers for this scene. :param painter | <QPainter> """ # draw the minor grid lines pen = QPen(self.borderColor()) painter.setPen(pen) painter.setBrush(self.baseColor()) ...
[ "def", "drawGrid", "(", "self", ",", "painter", ")", ":", "# draw the minor grid lines\r", "pen", "=", "QPen", "(", "self", ".", "borderColor", "(", ")", ")", "painter", ".", "setPen", "(", "pen", ")", "painter", ".", "setBrush", "(", "self", ".", "baseC...
31.777778
13.055556
def linearize_aliases(self): # type: () -> typing.List[Alias] """ Returns a list of all aliases used in the namespace. The aliases are ordered to ensure that if they reference other aliases those aliases come earlier in the list. """ linearized_aliases = [] ...
[ "def", "linearize_aliases", "(", "self", ")", ":", "# type: () -> typing.List[Alias]", "linearized_aliases", "=", "[", "]", "seen_aliases", "=", "set", "(", ")", "# type: typing.Set[Alias]", "def", "add_alias", "(", "alias", ")", ":", "# type: (Alias) -> None", "if", ...
32.16
13.12
def stream( self, accountID, **kwargs ): """ Get a stream of Transactions for an Account starting from when the request is made. Args: accountID: Account Identifier Returns: v20.response.Response containing the...
[ "def", "stream", "(", "self", ",", "accountID", ",", "*", "*", "kwargs", ")", ":", "request", "=", "Request", "(", "'GET'", ",", "'/v3/accounts/{accountID}/transactions/stream'", ")", "request", ".", "set_path_param", "(", "'accountID'", ",", "accountID", ")", ...
23.323529
21.705882
def commitAndClose(self): """ Commits the data of the sub editor and instructs the delegate to close this ctiEditor. The delegate will emit the closeEditor signal which is connected to the closeEditor method of the ConfigTreeView class. This, in turn will, call the finalize method of ...
[ "def", "commitAndClose", "(", "self", ")", ":", "if", "self", ".", "delegate", ":", "self", ".", "delegate", ".", "commitData", ".", "emit", "(", "self", ")", "self", ".", "delegate", ".", "closeEditor", ".", "emit", "(", "self", ",", "QtWidgets", ".",...
66.352941
36.058824
def find_subclass(cls, name): """Find a subclass with a given name""" if name == cls.__name__: return cls for sc in cls.__sub_classes__: r = sc.find_subclass(name) if r != None: return r
[ "def", "find_subclass", "(", "cls", ",", "name", ")", ":", "if", "name", "==", "cls", ".", "__name__", ":", "return", "cls", "for", "sc", "in", "cls", ".", "__sub_classes__", ":", "r", "=", "sc", ".", "find_subclass", "(", "name", ")", "if", "r", "...
31.875
9
def get(self, repository, snapshot, params=None): """ Retrieve information about a snapshot. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html>`_ :arg repository: A repository name :arg snapshot: A comma-separated list of snapshot names ...
[ "def", "get", "(", "self", ",", "repository", ",", "snapshot", ",", "params", "=", "None", ")", ":", "for", "param", "in", "(", "repository", ",", "snapshot", ")", ":", "if", "param", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value ...
52.789474
22.894737
def signal_stop(self, mode): """Signal postmaster process to stop :returns None if signaled, True if process is already gone, False if error """ if self.is_single_user: logger.warning("Cannot stop server; single-user server is running (PID: {0})".format(self.pid)) ...
[ "def", "signal_stop", "(", "self", ",", "mode", ")", ":", "if", "self", ".", "is_single_user", ":", "logger", ".", "warning", "(", "\"Cannot stop server; single-user server is running (PID: {0})\"", ".", "format", "(", "self", ".", "pid", ")", ")", "return", "Fa...
36.588235
21.941176
def create_form(self, label_columns=None, inc_columns=None, description_columns=None, validators_columns=None, extra_fields=None, filter_rel_fields=None): """ Converts a model to a form given :param label_columns: A dictionary with...
[ "def", "create_form", "(", "self", ",", "label_columns", "=", "None", ",", "inc_columns", "=", "None", ",", "description_columns", "=", "None", ",", "validators_columns", "=", "None", ",", "extra_fields", "=", "None", ",", "filter_rel_fields", "=", "None", ")"...
44.5
18.97619
def run_with_tornado(self): """ runs the tornado/websockets based test server """ from zengine.tornado_server.server import runserver runserver(self.manager.args.addr, int(self.manager.args.port))
[ "def", "run_with_tornado", "(", "self", ")", ":", "from", "zengine", ".", "tornado_server", ".", "server", "import", "runserver", "runserver", "(", "self", ".", "manager", ".", "args", ".", "addr", ",", "int", "(", "self", ".", "manager", ".", "args", "....
38.5
12.5
def fit_general(xy, uv): """ Performs a simple fit for the shift only between matched lists of positions 'xy' and 'uv'. Output: (same as for fit_arrays) ================================= DEVELOPMENT NOTE: Checks need to be put in place to verify that enough o...
[ "def", "fit_general", "(", "xy", ",", "uv", ")", ":", "# Set up products used for computing the fit", "gxy", "=", "uv", ".", "astype", "(", "ndfloat128", ")", "guv", "=", "xy", ".", "astype", "(", "ndfloat128", ")", "Sx", "=", "gxy", "[", ":", ",", "0", ...
32.350877
15
def getService(self, name, auto_execute=True): """ Returns a L{ServiceProxy} for the supplied name. Sets up an object that can have method calls made to it that build the AMF requests. @rtype: L{ServiceProxy} """ if not isinstance(name, basestring): raise Typ...
[ "def", "getService", "(", "self", ",", "name", ",", "auto_execute", "=", "True", ")", ":", "if", "not", "isinstance", "(", "name", ",", "basestring", ")", ":", "raise", "TypeError", "(", "'string type required'", ")", "return", "ServiceProxy", "(", "self", ...
35.909091
17.363636
def contains(self, clr): """ Returns True if the given color is part of this color range. Check whether each h, s, b, a component of the color falls within the defined range for that component. If the given color is grayscale, checks against the definitions for black an...
[ "def", "contains", "(", "self", ",", "clr", ")", ":", "if", "not", "isinstance", "(", "clr", ",", "Color", ")", ":", "return", "False", "if", "not", "isinstance", "(", "clr", ",", "_list", ")", ":", "clr", "=", "[", "clr", "]", "for", "clr", "in"...
30.911765
18.323529
def async_get_ac_states(self, uid, limit=1, offset=0, fields='*'): """Get log entries of a device.""" return (yield from self._get('/pods/{}/acStates'.format(uid), limit=limit, fields=fields, o...
[ "def", "async_get_ac_states", "(", "self", ",", "uid", ",", "limit", "=", "1", ",", "offset", "=", "0", ",", "fields", "=", "'*'", ")", ":", "return", "(", "yield", "from", "self", ".", "_get", "(", "'/pods/{}/acStates'", ".", "format", "(", "uid", "...
54.833333
14.5
def format_sentence(sentence): ''' fix display formatting of a sentence array ''' for index, word in enumerate(sentence): if word == 'a' and index + 1 < len(sentence) and \ re.match(r'^[aeiou]', sentence[index + 1]) and not \ re.match(r'^uni', sentence[index + 1]): ...
[ "def", "format_sentence", "(", "sentence", ")", ":", "for", "index", ",", "word", "in", "enumerate", "(", "sentence", ")", ":", "if", "word", "==", "'a'", "and", "index", "+", "1", "<", "len", "(", "sentence", ")", "and", "re", ".", "match", "(", "...
43.181818
12.272727
def comply(self, path): """Issues a chown and chmod to the file paths specified.""" utils.ensure_permissions(path, self.user.pw_name, self.group.gr_name, self.mode)
[ "def", "comply", "(", "self", ",", "path", ")", ":", "utils", ".", "ensure_permissions", "(", "path", ",", "self", ".", "user", ".", "pw_name", ",", "self", ".", "group", ".", "gr_name", ",", "self", ".", "mode", ")" ]
52.5
14.25
def unpack(rv): """Unpack the response from a view. :param rv: the view response :type rv: either a :class:`werkzeug.wrappers.Response` or a tuple of (data, status_code, headers) """ if isinstance(rv, ResponseBase): return rv status = headers = None if isinstance(rv, tuple...
[ "def", "unpack", "(", "rv", ")", ":", "if", "isinstance", "(", "rv", ",", "ResponseBase", ")", ":", "return", "rv", "status", "=", "headers", "=", "None", "if", "isinstance", "(", "rv", ",", "tuple", ")", ":", "rv", ",", "status", ",", "headers", "...
25.285714
20.047619
def model_at_upper_sigma_limit(self, sigma_limit): """Setup 1D vectors of the upper and lower limits of the multinest nlo. These are generated at an input limfrac, which gives the percentage of 1d posterior weighted samples within \ each parameter estimate Parameters ----------...
[ "def", "model_at_upper_sigma_limit", "(", "self", ",", "sigma_limit", ")", ":", "return", "list", "(", "map", "(", "lambda", "param", ":", "param", "[", "1", "]", ",", "self", ".", "model_at_sigma_limit", "(", "sigma_limit", ")", ")", ")" ]
44.384615
29.461538
def create_query(key, person, event=None, timestamp=None, identity=None, properties=None): """Build and encode query string. :param key: API key for product, found on the "KISSmetrics Settings". :param person: individual performing `event` :param event: event name that ...
[ "def", "create_query", "(", "key", ",", "person", ",", "event", "=", "None", ",", "timestamp", "=", "None", ",", "identity", "=", "None", ",", "properties", "=", "None", ")", ":", "if", "properties", "is", "None", ":", "properties", "=", "{", "}", "q...
31.25
16.694444
def _consolidate(self, inplace=False): """ Compute NDFrame with "consolidated" internals (data of each dtype grouped together in a single ndarray). Parameters ---------- inplace : boolean, default False If False return new object, otherwise modify existing ob...
[ "def", "_consolidate", "(", "self", ",", "inplace", "=", "False", ")", ":", "inplace", "=", "validate_bool_kwarg", "(", "inplace", ",", "'inplace'", ")", "if", "inplace", ":", "self", ".", "_consolidate_inplace", "(", ")", "else", ":", "f", "=", "lambda", ...
33
17.190476
def find_by_index(self, cls, index_name, value): """Required functionality.""" return self._find(cls, {index_name: str(value)})
[ "def", "find_by_index", "(", "self", ",", "cls", ",", "index_name", ",", "value", ")", ":", "return", "self", ".", "_find", "(", "cls", ",", "{", "index_name", ":", "str", "(", "value", ")", "}", ")" ]
47
8
def delete_media_service_rg(access_token, subscription_id, rgname, msname): '''Delete a media service. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. msname (str): Media service...
[ "def", "delete_media_service_rg", "(", "access_token", ",", "subscription_id", ",", "rgname", ",", "msname", ")", ":", "endpoint", "=", "''", ".", "join", "(", "[", "get_rm_endpoint", "(", ")", ",", "'/subscriptions/'", ",", "subscription_id", ",", "'/resourceGr...
38
20.222222
def get_cost(self, *args, **kwargs): """Get cost function This method calculates the current cost and tests for convergence Returns ------- bool result of the convergence test """ # Check if the cost should be calculated if self._iteration % self._cost...
[ "def", "get_cost", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Check if the cost should be calculated", "if", "self", ".", "_iteration", "%", "self", ".", "_cost_interval", ":", "test_result", "=", "False", "else", ":", "if", "self",...
24.583333
21.222222
def create_pool_b( dsn=None, *, min_size=10, max_size=10, max_queries=50000, max_inactive_connection_lifetime=300.0, setup=None, init=None, loop=None, connection_class=BuildPgConnection, **connect_kwargs, ): """ Create a connection pool. Can be used either with a...
[ "def", "create_pool_b", "(", "dsn", "=", "None", ",", "*", ",", "min_size", "=", "10", ",", "max_size", "=", "10", ",", "max_queries", "=", "50000", ",", "max_inactive_connection_lifetime", "=", "300.0", ",", "setup", "=", "None", ",", "init", "=", "None...
25.171429
21.914286
def plane_intersection(strike1, dip1, strike2, dip2): """ Finds the intersection of two planes. Returns a plunge/bearing of the linear intersection of the two planes. Also accepts sequences of strike1s, dip1s, strike2s, dip2s. Parameters ---------- strike1, dip1 : numbers or sequences of n...
[ "def", "plane_intersection", "(", "strike1", ",", "dip1", ",", "strike2", ",", "dip2", ")", ":", "norm1", "=", "sph2cart", "(", "*", "pole", "(", "strike1", ",", "dip1", ")", ")", "norm2", "=", "sph2cart", "(", "*", "pole", "(", "strike2", ",", "dip2...
36.185185
19.444444
def request(self, method, url, headers=None, raise_exception=True, **kwargs): """Main method for routing HTTP requests to the configured Vault base_uri. :param method: HTTP method to use with the request. E.g., GET, POST, etc. :type method: str :param url: Partial URL path to send the r...
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "headers", "=", "None", ",", "raise_exception", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "'//'", "in", "url", ":", "# Vault CLI treats a double forward slash ('//') as a single forward s...
39.864407
24.457627
def set_data(self, pos=None, color=None): """Set the data Parameters ---------- pos : list, tuple or numpy array Bounds of the region along the axis. len(pos) must be >=2. color : list, tuple, or array The color to use when drawing the line. It must have ...
[ "def", "set_data", "(", "self", ",", "pos", "=", "None", ",", "color", "=", "None", ")", ":", "new_pos", "=", "self", ".", "_pos", "new_color", "=", "self", ".", "_color", "if", "pos", "is", "not", "None", ":", "num_elements", "=", "len", "(", "pos...
40.303571
17.089286
def main(): """ NAME make_magic_plots.py DESCRIPTION inspects magic directory for available data and makes plots SYNTAX make_magic_plots.py [command line options] INPUT magic files OPTIONS -h prints help message and quits -f FILE specifies inpu...
[ "def", "main", "(", ")", ":", "if", "'-h'", "in", "sys", ".", "argv", ":", "print", "(", "main", ".", "__doc__", ")", "sys", ".", "exit", "(", ")", "# reset log files", "for", "fname", "in", "[", "'log.txt'", ",", "'errors.txt'", "]", ":", "f", "="...
42.703271
19.081776
def route(self, rule, **options): """A decorator that is used to register a view function for a given URL rule. This does the same thing as :meth:`add_url_rule` but is intended for decorator usage:: @app.route('/') def index(): return 'Hello World' ...
[ "def", "route", "(", "self", ",", "rule", ",", "*", "*", "options", ")", ":", "def", "decorator", "(", "f", ")", ":", "endpoint", "=", "options", ".", "pop", "(", "'endpoint'", ",", "None", ")", "self", ".", "add_update_rule", "(", "rule", ",", "en...
52.884615
20.423077
def TR(self,**kwargs): #pragma: no cover """ NAME: TR PURPOSE: Calculate the radial period for a power-law rotation curve INPUT: scipy.integrate.quadrature keywords OUTPUT: T_R(R,vT,vT)*vc/ro + estimate of the error HISTORY: ...
[ "def", "TR", "(", "self", ",", "*", "*", "kwargs", ")", ":", "#pragma: no cover", "if", "hasattr", "(", "self", ",", "'_TR'", ")", ":", "return", "self", ".", "_TR", "(", "rperi", ",", "rap", ")", "=", "self", ".", "calcRapRperi", "(", "*", "*", ...
37.142857
16.571429
def findNestedNamespaces(self, lst): ''' Recursive helper function for finding nested namespaces. If this node is a namespace node, it is appended to ``lst``. Each node also calls each of its child ``findNestedNamespaces`` with the same list. :Parameters: ``lst`` (...
[ "def", "findNestedNamespaces", "(", "self", ",", "lst", ")", ":", "if", "self", ".", "kind", "==", "\"namespace\"", ":", "lst", ".", "append", "(", "self", ")", "for", "c", "in", "self", ".", "children", ":", "c", ".", "findNestedNamespaces", "(", "lst...
37.785714
20.928571
def set_shared_config(cls, config): """ This allows to set a config that will be used when calling ``shared_blockchain_instance`` and allows to define the configuration without requiring to actually create an instance """ assert isinstance(config, dict) cls._share...
[ "def", "set_shared_config", "(", "cls", ",", "config", ")", ":", "assert", "isinstance", "(", "config", ",", "dict", ")", "cls", ".", "_sharedInstance", ".", "config", ".", "update", "(", "config", ")", "# if one is already set, delete", "if", "cls", ".", "_...
47.1
8.4
def fit_radius_from_potentials(z, SampleFreq, Damping, HistBins=100, show_fig=False): """ Fits the dynamical potential to the Steady State Potential by varying the Radius. z : ndarray Position data SampleFreq : float frequency at which the position data was sampled ...
[ "def", "fit_radius_from_potentials", "(", "z", ",", "SampleFreq", ",", "Damping", ",", "HistBins", "=", "100", ",", "show_fig", "=", "False", ")", ":", "dt", "=", "1", "/", "SampleFreq", "boltzmann", "=", "Boltzmann", "temp", "=", "300", "# why halved??", ...
33.15873
18.428571
def euler_number(self): """ Return the Euler characteristic (a topological invariant) for the mesh In order to guarantee correctness, this should be called after remove_unreferenced_vertices Returns ---------- euler_number : int Topological invariant ...
[ "def", "euler_number", "(", "self", ")", ":", "euler", "=", "int", "(", "self", ".", "referenced_vertices", ".", "sum", "(", ")", "-", "len", "(", "self", ".", "edges_unique", ")", "+", "len", "(", "self", ".", "faces", ")", ")", "return", "euler" ]
31.4
15.933333
def get_lon_variable(nc): ''' Returns the variable for longitude :param netCDF4.Dataset nc: netCDF dataset ''' if 'longitude' in nc.variables: return 'longitude' longitudes = nc.get_variables_by_attributes(standard_name="longitude") if longitudes: return longitudes[0].name ...
[ "def", "get_lon_variable", "(", "nc", ")", ":", "if", "'longitude'", "in", "nc", ".", "variables", ":", "return", "'longitude'", "longitudes", "=", "nc", ".", "get_variables_by_attributes", "(", "standard_name", "=", "\"longitude\"", ")", "if", "longitudes", ":"...
26.916667
19.583333
def bind(self, environ, app=None): """ Bind a new WSGI enviroment and clear out all previously computed attributes. This is done automatically for the global `bottle.request` instance on every request. """ if isinstance(environ, Request): # Recycl...
[ "def", "bind", "(", "self", ",", "environ", ",", "app", "=", "None", ")", ":", "if", "isinstance", "(", "environ", ",", "Request", ")", ":", "# Recycle already parsed content", "for", "key", "in", "self", ".", "__dict__", ":", "#TODO: Test this", "setattr", ...
45.368421
17.315789
def makePlot(gmag, pdf=False, png=False, rvs=False): """ Make a plot of a Mv vs (V-I) colour magnitude diagram containing lines of constant distance for stars at G=20. This will give an idea of the reach of Gaia. Parameters ---------- args - command line arguments """ vmini = np.linspace(-0.5,4.0,100)...
[ "def", "makePlot", "(", "gmag", ",", "pdf", "=", "False", ",", "png", "=", "False", ",", "rvs", "=", "False", ")", ":", "vmini", "=", "np", ".", "linspace", "(", "-", "0.5", ",", "4.0", ",", "100", ")", "if", "(", "rvs", ")", ":", "gminv", "=...
33.243902
21.634146
def _parse_options(): """Parses landslide's command line options""" parser = OptionParser( usage="%prog [options] input.md ...", description="Generates an HTML5 or PDF " "slideshow from Markdown or other formats", epilog="Note: PDF export requires the `prince` progra...
[ "def", "_parse_options", "(", ")", ":", "parser", "=", "OptionParser", "(", "usage", "=", "\"%prog [options] input.md ...\"", ",", "description", "=", "\"Generates an HTML5 or PDF \"", "\"slideshow from Markdown or other formats\"", ",", "epilog", "=", "\"Note: PDF export req...
28.176471
20.345588
def intersect(self, other): """ self와 other 키가 동일한 아이템의 dictobj :type other: dict :rtype: dictobj: """ return DictObj({k: self[k] for k in self if k in other})
[ "def", "intersect", "(", "self", ",", "other", ")", ":", "return", "DictObj", "(", "{", "k", ":", "self", "[", "k", "]", "for", "k", "in", "self", "if", "k", "in", "other", "}", ")" ]
28.714286
9.857143
def from_ewif_file(path: str, password: str) -> SigningKeyType: """ Return SigningKey instance from Duniter EWIF file :param path: Path to EWIF file :param password: Password of the encrypted seed """ with open(path, 'r') as fh: wif_content = fh.read() ...
[ "def", "from_ewif_file", "(", "path", ":", "str", ",", "password", ":", "str", ")", "->", "SigningKeyType", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "fh", ":", "wif_content", "=", "fh", ".", "read", "(", ")", "# check data field", "rege...
33.842105
16.157895
def max_brightness(self): """ Returns the maximum allowable brightness value. """ self._max_brightness, value = self.get_cached_attr_int(self._max_brightness, 'max_brightness') return value
[ "def", "max_brightness", "(", "self", ")", ":", "self", ".", "_max_brightness", ",", "value", "=", "self", ".", "get_cached_attr_int", "(", "self", ".", "_max_brightness", ",", "'max_brightness'", ")", "return", "value" ]
37.333333
18.666667
def sort_versions(versions=(), reverse=False, sep=u'.'): """Sort a list of version number strings. This function ensures that the package sorting based on number name is performed correctly when including alpha, dev rc1 etc... """ if versions == []: return [] digits = u'012345...
[ "def", "sort_versions", "(", "versions", "=", "(", ")", ",", "reverse", "=", "False", ",", "sep", "=", "u'.'", ")", ":", "if", "versions", "==", "[", "]", ":", "return", "[", "]", "digits", "=", "u'0123456789'", "def", "toint", "(", "x", ")", ":", ...
30.530303
17.106061
def _fill(self, values): """Add extra values to fill the line""" zero = self.view.y(min(max(self.zero, self._box.ymin), self._box.ymax)) # Check to see if the data has been padded with "none's" # Fill doesn't work correctly otherwise end = len(values) - 1 while end > 0: ...
[ "def", "_fill", "(", "self", ",", "values", ")", ":", "zero", "=", "self", ".", "view", ".", "y", "(", "min", "(", "max", "(", "self", ".", "zero", ",", "self", ".", "_box", ".", "ymin", ")", ",", "self", ".", "_box", ".", "ymax", ")", ")", ...
38.62069
18.103448
def _bar(s, align, colors, width=100, vmin=None, vmax=None): """ Draw bar chart in dataframe cells. """ # Get input value range. smin = s.min() if vmin is None else vmin if isinstance(smin, ABCSeries): smin = smin.min() smax = s.max() if vmax is None e...
[ "def", "_bar", "(", "s", ",", "align", ",", "colors", ",", "width", "=", "100", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ")", ":", "# Get input value range.", "smin", "=", "s", ".", "min", "(", ")", "if", "vmin", "is", "None", "else", ...
34.649123
15.385965
def quote_html(html, limit=1000): """ Like quote(), but takes an HTML message as an argument. The limit param represents the maximum number of lines to traverse until quoting the rest of the markup. Lines are separated by block elements or <br>. """ from . import _html tree = _html.get_html...
[ "def", "quote_html", "(", "html", ",", "limit", "=", "1000", ")", ":", "from", ".", "import", "_html", "tree", "=", "_html", ".", "get_html_tree", "(", "html", ")", "start_refs", ",", "end_refs", ",", "lines", "=", "_html", ".", "get_line_info", "(", "...
35.62963
23.333333
def create_features(bam_in, loci_file, reference, out_dir): """ Use feature extraction module from CoRaL """ lenvec_plus = op.join(out_dir, 'genomic_lenvec.plus') lenvec_minus = op.join(out_dir, 'genomic_lenvec.minus') compute_genomic_cmd = ("compute_genomic_lenvectors " ...
[ "def", "create_features", "(", "bam_in", ",", "loci_file", ",", "reference", ",", "out_dir", ")", ":", "lenvec_plus", "=", "op", ".", "join", "(", "out_dir", ",", "'genomic_lenvec.plus'", ")", "lenvec_minus", "=", "op", ".", "join", "(", "out_dir", ",", "'...
51.073171
17.804878
def parse_headers(lines, offset=0): """ Parse the headers in a STOMP response :param list(str) lines: the lines received in the message response :param int offset: the starting line number :rtype: dict(str,str) """ headers = {} for header_line in lines[offset:]: header_match = ...
[ "def", "parse_headers", "(", "lines", ",", "offset", "=", "0", ")", ":", "headers", "=", "{", "}", "for", "header_line", "in", "lines", "[", "offset", ":", "]", ":", "header_match", "=", "HEADER_LINE_RE", ".", "match", "(", "header_line", ")", "if", "h...
33.3
14
def com_google_fonts_check_name_description_max_length(ttFont): """Description strings in the name table must not exceed 200 characters.""" failed = False for name in ttFont['name'].names: if (name.nameID == NameID.DESCRIPTION and len(name.string.decode(name.getEncoding())) > 200): failed = True...
[ "def", "com_google_fonts_check_name_description_max_length", "(", "ttFont", ")", ":", "failed", "=", "False", "for", "name", "in", "ttFont", "[", "'name'", "]", ".", "names", ":", "if", "(", "name", ".", "nameID", "==", "NameID", ".", "DESCRIPTION", "and", "...
45.9
22.05
def _parameterize_string(raw): """Substitute placeholders in a string using CloudFormation references Args: raw (`str`): String to be processed. Byte strings are not supported; decode them before passing them to this function. Returns: `str` | :class:`troposphere.GenericHelperFn`: ...
[ "def", "_parameterize_string", "(", "raw", ")", ":", "parts", "=", "[", "]", "s_index", "=", "0", "for", "match", "in", "_PARAMETER_PATTERN", ".", "finditer", "(", "raw", ")", ":", "parts", ".", "append", "(", "raw", "[", "s_index", ":", "match", ".", ...
34.785714
23.892857
def _find_blob_start(self): """Find first blob from selection. """ # Convert input frequencies into what their corresponding channel number would be. self._setup_chans() # Check which is the blob time offset blob_time_start = self.t_start # Check which is the b...
[ "def", "_find_blob_start", "(", "self", ")", ":", "# Convert input frequencies into what their corresponding channel number would be.", "self", ".", "_setup_chans", "(", ")", "# Check which is the blob time offset", "blob_time_start", "=", "self", ".", "t_start", "# Check which i...
30.875
22.9375
def _to_free_energy(z, minener_zero=False): """Compute free energies from histogram counts. Parameters ---------- z : ndarray(T) Histogram counts. minener_zero : boolean, optional, default=False Shifts the energy minimum to zero. Returns ------- free_energy : ndarray(T)...
[ "def", "_to_free_energy", "(", "z", ",", "minener_zero", "=", "False", ")", ":", "pi", "=", "_to_density", "(", "z", ")", "free_energy", "=", "_np", ".", "inf", "*", "_np", ".", "ones", "(", "shape", "=", "z", ".", "shape", ")", "nonzero", "=", "pi...
26.608696
17.826087
def active(self): """Returns all outlets that are currently active and have sales.""" qs = self.get_queryset() return qs.filter( models.Q( models.Q(start_date__isnull=True) | models.Q(start_date__lte=now().date()) ) & models.Q( ...
[ "def", "active", "(", "self", ")", ":", "qs", "=", "self", ".", "get_queryset", "(", ")", "return", "qs", ".", "filter", "(", "models", ".", "Q", "(", "models", ".", "Q", "(", "start_date__isnull", "=", "True", ")", "|", "models", ".", "Q", "(", ...
34.230769
15.538462
def _open_file_in_editor(self, filename): """ Call editor executable. Return True when we received a zero return code. """ # If the 'VISUAL' or 'EDITOR' environment variable has been set, use that. # Otherwise, fall back to the first available editor that we can find. ...
[ "def", "_open_file_in_editor", "(", "self", ",", "filename", ")", ":", "# If the 'VISUAL' or 'EDITOR' environment variable has been set, use that.", "# Otherwise, fall back to the first available editor that we can find.", "visual", "=", "os", ".", "environ", ".", "get", "(", "'V...
29.583333
19.972222
def _GetProxies(self): """Gather a list of proxies to use.""" # Detect proxies from the OS environment. result = client_utils.FindProxies() # Also try to connect directly if all proxies fail. result.append("") # Also try all proxies configured in the config system. result.extend(config.CON...
[ "def", "_GetProxies", "(", "self", ")", ":", "# Detect proxies from the OS environment.", "result", "=", "client_utils", ".", "FindProxies", "(", ")", "# Also try to connect directly if all proxies fail.", "result", ".", "append", "(", "\"\"", ")", "# Also try all proxies c...
29.666667
19.666667
def init_megno(self, seed=None): """ This function initialises the chaos indicator MEGNO particles and enables their integration. MEGNO is short for Mean Exponential Growth of Nearby orbits. It can be used to test if a system is chaotic or not. In the backend, the integrator is integrat...
[ "def", "init_megno", "(", "self", ",", "seed", "=", "None", ")", ":", "if", "seed", "is", "None", ":", "clibrebound", ".", "reb_tools_megno_init", "(", "byref", "(", "self", ")", ")", "else", ":", "clibrebound", ".", "reb_tools_megno_init_seed", "(", "byre...
54.263158
36.263158
def _debug(self, message, load=False, no_prefix=False): """ Output debug information """ if self.args.debug_analysis: if load: message = '\r\n'.join( ['# ' + line for line in message.strip().split('\r\n')] ) print '{0}\n{1}\...
[ "def", "_debug", "(", "self", ",", "message", ",", "load", "=", "False", ",", "no_prefix", "=", "False", ")", ":", "if", "self", ".", "args", ".", "debug_analysis", ":", "if", "load", ":", "message", "=", "'\\r\\n'", ".", "join", "(", "[", "'# '", ...
43.466667
16.533333
def exists(self, bbox_or_slices): """ Produce a summary of whether all the requested chunks exist. bbox_or_slices: accepts either a Bbox or a tuple of slices representing the requested volume. Returns: { chunk_file_name: boolean, ... } """ if type(bbox_or_slices) is Bbox: requested...
[ "def", "exists", "(", "self", ",", "bbox_or_slices", ")", ":", "if", "type", "(", "bbox_or_slices", ")", "is", "Bbox", ":", "requested_bbox", "=", "bbox_or_slices", "else", ":", "(", "requested_bbox", ",", "_", ",", "_", ")", "=", "self", ".", "__interpr...
39.210526
19.210526
def calculate_size(transaction_id, thread_id): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(transaction_id) data_size += LONG_SIZE_IN_BYTES return data_size
[ "def", "calculate_size", "(", "transaction_id", ",", "thread_id", ")", ":", "data_size", "=", "0", "data_size", "+=", "calculate_size_str", "(", "transaction_id", ")", "data_size", "+=", "LONG_SIZE_IN_BYTES", "return", "data_size" ]
35.833333
10.833333
def commit(self): """Send buffered requests and refresh all indexes.""" self.send_buffered_operations() retry_until_ok(self.elastic.indices.refresh, index="")
[ "def", "commit", "(", "self", ")", ":", "self", ".", "send_buffered_operations", "(", ")", "retry_until_ok", "(", "self", ".", "elastic", ".", "indices", ".", "refresh", ",", "index", "=", "\"\"", ")" ]
44.75
11.5
def sanitize(func): """ NFC is the normalization form recommended by W3C. """ def wrapper(*args, **kwargs): return normalize('NFC', func(*args, **kwargs)) return wrapper
[ "def", "sanitize", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "normalize", "(", "'NFC'", ",", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "return", "wrapper" ]
30.833333
17.333333
def mol_from_file(path, assign_descriptors=True): """Parse CTAB file and return first one as a Compound object.""" cs = mols_from_file(path, False, assign_descriptors) return next(cs)
[ "def", "mol_from_file", "(", "path", ",", "assign_descriptors", "=", "True", ")", ":", "cs", "=", "mols_from_file", "(", "path", ",", "False", ",", "assign_descriptors", ")", "return", "next", "(", "cs", ")" ]
48
11.5
def config(redirect_url=None, custom_init='', custom_options='', **kwargs): """Initialize dropzone configuration. .. versionadded:: 1.4.4 :param redirect_url: The URL to redirect when upload complete. :param custom_init: Custom javascript code in ``init: function() {}``. :param...
[ "def", "config", "(", "redirect_url", "=", "None", ",", "custom_init", "=", "''", ",", "custom_options", "=", "''", ",", "*", "*", "kwargs", ")", ":", "if", "custom_init", "and", "not", "custom_init", ".", "strip", "(", ")", ".", "endswith", "(", "';'"...
47.429577
27.359155
def prune_cached(values): """Remove the items that have already been cached.""" import os config_path = os.path.expanduser('~/.config/blockade') file_path = os.path.join(config_path, 'cache.txt') if not os.path.isfile(file_path): return values cached = [x.strip() for x in open(file_path,...
[ "def", "prune_cached", "(", "values", ")", ":", "import", "os", "config_path", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.config/blockade'", ")", "file_path", "=", "os", ".", "path", ".", "join", "(", "config_path", ",", "'cache.txt'", ")", "if",...
33.266667
15.6
def get_division(self, obj): """Division.""" if self.context.get("division"): return DivisionSerializer(self.context.get("division")).data else: if obj.slug == "senate": return DivisionSerializer(obj.jurisdiction.division).data else: ...
[ "def", "get_division", "(", "self", ",", "obj", ")", ":", "if", "self", ".", "context", ".", "get", "(", "\"division\"", ")", ":", "return", "DivisionSerializer", "(", "self", ".", "context", ".", "get", "(", "\"division\"", ")", ")", ".", "data", "els...
36.421053
19.947368
def post(self): """Handle post request.""" client_customer_id = self.request.get('clientCustomerId') campaign_id = self.request.get('campaignId') if not client_customer_id or not campaign_id: self.redirect('/') else: self.redirect('/showAdGroups?clientCustomerId=%s&campaignId=%s' ...
[ "def", "post", "(", "self", ")", ":", "client_customer_id", "=", "self", ".", "request", ".", "get", "(", "'clientCustomerId'", ")", "campaign_id", "=", "self", ".", "request", ".", "get", "(", "'campaignId'", ")", "if", "not", "client_customer_id", "or", ...
40.111111
17.222222
def iterifs(physical=True): ''' Iterate over all the interfaces in the system. If physical is true, then return only real physical interfaces (not 'lo', etc).''' net_files = os.listdir(SYSFS_NET_PATH) interfaces = set() virtual = set() for d in net_files: path = os.path.join(SYSFS_NE...
[ "def", "iterifs", "(", "physical", "=", "True", ")", ":", "net_files", "=", "os", ".", "listdir", "(", "SYSFS_NET_PATH", ")", "interfaces", "=", "set", "(", ")", "virtual", "=", "set", "(", ")", "for", "d", "in", "net_files", ":", "path", "=", "os", ...
40.611111
20.388889
def add_team_member(self, account_id=None, email_address=None): ''' Add or invite a user to your Team Args: account_id (str): The id of the account of the user to invite to your team. email_address (str): The email address of the account to invite to your team. The ac...
[ "def", "add_team_member", "(", "self", ",", "account_id", "=", "None", ",", "email_address", "=", "None", ")", ":", "return", "self", ".", "_add_remove_team_member", "(", "self", ".", "TEAM_ADD_MEMBER_URL", ",", "email_address", ",", "account_id", ")" ]
37.785714
39.928571
def try_eval(self): """ Recursively evals the node. Returns None if it is still unresolved. """ item = self.symbol.item if isinstance(item, int): return item if isinstance(item, Label): if item.defined: if isinstance(item.value, E...
[ "def", "try_eval", "(", "self", ")", ":", "item", "=", "self", ".", "symbol", ".", "item", "if", "isinstance", "(", "item", ",", "int", ")", ":", "return", "item", "if", "isinstance", "(", "item", ",", "Label", ")", ":", "if", "item", ".", "defined...
28.659091
19.181818
def deprecated(message): """ Decorator for deprecating functions and methods. :: @deprecated("'foo' has been deprecated in favour of 'bar'") def foo(x): pass """ def f__(f): def f_(*args, **kwargs): from warnings import warn warn(message, ca...
[ "def", "deprecated", "(", "message", ")", ":", "def", "f__", "(", "f", ")", ":", "def", "f_", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "warnings", "import", "warn", "warn", "(", "message", ",", "category", "=", "DeprecationWarning...
25.75
18.9
def _InvokeGitkitApi(self, method, params=None, need_service_account=True): """Invokes Gitkit API, with optional access token for service account. Args: method: string, the api method name. params: dict of optional parameters for the API. need_service_account: false if service account is not ...
[ "def", "_InvokeGitkitApi", "(", "self", ",", "method", ",", "params", "=", "None", ",", "need_service_account", "=", "True", ")", ":", "body", "=", "simplejson", ".", "dumps", "(", "params", ")", "if", "params", "else", "None", "req", "=", "urllib_request"...
38.628571
20.657143
def manage_api_keys(): """Page for viewing and creating API keys.""" build = g.build create_form = forms.CreateApiKeyForm() if create_form.validate_on_submit(): api_key = models.ApiKey() create_form.populate_obj(api_key) api_key.id = utils.human_uuid() api_key.secret = ut...
[ "def", "manage_api_keys", "(", ")", ":", "build", "=", "g", ".", "build", "create_form", "=", "forms", ".", "CreateApiKeyForm", "(", ")", "if", "create_form", ".", "validate_on_submit", "(", ")", ":", "api_key", "=", "models", ".", "ApiKey", "(", ")", "c...
30.475
15.1
def delete_all_objects(self, nms, async_=False): """ Deletes all objects from this container. By default the call will block until all objects have been deleted. By passing True for the 'async_' parameter, this method will not block, and instead return an object that can be used...
[ "def", "delete_all_objects", "(", "self", ",", "nms", ",", "async_", "=", "False", ")", ":", "if", "nms", "is", "None", ":", "nms", "=", "self", ".", "api", ".", "list_object_names", "(", "self", ".", "name", ",", "full_listing", "=", "True", ")", "r...
51.571429
26.142857
def close(self): """ Send a terminate request and then disconnect from the serial device. """ if self._initialized: self.stop() self.logged_in = False return self.serial_h.close()
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_initialized", ":", "self", ".", "stop", "(", ")", "self", ".", "logged_in", "=", "False", "return", "self", ".", "serial_h", ".", "close", "(", ")" ]
23.375
15.375