text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def EnsembleLearner(learners): """Given a list of learning algorithms, have them vote.""" def train(dataset): predictors = [learner(dataset) for learner in learners] def predict(example): return mode(predictor(example) for predictor in predictors) return predict return tr...
[ "def", "EnsembleLearner", "(", "learners", ")", ":", "def", "train", "(", "dataset", ")", ":", "predictors", "=", "[", "learner", "(", "dataset", ")", "for", "learner", "in", "learners", "]", "def", "predict", "(", "example", ")", ":", "return", "mode", ...
39.5
16.75
def get_developer_certificate(self, developer_certificate_id, authorization, **kwargs): # noqa: E501 """Fetch an existing developer certificate to connect to the bootstrap server. # noqa: E501 This REST API is intended to be used by customers to fetch an existing developer certificate (a certificate ...
[ "def", "get_developer_certificate", "(", "self", ",", "developer_certificate_id", ",", "authorization", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'...
74.090909
45.5
def _drain(self, cycles=None): """Activate the pump and let the flow go. This will call the process() method on each attached module until a StopIteration is raised, usually by a pump when it reached the EOF. A StopIteration is also raised when self.cycles was set and the numbe...
[ "def", "_drain", "(", "self", ",", "cycles", "=", "None", ")", ":", "log", ".", "info", "(", "\"Now draining...\"", ")", "if", "not", "cycles", ":", "log", ".", "info", "(", "\"No cycle count, the pipeline may be drained forever.\"", ")", "if", "self", ".", ...
39.655172
17.747126
def get_function_name(s): """ Get the function name from a C-style function declaration string. :param str s: A C-style function declaration string. :return: The function name. :rtype: str """ s = s.strip() if s.startswith("__attribute__"): # Remove "__attribute__ ((...
[ "def", "get_function_name", "(", "s", ")", ":", "s", "=", "s", ".", "strip", "(", ")", "if", "s", ".", "startswith", "(", "\"__attribute__\"", ")", ":", "# Remove \"__attribute__ ((foobar))\"", "if", "\"))\"", "not", "in", "s", ":", "raise", "ValueError", ...
30.8125
22.5625
def deleteByteArray(self, context, page, returnError): """please override""" returnError.contents.value = self.IllegalStateError raise NotImplementedError("You must override this method.")
[ "def", "deleteByteArray", "(", "self", ",", "context", ",", "page", ",", "returnError", ")", ":", "returnError", ".", "contents", ".", "value", "=", "self", ".", "IllegalStateError", "raise", "NotImplementedError", "(", "\"You must override this method.\"", ")" ]
52.25
15
def diagnose_cluster( self, project_id, region, cluster_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets cluster diagnostic information. After the operation complet...
[ "def", "diagnose_cluster", "(", "self", ",", "project_id", ",", "region", ",", "cluster_name", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", "....
41.364706
22.988235
def getSecurityHkey(self, s): ''' returns the necessary string value for an HKEY for the win32security module ''' try: return self.hkeys_security[s] except KeyError: raise CommandExecutionError(( 'No HKEY named "{0}". It should be one of t...
[ "def", "getSecurityHkey", "(", "self", ",", "s", ")", ":", "try", ":", "return", "self", ".", "hkeys_security", "[", "s", "]", "except", "KeyError", ":", "raise", "CommandExecutionError", "(", "(", "'No HKEY named \"{0}\". It should be one of the following: {1}'", ...
39.1
21.7
def _parse_info(self, s): """Given relevant data from the ffmpeg output, set audio parameter fields on this object. """ # Sample rate. match = re.search(r'(\d+) hz', s) if match: self.samplerate = int(match.group(1)) else: self.samplerate =...
[ "def", "_parse_info", "(", "self", ",", "s", ")", ":", "# Sample rate.", "match", "=", "re", ".", "search", "(", "r'(\\d+) hz'", ",", "s", ")", "if", "match", ":", "self", ".", "samplerate", "=", "int", "(", "match", ".", "group", "(", "1", ")", ")...
29.404762
14.809524
def same_types(self, index1, index2): """Returns True if both symbol table elements are of the same type""" try: same = self.table[index1].type == self.table[index2].type != SharedData.TYPES.NO_TYPE except Exception: self.error() return same
[ "def", "same_types", "(", "self", ",", "index1", ",", "index2", ")", ":", "try", ":", "same", "=", "self", ".", "table", "[", "index1", "]", ".", "type", "==", "self", ".", "table", "[", "index2", "]", ".", "type", "!=", "SharedData", ".", "TYPES",...
42.428571
19.571429
def narrow_sqs(self, sqs): """ TODO: Currently this is an AND conjunction. It should vary depending on the value of self.select_many. """ if self.select_many: sq = None for value in self.get_applicable_values(): q = SQ(**{self.field_name: s...
[ "def", "narrow_sqs", "(", "self", ",", "sqs", ")", ":", "if", "self", ".", "select_many", ":", "sq", "=", "None", "for", "value", "in", "self", ".", "get_applicable_values", "(", ")", ":", "q", "=", "SQ", "(", "*", "*", "{", "self", ".", "field_nam...
32.272727
17.636364
def save(self, force_eav=False, **kwargs): """ Saves entity instance and creates/updates related attribute instances. :param eav: if True (default), EAV attributes are saved along with entity. """ # save entity super(BaseEntity, self).save(**kwargs) # TODO: thin...
[ "def", "save", "(", "self", ",", "force_eav", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# save entity", "super", "(", "BaseEntity", ",", "self", ")", ".", "save", "(", "*", "*", "kwargs", ")", "# TODO: think about use cases; are we doing it right?", ...
38.52381
19.666667
def delete_servers(*servers, **options): ''' Removes NTP servers configured on the device. :param servers: list of IP Addresses/Domain Names to be removed as NTP servers :param test (bool): discard loaded config. By default ``test`` is False (will not dicard the changes) :param com...
[ "def", "delete_servers", "(", "*", "servers", ",", "*", "*", "options", ")", ":", "test", "=", "options", ".", "pop", "(", "'test'", ",", "False", ")", "commit", "=", "options", ".", "pop", "(", "'commit'", ",", "True", ")", "return", "__salt__", "["...
39.441176
27.911765
def flash_block(self, addr, data, smart_flash=True, chip_erase=None, progress_cb=None, fast_verify=False): """! @brief Flash a block of data. """ assert self.region is not None assert self.region.contains_range(start=addr, length=len(data)) fb = FlashBuilder(self...
[ "def", "flash_block", "(", "self", ",", "addr", ",", "data", ",", "smart_flash", "=", "True", ",", "chip_erase", "=", "None", ",", "progress_cb", "=", "None", ",", "fast_verify", "=", "False", ")", ":", "assert", "self", ".", "region", "is", "not", "No...
40
19
def get_names_including_errors_by_namespace(graph: BELGraph, namespace: str) -> Set[str]: """Takes the names from the graph in a given namespace (:func:`pybel.struct.summary.get_names_by_namespace`) and the erroneous names from the same namespace (:func:`get_incorrect_names_by_namespace`) and returns them toget...
[ "def", "get_names_including_errors_by_namespace", "(", "graph", ":", "BELGraph", ",", "namespace", ":", "str", ")", "->", "Set", "[", "str", "]", ":", "return", "get_names_by_namespace", "(", "graph", ",", "namespace", ")", "|", "get_incorrect_names_by_namespace", ...
68.125
37.75
def _calc_mask(self): """Computes a boolean mask from the user defined constraints.""" mask = [] for row in self._constraints: mask.append(tuple(x is None for x in row)) return tuple(mask)
[ "def", "_calc_mask", "(", "self", ")", ":", "mask", "=", "[", "]", "for", "row", "in", "self", ".", "_constraints", ":", "mask", ".", "append", "(", "tuple", "(", "x", "is", "None", "for", "x", "in", "row", ")", ")", "return", "tuple", "(", "mask...
34.166667
13.166667
def command(state, args): """Add an anime from an AniDB search.""" args = parser.parse_args(args[1:]) if args.watching: rows = query.select.select(state.db, 'regexp IS NOT NULL', [], ['aid']) aids = [anime.aid for anime in rows] elif args.incomplete: rows = query.select.select(st...
[ "def", "command", "(", "state", ",", "args", ")", ":", "args", "=", "parser", ".", "parse_args", "(", "args", "[", "1", ":", "]", ")", "if", "args", ".", "watching", ":", "rows", "=", "query", ".", "select", ".", "select", "(", "state", ".", "db"...
37.636364
15.909091
def get_model_core(model): """ Return core view of given model or None """ model_label = lower('%s.%s' % (model._meta.app_label, model._meta.object_name)) return registered_model_cores.get(model_label)
[ "def", "get_model_core", "(", "model", ")", ":", "model_label", "=", "lower", "(", "'%s.%s'", "%", "(", "model", ".", "_meta", ".", "app_label", ",", "model", ".", "_meta", ".", "object_name", ")", ")", "return", "registered_model_cores", ".", "get", "(", ...
36
11.666667
def ihfft(a, n=None, axis=-1, norm=None): """ Compute the inverse FFT of a signal which has Hermitian symmetry. Parameters ---------- a : array_like Input array. n : int, optional Length of the inverse FFT. Number of points along transformation axis in the input to use. ...
[ "def", "ihfft", "(", "a", ",", "n", "=", "None", ",", "axis", "=", "-", "1", ",", "norm", "=", "None", ")", ":", "# The copy may be required for multithreading.", "a", "=", "array", "(", "a", ",", "copy", "=", "True", ",", "dtype", "=", "float", ")",...
35.192982
22.631579
def proxy_num(self, protocol=None): """Get the number of proxies in the pool Args: protocol (str, optional): 'http' or 'https' or None. (default None) Returns: If protocol is None, return the total number of proxies, otherwise, return the number of proxies o...
[ "def", "proxy_num", "(", "self", ",", "protocol", "=", "None", ")", ":", "http_num", "=", "len", "(", "self", ".", "proxies", "[", "'http'", "]", ")", "https_num", "=", "len", "(", "self", ".", "proxies", "[", "'https'", "]", ")", "if", "protocol", ...
33.777778
17.833333
def requiv_contact_L1(q, sma, compno, **kwargs): """ for the contact case we can make the assumption of aligned, synchronous, and circular """ return requiv_L1(q=q, syncpar=1, ecc=0, sma=sma, incl_star=0, long_an_star=0, incl_orb=0, long_an_orb=0, compno=compno, **kwargs)
[ "def", "requiv_contact_L1", "(", "q", ",", "sma", ",", "compno", ",", "*", "*", "kwargs", ")", ":", "return", "requiv_L1", "(", "q", "=", "q", ",", "syncpar", "=", "1", ",", "ecc", "=", "0", ",", "sma", "=", "sma", ",", "incl_star", "=", "0", "...
56.8
30
def get_instance( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets the details of a specific Redis instance. Example: >>> from google.cloud import redis_...
[ "def", "get_instance", "(", "self", ",", "name", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata"...
42.894737
24.649123
def get_timestamp(dt=None): ''' Return current timestamp if @dt is None else return timestamp of @dt. >>> t = datetime.datetime(2015, 0o5, 21) >>> get_timestamp(t) 1432166400 ''' if dt is None: dt = datetime.datetime.utcnow() t = dt.utctimetuple() return calendar.timegm(t)
[ "def", "get_timestamp", "(", "dt", "=", "None", ")", ":", "if", "dt", "is", "None", ":", "dt", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "t", "=", "dt", ".", "utctimetuple", "(", ")", "return", "calendar", ".", "timegm", "(", "t", ...
21.642857
20.785714
def process(self, content): """ Process (marshal) the tag with the specified value using the optional type information. @param content: The content to process. @type content: L{Object} """ log.debug('processing:\n%s', content) self.reset() if conte...
[ "def", "process", "(", "self", ",", "content", ")", ":", "log", ".", "debug", "(", "'processing:\\n%s'", ",", "content", ")", "self", ".", "reset", "(", ")", "if", "content", ".", "tag", "is", "None", ":", "content", ".", "tag", "=", "content", ".", ...
35.944444
10.722222
def do_p(self, node): """handle <p> tag The <p> tag is the core of the grammar. It can contain almost anything: freeform text, <choice> tags, <xref> tags, even other <p> tags. If a "class='sentence'" attribute is found, a flag is set and the next word will be cap...
[ "def", "do_p", "(", "self", ",", "node", ")", ":", "keys", "=", "node", ".", "attributes", ".", "keys", "(", ")", "if", "\"class\"", "in", "keys", ":", "if", "node", ".", "attributes", "[", "\"class\"", "]", ".", "value", "==", "\"sentence\"", ":", ...
42.818182
18.727273
def getMetricsTimeline(tmaster, component_name, metric_names, instances, start_time, end_time, callback=None): """ Get the specified metrics for the given component name of this ...
[ "def", "getMetricsTimeline", "(", "tmaster", ",", "component_name", ",", "metric_names", ",", "instances", ",", "start_time", ",", "end_time", ",", "callback", "=", "None", ")", ":", "# Tmaster is the proto object and must have host and port for stats.", "if", "not", "t...
30.966667
18.15
def allow_client_incoming(self, client_name): """ Allow the user of this token to accept incoming connections. :param str client_name: Client name to accept calls from """ self.client_name = client_name self.capabilities['incoming'] = ScopeURI('client', 'incoming', {'cli...
[ "def", "allow_client_incoming", "(", "self", ",", "client_name", ")", ":", "self", ".", "client_name", "=", "client_name", "self", ".", "capabilities", "[", "'incoming'", "]", "=", "ScopeURI", "(", "'client'", ",", "'incoming'", ",", "{", "'clientName'", ":", ...
42
19.75
def BL(self, params): """ BL label Branch to the label, storing the next instruction in the Link Register """ label = self.get_one_parameter(self.ONE_PARAMETER, params) self.check_arguments(label_exists=(label,)) # TODO check if label is within +- 16 MB ...
[ "def", "BL", "(", "self", ",", "params", ")", ":", "label", "=", "self", ".", "get_one_parameter", "(", "self", ".", "ONE_PARAMETER", ",", "params", ")", "self", ".", "check_arguments", "(", "label_exists", "=", "(", "label", ",", ")", ")", "# TODO check...
31.470588
25.588235
def collapse_user(fp): """ Converts a path back to ~/ from expanduser() """ home_dir = os.path.expanduser("~") abs_path = os.path.abspath(fp) return abs_path.replace(home_dir, "~")
[ "def", "collapse_user", "(", "fp", ")", ":", "home_dir", "=", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", "abs_path", "=", "os", ".", "path", ".", "abspath", "(", "fp", ")", "return", "abs_path", ".", "replace", "(", "home_dir", ",", "\"...
28.285714
5.142857
def get(self, sid): """ Constructs a MemberContext :param sid: The unique string that identifies the resource :returns: twilio.rest.chat.v2.service.channel.member.MemberContext :rtype: twilio.rest.chat.v2.service.channel.member.MemberContext """ return MemberCon...
[ "def", "get", "(", "self", ",", "sid", ")", ":", "return", "MemberContext", "(", "self", ".", "_version", ",", "service_sid", "=", "self", ".", "_solution", "[", "'service_sid'", "]", ",", "channel_sid", "=", "self", ".", "_solution", "[", "'channel_sid'",...
31.933333
20.2
def tags_check_convert(cls, tags): """Accept one tag as string or multiple tags in list of strings. Returns list (with tags in unicode form) or raises ValueError """ # single string check comes first since string is also a Sequence if isinstance(tags, string_types): r...
[ "def", "tags_check_convert", "(", "cls", ",", "tags", ")", ":", "# single string check comes first since string is also a Sequence", "if", "isinstance", "(", "tags", ",", "string_types", ")", ":", "return", "[", "cls", ".", "__tag_check_convert", "(", "tags", ")", "...
49
16.307692
def to_d(l): """ Converts list of dicts to dict. """ _d = {} for x in l: for k, v in x.items(): _d[k] = v return _d
[ "def", "to_d", "(", "l", ")", ":", "_d", "=", "{", "}", "for", "x", "in", "l", ":", "for", "k", ",", "v", "in", "x", ".", "items", "(", ")", ":", "_d", "[", "k", "]", "=", "v", "return", "_d" ]
16.777778
15.888889
def conditional_resize(image, ratio, width=None, height=None, upcrop=True, namespace="resized"): """ Crop the image based on a ratio If upcrop is true, crops the images that have a higher ratio than the given ratio, if false crops the images that have a lower ratio """ as...
[ "def", "conditional_resize", "(", "image", ",", "ratio", ",", "width", "=", "None", ",", "height", "=", "None", ",", "upcrop", "=", "True", ",", "namespace", "=", "\"resized\"", ")", ":", "aspect", "=", "float", "(", "image", ".", "width", ")", "/", ...
37.1875
22.5625
def render_toctrees(kb_app: kb, sphinx_app: Sphinx, doctree: doctree, fromdocname: str): """ Look in doctrees for toctree and replace with custom render """ # Only do any of this if toctree support is turned on in KaybeeSettings. # By default, this is off. settings: KaybeeSettings =...
[ "def", "render_toctrees", "(", "kb_app", ":", "kb", ",", "sphinx_app", ":", "Sphinx", ",", "doctree", ":", "doctree", ",", "fromdocname", ":", "str", ")", ":", "# Only do any of this if toctree support is turned on in KaybeeSettings.", "# By default, this is off.", "setti...
42.894737
18.552632
def get(key, default=None): ''' Get a (list of) value(s) from the minion datastore .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' data.get key salt '*' data.get '["key1", "key2"]' ''' store = load() if isinstance(key, six.string_types): ...
[ "def", "get", "(", "key", ",", "default", "=", "None", ")", ":", "store", "=", "load", "(", ")", "if", "isinstance", "(", "key", ",", "six", ".", "string_types", ")", ":", "return", "store", ".", "get", "(", "key", ",", "default", ")", "elif", "d...
22.47619
21.52381
def FromDictionary(cls, dictionary): """Initializes from user specified dictionary. Args: dictionary: dict of user specified attributes Returns: GitkitUser object """ if 'user_id' in dictionary: raise errors.GitkitClientError('use localId instead') if 'localId' not in dictiona...
[ "def", "FromDictionary", "(", "cls", ",", "dictionary", ")", ":", "if", "'user_id'", "in", "dictionary", ":", "raise", "errors", ".", "GitkitClientError", "(", "'use localId instead'", ")", "if", "'localId'", "not", "in", "dictionary", ":", "raise", "errors", ...
31.625
15.6875
def unstack(self, dimensions=None, **dimensions_kwargs): """ Unstack an existing dimension into multiple new dimensions. New dimensions will be added at the end, and the order of the data along each new dimension will be in contiguous (C) order. Parameters ---------- ...
[ "def", "unstack", "(", "self", ",", "dimensions", "=", "None", ",", "*", "*", "dimensions_kwargs", ")", ":", "dimensions", "=", "either_dict_or_kwargs", "(", "dimensions", ",", "dimensions_kwargs", ",", "'unstack'", ")", "result", "=", "self", "for", "old_dim"...
35.225806
22.451613
def GenerateHelpText(self, env, sort=None): """ Generate the help text for the options. env - an environment that is used to get the current values of the options. cmp - Either a function as follows: The specific sort function should take two arguments and return -1, 0 or ...
[ "def", "GenerateHelpText", "(", "self", ",", "env", ",", "sort", "=", "None", ")", ":", "if", "callable", "(", "sort", ")", ":", "options", "=", "sorted", "(", "self", ".", "options", ",", "key", "=", "cmp_to_key", "(", "lambda", "x", ",", "y", ":"...
38.576923
22.884615
def _set_sort_expressions(self): """Construct the query: sorting. Add sorting(ORDER BY) on the columns needed to be applied on. """ sort_expressions = [] i = 0 while self.params.get('order[{:d}][column]'.format(i), False): column_nr = int(self.params.get('ord...
[ "def", "_set_sort_expressions", "(", "self", ")", ":", "sort_expressions", "=", "[", "]", "i", "=", "0", "while", "self", ".", "params", ".", "get", "(", "'order[{:d}][column]'", ".", "format", "(", "i", ")", ",", "False", ")", ":", "column_nr", "=", "...
40.709677
15.516129
def pull(self, images, file_name=None, save=True, **kwargs): '''pull an image from gitlab. The image is found based on the uri that should correspond to a gitlab repository, and then the branch, job name, artifact folder, and tag of the container. The minimum that we need are the job id, colle...
[ "def", "pull", "(", "self", ",", "images", ",", "file_name", "=", "None", ",", "save", "=", "True", ",", "*", "*", "kwargs", ")", ":", "force", "=", "False", "if", "\"force\"", "in", "kwargs", ":", "force", "=", "kwargs", "[", "'force'", "]", "if",...
37.605505
22.669725
def ar_periodogram(x, window='hanning', window_len=7): """ Compute periodogram from data x, using prewhitening, smoothing and recoloring. The data is fitted to an AR(1) model for prewhitening, and the residuals are used to compute a first-pass periodogram with smoothing. The fitted coefficients ar...
[ "def", "ar_periodogram", "(", "x", ",", "window", "=", "'hanning'", ",", "window_len", "=", "7", ")", ":", "# === run regression === #", "x_lag", "=", "x", "[", ":", "-", "1", "]", "# lagged x", "X", "=", "np", ".", "array", "(", "[", "np", ".", "one...
34.333333
22.047619
def name(self) -> str: """Return template's name (includes whitespace).""" h = self._atomic_partition(self._first_arg_sep)[0] if len(h) == len(self.string): return h[2:-2] return h[2:]
[ "def", "name", "(", "self", ")", "->", "str", ":", "h", "=", "self", ".", "_atomic_partition", "(", "self", ".", "_first_arg_sep", ")", "[", "0", "]", "if", "len", "(", "h", ")", "==", "len", "(", "self", ".", "string", ")", ":", "return", "h", ...
37.166667
12
def inodeusage(args=None): ''' Return inode usage information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.inodeusage ''' flags = _clean_flags(args, 'disk.inodeusage') if __grains__['kernel'] == 'AIX': cmd = 'df -i' else: c...
[ "def", "inodeusage", "(", "args", "=", "None", ")", ":", "flags", "=", "_clean_flags", "(", "args", ",", "'disk.inodeusage'", ")", "if", "__grains__", "[", "'kernel'", "]", "==", "'AIX'", ":", "cmd", "=", "'df -i'", "else", ":", "cmd", "=", "'df -iP'", ...
29.339286
15.482143
def _parse_parameters(self, resource, params): '''Creates a dictionary from query_string and `params` Transforms the `?key=value&...` to a {'key': 'value'} and adds (or overwrites if already present) the value with the dictionary in `params`. ''' # remove params from res...
[ "def", "_parse_parameters", "(", "self", ",", "resource", ",", "params", ")", ":", "# remove params from resource URI (needed for paginated stuff)", "parsed_uri", "=", "urlparse", "(", "resource", ")", "qs", "=", "parsed_uri", ".", "query", "resource", "=", "urlunpars...
37.578947
19.789474
def as_objective(obj): """Convert obj into Objective class. Strings of the form "layer:n" become the Objective channel(layer, n). Objectives are returned unchanged. Args: obj: string or Objective. Returns: Objective """ if isinstance(obj, Objective): return obj elif callable(obj): ret...
[ "def", "as_objective", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "Objective", ")", ":", "return", "obj", "elif", "callable", "(", "obj", ")", ":", "return", "obj", "elif", "isinstance", "(", "obj", ",", "str", ")", ":", "layer", ",",...
21.65
19.6
def load_config(config, expand_env=False, force=False): """Return repos from a directory and fnmatch. Not recursive. :param config: paths to config file :type config: str :param expand_env: True to expand environment varialbes in the config. :type expand_env: bool :param bool force: True to agg...
[ "def", "load_config", "(", "config", ",", "expand_env", "=", "False", ",", "force", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "config", ")", ":", "raise", "ConfigException", "(", "'Unable to find configuration file: %s'", "%...
37.333333
18.625
def replace_surrogate_decode(mybytes): """ Returns a (unicode) string """ decoded = [] for ch in mybytes: # We may be parsing newbytes (in which case ch is an int) or a native # str on Py2 if isinstance(ch, int): code = ch else: code = ord(ch) ...
[ "def", "replace_surrogate_decode", "(", "mybytes", ")", ":", "decoded", "=", "[", "]", "for", "ch", "in", "mybytes", ":", "# We may be parsing newbytes (in which case ch is an int) or a native", "# str on Py2", "if", "isinstance", "(", "ch", ",", "int", ")", ":", "c...
28.565217
12.73913
def _get_logger(self): """Get the appropriate logger Prevents uninitialized servers in write-only mode from failing. """ if self.logger: return self.logger elif self.server: return self.server.logger else: return default_logger
[ "def", "_get_logger", "(", "self", ")", ":", "if", "self", ".", "logger", ":", "return", "self", ".", "logger", "elif", "self", ".", "server", ":", "return", "self", ".", "server", ".", "logger", "else", ":", "return", "default_logger" ]
25.166667
17.333333
def contrast(self, value=1.0): """Increases or decreases the contrast in the layer. The given value is a percentage to increase or decrease the image contrast, for example 1.2 means contrast at 120%. """ c = ImageEnhance.Contrast(self.img) self.im...
[ "def", "contrast", "(", "self", ",", "value", "=", "1.0", ")", ":", "c", "=", "ImageEnhance", ".", "Contrast", "(", "self", ".", "img", ")", "self", ".", "img", "=", "c", ".", "enhance", "(", "value", ")" ]
27.416667
15.5
def create(years, certificate_type, promotion_code=None, sans_to_add=None): ''' Creates a new SSL certificate. Returns the following information: - Whether or not the SSL order was successful - The certificate ID - The order ID - The transaction ID - The amount charged for the order - T...
[ "def", "create", "(", "years", ",", "certificate_type", ",", "promotion_code", "=", "None", ",", "sans_to_add", "=", "None", ")", ":", "valid_certs", "=", "(", "'QuickSSL Premium'", ",", "'RapidSSL'", ",", "'RapidSSL Wildcard'", ",", "'PremiumSSL'", ",", "'Insta...
50.296703
27.813187
async def apply_command(self, cmd): """ applies a command This calls the pre and post hooks attached to the command, as well as :meth:`cmd.apply`. :param cmd: an applicable command :type cmd: :class:`~alot.commands.Command` """ # FIXME: What are we guard...
[ "async", "def", "apply_command", "(", "self", ",", "cmd", ")", ":", "# FIXME: What are we guarding for here? We don't mention that None is", "# allowed as a value fo cmd.", "if", "cmd", ":", "if", "cmd", ".", "prehook", ":", "await", "cmd", ".", "prehook", "(", "ui", ...
35.192308
15.269231
def persistant_success(request, message, extra_tags='', fail_silently=False, *args, **kwargs): """ Adds a persistant message with the ``SUCCESS`` level. """ add_message(request, SUCCESS_PERSISTENT, message, extra_tags=extra_tags, fail_silently=fail_silently, *args, **kwargs)
[ "def", "persistant_success", "(", "request", ",", "message", ",", "extra_tags", "=", "''", ",", "fail_silently", "=", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "add_message", "(", "request", ",", "SUCCESS_PERSISTENT", ",", "message", ",...
50.333333
21.333333
def get_data(self): """ returns a generator object that reads data a block at a time; the generator prints "File depleted" and returns nothing when all data in the file has been read. :return: """ with self as gr: while True: try: ...
[ "def", "get_data", "(", "self", ")", ":", "with", "self", "as", "gr", ":", "while", "True", ":", "try", ":", "yield", "gr", ".", "read_next_data_block_int8", "(", ")", "except", "Exception", "as", "e", ":", "print", "(", "\"File depleted\"", ")", "yield"...
36.615385
16.461538
def calc_freefree_kappa(ne, t, hz): """Dulk (1985) eq 20, assuming pure hydrogen.""" return 9.78e-3 * ne**2 * hz**-2 * t**-1.5 * (24.5 + np.log(t) - np.log(hz))
[ "def", "calc_freefree_kappa", "(", "ne", ",", "t", ",", "hz", ")", ":", "return", "9.78e-3", "*", "ne", "**", "2", "*", "hz", "**", "-", "2", "*", "t", "**", "-", "1.5", "*", "(", "24.5", "+", "np", ".", "log", "(", "t", ")", "-", "np", "."...
55.333333
14.666667
def to_sympy_column_matrix(matrix): """ Converts a sympy matrix to a column matrix (i.e. transposes it if it was row matrix) Raises ValueError if matrix provided is not a vector :param matrix: a vector to be converted to column :return: """ matrix = to_sympy_matrix(matrix) if matrix.cols...
[ "def", "to_sympy_column_matrix", "(", "matrix", ")", ":", "matrix", "=", "to_sympy_matrix", "(", "matrix", ")", "if", "matrix", ".", "cols", "==", "1", ":", "return", "matrix", "elif", "matrix", ".", "rows", "==", "1", ":", "return", "matrix", ".", "T", ...
34.214286
18.071429
def get_folders(self): """ Returns a list of all folders for this account Returns: List[:class:`Folder <pyOutlook.core.folder.Folder>`] """ endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' r = requests.get(endpoint, headers=self._headers) ...
[ "def", "get_folders", "(", "self", ")", ":", "endpoint", "=", "'https://outlook.office.com/api/v2.0/me/MailFolders/'", "r", "=", "requests", ".", "get", "(", "endpoint", ",", "headers", "=", "self", ".", "_headers", ")", "if", "check_response", "(", "r", ")", ...
32.916667
22
def load_config(self, config_file_name): """ Load configuration file from prt or str. Configuration file type is extracted from the file suffix - prt or str. :param config_file_name: full path to the configuration file. IxTclServer must have access to the file location. either: ...
[ "def", "load_config", "(", "self", ",", "config_file_name", ")", ":", "config_file_name", "=", "config_file_name", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "ext", "=", "path", ".", "splitext", "(", "config_file_name", ")", "[", "-", "1", "]", ".", ...
44.619048
23.333333
def pitch(self): """ Calculates the Pitch of the Quaternion. """ x, y, z, w = self.x, self.y, self.z, self.w return math.atan2(2*x*w - 2*y*z, 1 - 2*x*x - 2*z*z)
[ "def", "pitch", "(", "self", ")", ":", "x", ",", "y", ",", "z", ",", "w", "=", "self", ".", "x", ",", "self", ".", "y", ",", "self", ".", "z", ",", "self", ".", "w", "return", "math", ".", "atan2", "(", "2", "*", "x", "*", "w", "-", "2"...
33.8
17.2
def _get_bucket(self, bucket_name): '''get a bucket based on a bucket name. If it doesn't exist, create it. Parameters ========== bucket_name: the name of the bucket to get (or create). It should not contain google, and should be all lowercase with - ...
[ "def", "_get_bucket", "(", "self", ",", "bucket_name", ")", ":", "# Case 1: The bucket already exists", "try", ":", "bucket", "=", "self", ".", "_bucket_service", ".", "get_bucket", "(", "bucket_name", ")", "# Case 2: The bucket needs to be created", "except", "google",...
33.958333
24.125
def by_member(self, member_id, type='introduced'): """ Takes a bioguide ID and a type: (introduced|updated|cosponsored|withdrawn) Returns recent bills """ path = "members/{member_id}/bills/{type}.json".format( member_id=member_id, type=type) return sel...
[ "def", "by_member", "(", "self", ",", "member_id", ",", "type", "=", "'introduced'", ")", ":", "path", "=", "\"members/{member_id}/bills/{type}.json\"", ".", "format", "(", "member_id", "=", "member_id", ",", "type", "=", "type", ")", "return", "self", ".", ...
36.111111
7.444444
def reject_entry(request, entry_id): """ Admins can reject an entry that has been verified or approved but not invoiced to set its status to 'unverified' for the user to fix. """ return_url = request.GET.get('next', reverse('dashboard')) try: entry = Entry.no_join.get(pk=entry_id) ex...
[ "def", "reject_entry", "(", "request", ",", "entry_id", ")", ":", "return_url", "=", "request", ".", "GET", ".", "get", "(", "'next'", ",", "reverse", "(", "'dashboard'", ")", ")", "try", ":", "entry", "=", "Entry", ".", "no_join", ".", "get", "(", "...
35.892857
15.607143
def circ_corrcc(x, y, tail='two-sided'): """Correlation coefficient between two circular variables. Parameters ---------- x : np.array First circular variable (expressed in radians) y : np.array Second circular variable (expressed in radians) tail : string Specify whethe...
[ "def", "circ_corrcc", "(", "x", ",", "y", ",", "tail", "=", "'two-sided'", ")", ":", "from", "scipy", ".", "stats", "import", "norm", "x", "=", "np", ".", "asarray", "(", "x", ")", "y", "=", "np", ".", "asarray", "(", "y", ")", "# Check size", "i...
27.546875
20.96875
def _normalize_orders(self): """Helper: adjust orders based on cursors, where clauses.""" orders = list(self._orders) _has_snapshot_cursor = False if self._start_at: if isinstance(self._start_at[0], document.DocumentSnapshot): _has_snapshot_cursor = True ...
[ "def", "_normalize_orders", "(", "self", ")", ":", "orders", "=", "list", "(", "self", ".", "_orders", ")", "_has_snapshot_cursor", "=", "False", "if", "self", ".", "_start_at", ":", "if", "isinstance", "(", "self", ".", "_start_at", "[", "0", "]", ",", ...
41.363636
19.515152
def close(self) -> None: """Closes all loaded tables.""" while self.wdl: _, wdl = self.wdl.popitem() wdl.close() while self.dtz: _, dtz = self.dtz.popitem() dtz.close() self.lru.clear()
[ "def", "close", "(", "self", ")", "->", "None", ":", "while", "self", ".", "wdl", ":", "_", ",", "wdl", "=", "self", ".", "wdl", ".", "popitem", "(", ")", "wdl", ".", "close", "(", ")", "while", "self", ".", "dtz", ":", "_", ",", "dtz", "=", ...
23.363636
16.545455
def set_key(self, key='C'): """Add a key signature event to the track_data.""" if isinstance(key, Key): key = key.name[0] self.track_data += self.key_signature_event(key)
[ "def", "set_key", "(", "self", ",", "key", "=", "'C'", ")", ":", "if", "isinstance", "(", "key", ",", "Key", ")", ":", "key", "=", "key", ".", "name", "[", "0", "]", "self", ".", "track_data", "+=", "self", ".", "key_signature_event", "(", "key", ...
40.4
9.6
def path(self): """HTTP full path constraint. (read-only). """ path = self.__prefix if self is not self.over: path = self.over.path + path return path
[ "def", "path", "(", "self", ")", ":", "path", "=", "self", ".", "__prefix", "if", "self", "is", "not", "self", ".", "over", ":", "path", "=", "self", ".", "over", ".", "path", "+", "path", "return", "path" ]
28
9.285714
def constant(self, val, ty): """ Creates a constant as a VexValue :param val: The value, as an integer :param ty: The type of the resulting VexValue :return: a VexValue """ if isinstance(val, VexValue) and not isinstance(val, IRExpr): raise Exception(...
[ "def", "constant", "(", "self", ",", "val", ",", "ty", ")", ":", "if", "isinstance", "(", "val", ",", "VexValue", ")", "and", "not", "isinstance", "(", "val", ",", "IRExpr", ")", ":", "raise", "Exception", "(", "'Constant cannot be made from VexValue or IREx...
37
12.666667
def step(self, compute=True): """Context manager to gradually build a history row, then commit it at the end. To reduce the number of conditionals needed, code can check run.history.compute: with run.history.step(batch_idx % log_interval == 0): run.history.add({"nice": "ok"}) ...
[ "def", "step", "(", "self", ",", "compute", "=", "True", ")", ":", "if", "self", ".", "batched", ":", "# we're already in a context manager", "raise", "wandb", ".", "Error", "(", "\"Nested History step contexts aren't supported\"", ")", "self", ".", "batched", "="...
37.611111
18.277778
def WriteHashes(self, arr): """ Write an array of hashes to the stream. Args: arr (list): a list of 32 byte hashes. """ length = len(arr) self.WriteVarInt(length) for item in arr: ba = bytearray(binascii.unhexlify(item)) ba.rev...
[ "def", "WriteHashes", "(", "self", ",", "arr", ")", ":", "length", "=", "len", "(", "arr", ")", "self", ".", "WriteVarInt", "(", "length", ")", "for", "item", "in", "arr", ":", "ba", "=", "bytearray", "(", "binascii", ".", "unhexlify", "(", "item", ...
29.071429
13.785714
def find_matches_by_sigma(cos_vects, unc_vect, cut_sigma): """Find all the pairs of sources within a given distance of each other. Parameters ---------- cos_vects : np.ndarray(3,nsrc) Directional cosines (i.e., x,y,z component) values of all the sources unc_vect : np.ndarray(nsrc) ...
[ "def", "find_matches_by_sigma", "(", "cos_vects", ",", "unc_vect", ",", "cut_sigma", ")", ":", "match_dict", "=", "{", "}", "sig_2_vect", "=", "unc_vect", "*", "unc_vect", "for", "i", ",", "v1", "in", "enumerate", "(", "cos_vects", ".", "T", ")", ":", "c...
32.621622
16.324324
def rel_path(filename): """ Function that gets relative path to the filename """ return os.path.join(os.getcwd(), os.path.dirname(__file__), filename)
[ "def", "rel_path", "(", "filename", ")", ":", "return", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "filename", ")" ]
32.4
12.4
def create(clients_num, clients_host, clients_port, people_num, throttle): """ Prepare clients to execute :return: Modules to execute, cmd line function :rtype: list[WrapperClient], (str, object) -> str | None """ res = [] for number in range(clients_num): sc = EchoClient({ ...
[ "def", "create", "(", "clients_num", ",", "clients_host", ",", "clients_port", ",", "people_num", ",", "throttle", ")", ":", "res", "=", "[", "]", "for", "number", "in", "range", "(", "clients_num", ")", ":", "sc", "=", "EchoClient", "(", "{", "'id'", ...
29.807692
15.269231
def _make_job_id(job_id, prefix=None): """Construct an ID for a new job. :type job_id: str or ``NoneType`` :param job_id: the user-provided job ID :type prefix: str or ``NoneType`` :param prefix: (Optional) the user-provided prefix for a job ID :rtype: str :returns: A job ID """ i...
[ "def", "_make_job_id", "(", "job_id", ",", "prefix", "=", "None", ")", ":", "if", "job_id", "is", "not", "None", ":", "return", "job_id", "elif", "prefix", "is", "not", "None", ":", "return", "str", "(", "prefix", ")", "+", "str", "(", "uuid", ".", ...
25.833333
16.166667
def on_redraw_timer(self, event): '''the redraw timer ensures we show new map tiles as they are downloaded''' state = self.state while state.in_queue.qsize(): obj = state.in_queue.get() if isinstance(obj, MPImageData): img = wx.EmptyImage(obj.width...
[ "def", "on_redraw_timer", "(", "self", ",", "event", ")", ":", "state", "=", "self", ".", "state", "while", "state", ".", "in_queue", ".", "qsize", "(", ")", ":", "obj", "=", "state", ".", "in_queue", ".", "get", "(", ")", "if", "isinstance", "(", ...
43.9375
10.25
def _cast_to_pod(val): """Try cast to int, float, bool, str, in that order.""" bools = {"True": True, "False": False} if val in bools: return bools[val] try: return int(val) except ValueError: try: return float(val) except ValueError: return tf.compat.as_text(val)
[ "def", "_cast_to_pod", "(", "val", ")", ":", "bools", "=", "{", "\"True\"", ":", "True", ",", "\"False\"", ":", "False", "}", "if", "val", "in", "bools", ":", "return", "bools", "[", "val", "]", "try", ":", "return", "int", "(", "val", ")", "except...
24.25
17.166667
def exponential_map(term): """ Returns a function f(alpha) that constructs the Program corresponding to exp(-1j*alpha*term). :param term: A pauli term to exponentiate :returns: A function that takes an angle parameter and returns a program. :rtype: Function """ if not np.isclose(np.imag(ter...
[ "def", "exponential_map", "(", "term", ")", ":", "if", "not", "np", ".", "isclose", "(", "np", ".", "imag", "(", "term", ".", "coefficient", ")", ",", "0.0", ")", ":", "raise", "TypeError", "(", "\"PauliTerm coefficient must be real\"", ")", "coeff", "=", ...
30.321429
19.535714
def list_versions(self, bucket_name, prefix='', delimiter='', max_results=1000, starting_key='', starting_version=''): ''' a method for retrieving a list of the versions of records in a bucket :param bucket_name: string with name of bucket :param prefix: [optional] string with valu...
[ "def", "list_versions", "(", "self", ",", "bucket_name", ",", "prefix", "=", "''", ",", "delimiter", "=", "''", ",", "max_results", "=", "1000", ",", "starting_key", "=", "''", ",", "starting_version", "=", "''", ")", ":", "title", "=", "'%s.list_versions'...
40.038462
21.173077
def _get_omim_ids(self): ''' side effect: populate omim_type map from a omim number to an ontology term the ontology terms's labels as - 'gene' when they declare it as a gene - 'Phenotype' Ph...
[ "def", "_get_omim_ids", "(", "self", ")", ":", "src_key", "=", "'mim2gene'", "omim_nums", "=", "set", "(", ")", "# all types", "line_counter", "=", "0", "raw", "=", "'/'", ".", "join", "(", "(", "self", ".", "rawdir", ",", "self", ".", "files", "[", ...
42.174419
20.895349
def erps(self, erps): '''Set the ERP values for this object's degrees of freedom. Parameters ---------- erps : float or sequence of float An ERP value to set on all degrees of freedom, or a list containing one such value for each degree of freedom. ''' ...
[ "def", "erps", "(", "self", ",", "erps", ")", ":", "_set_params", "(", "self", ".", "ode_obj", ",", "'ERP'", ",", "erps", ",", "self", ".", "ADOF", "+", "self", ".", "LDOF", ")" ]
37.8
24.2
def rmsd(ref_cds, est_cds): """ Root-mean-squared-difference """ ref_dists = pdist(ref_cds) est_dists = pdist(est_cds) return np.sqrt(((ref_dists - est_dists)**2).mean())
[ "def", "rmsd", "(", "ref_cds", ",", "est_cds", ")", ":", "ref_dists", "=", "pdist", "(", "ref_cds", ")", "est_dists", "=", "pdist", "(", "est_cds", ")", "return", "np", ".", "sqrt", "(", "(", "(", "ref_dists", "-", "est_dists", ")", "**", "2", ")", ...
26.857143
8
def make_account_admin(self, user_id, account_id, role=None, role_id=None, send_confirmation=None): """ Make an account admin. Flag an existing user as an admin within the account. """ path = {} data = {} params = {} # REQUIRED - PATH - account...
[ "def", "make_account_admin", "(", "self", ",", "user_id", ",", "account_id", ",", "role", "=", "None", ",", "role_id", "=", "None", ",", "send_confirmation", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}"...
38.846154
20.128205
def predict_mhcii_binding(job, peptfile, allele, univ_options, mhcii_options): """ This module will predict MHC:peptide binding for peptides in the files created in node YY to ALLELE. ALLELE represents an MHCII allele. The module returns (PREDFILE, PREDICTOR) where PREDFILE contains the predictions an...
[ "def", "predict_mhcii_binding", "(", "job", ",", "peptfile", ",", "allele", ",", "univ_options", ",", "mhcii_options", ")", ":", "job", ".", "fileStore", ".", "logToMaster", "(", "'Running mhcii on %s:%s'", "%", "(", "univ_options", "[", "'patient'", "]", ",", ...
46.047619
21.714286
def format(self, dt, fmt, locale=None): """ Formats a DateTime instance with a given format and locale. :param dt: The instance to format :type dt: pendulum.DateTime :param fmt: The format to use :type fmt: str :param locale: The locale to use :type loc...
[ "def", "format", "(", "self", ",", "dt", ",", "fmt", ",", "locale", "=", "None", ")", ":", "if", "not", "locale", ":", "locale", "=", "pendulum", ".", "get_locale", "(", ")", "locale", "=", "Locale", ".", "load", "(", "locale", ")", "result", "=", ...
24.166667
17.433333
def _multiprocessing_to_asyncio(in_queue, out_queue, loop): """Bridge between a synchronous multiprocessing queue and an asynchronous asyncio queue. Args: in_queue (multiprocessing.Queue): input queue out_queue (asyncio.Queue): output queue """ while True: value = in_queue....
[ "def", "_multiprocessing_to_asyncio", "(", "in_queue", ",", "out_queue", ",", "loop", ")", ":", "while", "True", ":", "value", "=", "in_queue", ".", "get", "(", ")", "loop", ".", "call_soon_threadsafe", "(", "out_queue", ".", "put_nowait", ",", "value", ")" ...
31.416667
17.416667
def NearestNeighborLearner(dataset, k=1): "k-NearestNeighbor: the k nearest neighbors vote." def predict(example): "Find the k closest, and have them vote for the best." best = heapq.nsmallest(k, ((dataset.distance(e, example), e) for e in dataset.examples)) ...
[ "def", "NearestNeighborLearner", "(", "dataset", ",", "k", "=", "1", ")", ":", "def", "predict", "(", "example", ")", ":", "\"Find the k closest, and have them vote for the best.\"", "best", "=", "heapq", ".", "nsmallest", "(", "k", ",", "(", "(", "dataset", "...
48.375
17.625
def make_app(config=None): """ Factory function that creates a new `CoolmagicApplication` object. Optional WSGI middlewares should be applied here. """ config = config or {} app = CoolMagicApplication(config) # static stuff app = SharedDataMiddleware( app, {"/public": path.join(...
[ "def", "make_app", "(", "config", "=", "None", ")", ":", "config", "=", "config", "or", "{", "}", "app", "=", "CoolMagicApplication", "(", "config", ")", "# static stuff", "app", "=", "SharedDataMiddleware", "(", "app", ",", "{", "\"/public\"", ":", "path"...
25.176471
19.882353
def dbsource(dbname, var, resolution=None, tscale=None): """Return which file(s) to use according to dbname, var, etc """ db_cfg = {} cfg_dir = 'datasource' cfg_files = pkg_resources.resource_listdir('oceansdb', cfg_dir) cfg_files = [f for f in cfg_files if f[-5:] == '.json'] for src_cfg in ...
[ "def", "dbsource", "(", "dbname", ",", "var", ",", "resolution", "=", "None", ",", "tscale", "=", "None", ")", ":", "db_cfg", "=", "{", "}", "cfg_dir", "=", "'datasource'", "cfg_files", "=", "pkg_resources", ".", "resource_listdir", "(", "'oceansdb'", ",",...
33.571429
19.261905
def cursor_to_data_header(cursor): """Fetches all rows from query ("cursor") and returns a pair (data, header) Returns: (data, header), where - data is a [num_rows]x[num_cols] sequence of sequences; - header is a [num_cols] list containing the field names """ n = 0 data, hea...
[ "def", "cursor_to_data_header", "(", "cursor", ")", ":", "n", "=", "0", "data", ",", "header", "=", "[", "]", ",", "{", "}", "for", "row", "in", "cursor", ":", "if", "n", "==", "0", ":", "header", "=", "row", ".", "keys", "(", ")", "data", ".",...
33
14.714286
def simple_peak_find(s, init_slope=500, start_slope=500, end_slope=200, min_peak_height=50, max_peak_width=1.5): """ Given a Series, return a list of tuples indicating when peaks start and stop and what their baseline is. [(t_start, t_end, hints) ...] """ point_gap = 10 ...
[ "def", "simple_peak_find", "(", "s", ",", "init_slope", "=", "500", ",", "start_slope", "=", "500", ",", "end_slope", "=", "200", ",", "min_peak_height", "=", "50", ",", "max_peak_width", "=", "1.5", ")", ":", "point_gap", "=", "10", "def", "slid_win", "...
35.397727
17.397727
def save(self): """ :return: save this environment on Ariane server (create or update) """ LOGGER.debug("Environment.save") post_payload = {} consolidated_osi_id = [] if self.id is not None: post_payload['environmentID'] = self.id if self.nam...
[ "def", "save", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "\"Environment.save\"", ")", "post_payload", "=", "{", "}", "consolidated_osi_id", "=", "[", "]", "if", "self", ".", "id", "is", "not", "None", ":", "post_payload", "[", "'environmentID'", ...
38.611111
17.166667
def require_server(fn): """ Checks if the user has called the task with a server name. Fabric tasks decorated with this decorator must be called like so:: fab <server name> <task name> If no server name is given, the task will not be executed. """ @wraps(fn) def wrapper(*args, **...
[ "def", "require_server", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "env", ".", "machine", "is", "None", ":", "abort", "(", "red", "(", "'ERROR: You must provide a s...
28.055556
20.388889
def iterate_nodes(self, string_key, distinct=True): """Given a string key it returns the nodes as a generator that can hold the key. The generator iterates one time through the ring starting at the correct position. if `distinct` is set, then the nodes returned will be unique, ...
[ "def", "iterate_nodes", "(", "self", ",", "string_key", ",", "distinct", "=", "True", ")", ":", "if", "not", "self", ".", "ring", ":", "yield", "None", ",", "None", "returned_values", "=", "set", "(", ")", "def", "distinct_filter", "(", "value", ")", "...
32.166667
16.466667
def remove_null_proxy_kwarg(func): """decorator, to remove a 'proxy' keyword argument. For wrapping certain Manager methods""" def wrapper(*args, **kwargs): if 'proxy' in kwargs: # if kwargs['proxy'] is None: del kwargs['proxy'] # else: # raise InvalidA...
[ "def", "remove_null_proxy_kwarg", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'proxy'", "in", "kwargs", ":", "# if kwargs['proxy'] is None:", "del", "kwargs", "[", "'proxy'", "]", "# else:", "# rais...
45
15.5
def _ann_store_annotations(self, item_with_annotations, node, overwrite=False): """Stores annotations into an hdf5 file.""" # If we overwrite delete all annotations first if overwrite is True or overwrite == 'v_annotations': annotated = self._all_get_from_attrs(node, HDF5StorageServ...
[ "def", "_ann_store_annotations", "(", "self", ",", "item_with_annotations", ",", "node", ",", "overwrite", "=", "False", ")", ":", "# If we overwrite delete all annotations first", "if", "overwrite", "is", "True", "or", "overwrite", "==", "'v_annotations'", ":", "anno...
43.571429
24.685714
def font(self): """Font object controlling text format defaults for this chart.""" defRPr = ( self._chartSpace .get_or_add_txPr() .p_lst[0] .get_or_add_pPr() .get_or_add_defRPr() ) return Font(defRPr)
[ "def", "font", "(", "self", ")", ":", "defRPr", "=", "(", "self", ".", "_chartSpace", ".", "get_or_add_txPr", "(", ")", ".", "p_lst", "[", "0", "]", ".", "get_or_add_pPr", "(", ")", ".", "get_or_add_defRPr", "(", ")", ")", "return", "Font", "(", "def...
29.9
13.5
def fail(self, tup): """Indicate that processing of a Tuple has failed. :param tup: the Tuple to fail (its ``id`` if ``str``). :type tup: :class:`str` or :class:`pystorm.component.Tuple` """ tup_id = tup.id if isinstance(tup, Tuple) else tup self.send_message({"command":...
[ "def", "fail", "(", "self", ",", "tup", ")", ":", "tup_id", "=", "tup", ".", "id", "if", "isinstance", "(", "tup", ",", "Tuple", ")", "else", "tup", "self", ".", "send_message", "(", "{", "\"command\"", ":", "\"fail\"", ",", "\"id\"", ":", "tup_id", ...
42
18.375
def _Backward3_sat_v_P(P, T, x): """Backward equation for region 3 for saturated state, vs=f(P,x) Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] x : integer Vapor quality, [-] Returns ------- v : float Specific volume, [m³...
[ "def", "_Backward3_sat_v_P", "(", "P", ",", "T", ",", "x", ")", ":", "if", "x", "==", "0", ":", "if", "P", "<", "19.00881189", ":", "region", "=", "\"c\"", "elif", "P", "<", "21.0434", ":", "region", "=", "\"s\"", "elif", "P", "<", "21.9316", ":"...
20.487805
21.243902
def escore(self): """(property) Returns the E-score associated with the result.""" hg_pval_thresh = self.escore_pval_thresh or self.pval escore_tol = self.escore_tol or mhg_cython.get_default_tol() es = mhg_cython.get_xlmhg_escore( self.indices, self.N, self.K, self.X, self.L...
[ "def", "escore", "(", "self", ")", ":", "hg_pval_thresh", "=", "self", ".", "escore_pval_thresh", "or", "self", ".", "pval", "escore_tol", "=", "self", ".", "escore_tol", "or", "mhg_cython", ".", "get_default_tol", "(", ")", "es", "=", "mhg_cython", ".", "...
46.5
14.25
def Beach(fm, linewidth=2, facecolor='b', bgcolor='w', edgecolor='k', alpha=1.0, xy=(0, 0), width=200, size=100, nofill=False, zorder=100, axes=None): """ Return a beach ball as a collection which can be connected to an current matplotlib axes instance (ax.add_collection). S1, D1, a...
[ "def", "Beach", "(", "fm", ",", "linewidth", "=", "2", ",", "facecolor", "=", "'b'", ",", "bgcolor", "=", "'w'", ",", "edgecolor", "=", "'k'", ",", "alpha", "=", "1.0", ",", "xy", "=", "(", "0", ",", "0", ")", ",", "width", "=", "200", ",", "...
42.542056
22.82243
def gen_keys(keysize=2048): ''' Generate Salt minion keys and return them as PEM file strings ''' # Mandate that keys are at least 2048 in size if keysize < 2048: keysize = 2048 tdir = tempfile.mkdtemp() salt.crypt.gen_keys(tdir, 'minion', keysize) priv_path = os.path.join(tdir,...
[ "def", "gen_keys", "(", "keysize", "=", "2048", ")", ":", "# Mandate that keys are at least 2048 in size", "if", "keysize", "<", "2048", ":", "keysize", "=", "2048", "tdir", "=", "tempfile", ".", "mkdtemp", "(", ")", "salt", ".", "crypt", ".", "gen_keys", "(...
35.111111
17.666667
def match(self, f, *args): """Match grammar function 'f' against next token and set 'self.matched'. Arguments: f: A grammar function - see efilter.parsers.common.grammar. Must return TokenMatch or None. args: Passed to 'f', if any. Returns: I...
[ "def", "match", "(", "self", ",", "f", ",", "*", "args", ")", ":", "try", ":", "match", "=", "f", "(", "self", ".", "tokenizer", ",", "*", "args", ")", "except", "StopIteration", ":", "# The grammar function might have tried to access more tokens than", "# are...
32.580645
22.806452