text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def apply_T5(word): '''If a (V)VVV-sequence contains a VV-sequence that could be an /i/-final diphthong, there is a syllable boundary between it and the third vowel, e.g., [raa.ois.sa], [huo.uim.me], [la.eis.sa], [sel.vi.äi.si], [tai.an], [säi.e], [oi.om.me].''' WORD = _split_consonants_and_vowels(w...
[ "def", "apply_T5", "(", "word", ")", ":", "WORD", "=", "_split_consonants_and_vowels", "(", "word", ")", "for", "k", ",", "v", "in", "WORD", ".", "iteritems", "(", ")", ":", "if", "len", "(", "v", ")", ">=", "3", "and", "is_vowel", "(", "v", "[", ...
29.833333
0.001353
def get_question_ids_for_assessment_part(self, assessment_part_id): """convenience method returns unique question ids associated with an assessment_part_id""" question_ids = [] for question_map in self._my_map['questions']: if question_map['assessmentPartId'] == str(assessment_part_i...
[ "def", "get_question_ids_for_assessment_part", "(", "self", ",", "assessment_part_id", ")", ":", "question_ids", "=", "[", "]", "for", "question_map", "in", "self", ".", "_my_map", "[", "'questions'", "]", ":", "if", "question_map", "[", "'assessmentPartId'", "]",...
62.285714
0.00905
def tarfile_to_pif(filename, temp_root_dir='', verbose=0): """ Process a tar file that contains DFT data. Input: filename - String, Path to the file to process. temp_root_dir - String, Directory in which to save temporary files. Defaults to working directory. verbose - int, How much...
[ "def", "tarfile_to_pif", "(", "filename", ",", "temp_root_dir", "=", "''", ",", "verbose", "=", "0", ")", ":", "temp_dir", "=", "temp_root_dir", "+", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "os", ".", "makedirs", "(", "temp_dir", ")", "try", ...
35.153846
0.00213
def update_account(self, email=None, company_name=None, first_name=None, last_name=None, address=None, postal_code=None, city=None, state=None, country=None, phone=None): """ :: POST /:login :param email: Email address :type email: :...
[ "def", "update_account", "(", "self", ",", "email", "=", "None", ",", "company_name", "=", "None", ",", "first_name", "=", "None", ",", "last_name", "=", "None", ",", "address", "=", "None", ",", "postal_code", "=", "None", ",", "city", "=", "None", ",...
29.625
0.008678
def chu_liu_edmonds(length: int, score_matrix: numpy.ndarray, current_nodes: List[bool], final_edges: Dict[int, int], old_input: numpy.ndarray, old_output: numpy.ndarray, representatives: List[Set[int...
[ "def", "chu_liu_edmonds", "(", "length", ":", "int", ",", "score_matrix", ":", "numpy", ".", "ndarray", ",", "current_nodes", ":", "List", "[", "bool", "]", ",", "final_edges", ":", "Dict", "[", "int", ",", "int", "]", ",", "old_input", ":", "numpy", "...
37.851613
0.000498
def list_create(self, title): """ Create a new list with the given `title`. Returns the `list dict`_ of the created list. """ params = self.__generate_params(locals()) return self.__api_request('POST', '/api/v1/lists', params)
[ "def", "list_create", "(", "self", ",", "title", ")", ":", "params", "=", "self", ".", "__generate_params", "(", "locals", "(", ")", ")", "return", "self", ".", "__api_request", "(", "'POST'", ",", "'/api/v1/lists'", ",", "params", ")" ]
34.5
0.010601
def resolve( expr, name=None, safe=DEFAULT_SAFE, tostr=DEFAULT_TOSTR, scope=DEFAULT_SCOPE, besteffort=DEFAULT_BESTEFFORT ): """Resolve an expression with possibly a dedicated expression resolvers. :param str name: expression resolver registered name. Default is the first registe...
[ "def", "resolve", "(", "expr", ",", "name", "=", "None", ",", "safe", "=", "DEFAULT_SAFE", ",", "tostr", "=", "DEFAULT_TOSTR", ",", "scope", "=", "DEFAULT_SCOPE", ",", "besteffort", "=", "DEFAULT_BESTEFFORT", ")", ":", "return", "_RESOLVER_REGISTRY", ".", "r...
38.083333
0.001067
def delete_vpc_peering_connection(name, conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' name Name of the state conn_id ID of the peering connection to delete. Exclusive with conn_name. conn_name The name of ...
[ "def", "delete_vpc_peering_connection", "(", "name", ",", "conn_id", "=", "None", ",", "conn_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "log", ".", "debug",...
26.517647
0.001711
def load_edited_source(self, source, good_cb=None, bad_cb=None, filename=None): """ Load changed code into the execution environment. Until the code is executed correctly, it will be in the 'tenuous' state. """ with LiveExecution.lock: self.good_cb = good_cb ...
[ "def", "load_edited_source", "(", "self", ",", "source", ",", "good_cb", "=", "None", ",", "bad_cb", "=", "None", ",", "filename", "=", "None", ")", ":", "with", "LiveExecution", ".", "lock", ":", "self", ".", "good_cb", "=", "good_cb", "self", ".", "b...
36.227273
0.002445
def classify(in_x, groups, labels, k): """分类""" # 计算欧式距离 gl = array_len(groups) tmp = tile(in_x, (gl, 1)) - groups tmp = exponential_operation(tmp, 2) tmp = array_sum(tmp) tmp = exponential_operation(tmp, 0.5) # 得到排序后的数组的索引 arg = argsort(tmp) # 计算最相似数据的前k个数据的分类次数 cc = odict...
[ "def", "classify", "(", "in_x", ",", "groups", ",", "labels", ",", "k", ")", ":", "# 计算欧式距离", "gl", "=", "array_len", "(", "groups", ")", "tmp", "=", "tile", "(", "in_x", ",", "(", "gl", ",", "1", ")", ")", "-", "groups", "tmp", "=", "exponential...
22.421053
0.002252
def rect(self): """rect(self) -> PyObject *""" CheckParent(self) val = _fitz.Link_rect(self) val = Rect(val) return val
[ "def", "rect", "(", "self", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Link_rect", "(", "self", ")", "val", "=", "Rect", "(", "val", ")", "return", "val" ]
19.25
0.012422
def get_imag_self_energy(interaction, grid_points, sigmas, frequency_step=None, num_frequency_points=None, temperatures=None, scattering_event_class=None, # class 1 or 2...
[ "def", "get_imag_self_energy", "(", "interaction", ",", "grid_points", ",", "sigmas", ",", "frequency_step", "=", "None", ",", "num_frequency_points", "=", "None", ",", "temperatures", "=", "None", ",", "scattering_event_class", "=", "None", ",", "# class 1 or 2", ...
37.248276
0.000361
def _perform_insertions(self, initial, max_cost): """ возвращает все трансдукции стоимости <= max_cost, которые можно получить из элементов initial Аргументы: ---------- initial : list of tuples список исходных трансдукций вида [(трансдукция, стоимость)] ...
[ "def", "_perform_insertions", "(", "self", ",", "initial", ",", "max_cost", ")", ":", "queue", "=", "list", "(", "initial", ")", "final", "=", "initial", "while", "len", "(", "queue", ")", ">", "0", ":", "transduction", ",", "cost", "=", "queue", "[", ...
36.068966
0.001862
def image_to_string(image, lang=None, boxes=False): ''' Runs tesseract on the specified image. First, the image is written to disk, and then the tesseract command is run on the image. Resseract's result is read, and the temporary files are erased. ''' input_file_name = '%s.bmp' % tempnam() ...
[ "def", "image_to_string", "(", "image", ",", "lang", "=", "None", ",", "boxes", "=", "False", ")", ":", "input_file_name", "=", "'%s.bmp'", "%", "tempnam", "(", ")", "output_file_name_base", "=", "tempnam", "(", ")", "if", "not", "boxes", ":", "output_file...
34.774194
0.000903
def ijk_ljk_to_ilk(A, B): """ Faster version of einsum np.einsum('ijk,ljk->ilk', A, B) I.e A.dot(B.T) for every dimension """ res = np.zeros((A.shape[-1], A.shape[0], B.shape[0])) [np.dot(A[:,:,i], B[:,:,i].T, out=res[i,:,:]) for i in range(A.shape[-1])] res = res.swapaxes(0, 2).swapaxes(0,...
[ "def", "ijk_ljk_to_ilk", "(", "A", ",", "B", ")", ":", "res", "=", "np", ".", "zeros", "(", "(", "A", ".", "shape", "[", "-", "1", "]", ",", "A", ".", "shape", "[", "0", "]", ",", "B", ".", "shape", "[", "0", "]", ")", ")", "[", "np", "...
32.8
0.023739
def set_value(self, value: ScalarType) -> None: """Sets the value of the node to a scalar value. After this, is_scalar(type(value)) will return true. Args: value: The value to set this node to, a str, int, float, \ bool, or None. """ if isinstanc...
[ "def", "set_value", "(", "self", ",", "value", ":", "ScalarType", ")", "->", "None", ":", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "value_str", "=", "'true'", "if", "value", "else", "'false'", "else", ":", "value_str", "=", "str", "(", ...
40.869565
0.002079
def display_dialog(self, *args, **kwargs): """Display form and success message when set""" form = kwargs.pop('form_instance', None) success_message = kwargs.pop('success_message', None) if not form: form = self.get_form_class()(initial=kwargs, instance=self.object) ...
[ "def", "display_dialog", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "form", "=", "kwargs", ".", "pop", "(", "'form_instance'", ",", "None", ")", "success_message", "=", "kwargs", ".", "pop", "(", "'success_message'", ",", "None", ...
36.125
0.002247
def _get_data_from_table(source, fields='*', first_row=0, count=-1, schema=None): """ Helper function for _get_data that handles BQ Tables. """ if not source.exists(): return _get_data_from_empty_list(source, fields, first_row, count) if schema is None: schema = source.schema fields = get_field_list(fie...
[ "def", "_get_data_from_table", "(", "source", ",", "fields", "=", "'*'", ",", "first_row", "=", "0", ",", "count", "=", "-", "1", ",", "schema", "=", "None", ")", ":", "if", "not", "source", ".", "exists", "(", ")", ":", "return", "_get_data_from_empty...
54.7
0.017986
def proximal_composition(proximal, operator, mu): r"""Proximal operator factory of functional composed with unitary operator. For a functional ``F`` and a linear unitary `Operator` ``L`` this is the factory for the proximal operator of ``F * L``. Parameters ---------- proximal : callable ...
[ "def", "proximal_composition", "(", "proximal", ",", "operator", ",", "mu", ")", ":", "def", "proximal_composition_factory", "(", "sigma", ")", ":", "\"\"\"Create proximal for the dual with a given sigma\n\n Parameters\n ----------\n sigma : positive float\n ...
31.055556
0.000433
def create_exclude_rules(args): """Creates the exlude rules """ global _cached_exclude_rules if _cached_exclude_rules is not None: return _cached_exclude_rules rules = [] for excl_path in args.exclude: abspath = os.path.abspath(os.path.join(args.root, excl_path)) rules.ap...
[ "def", "create_exclude_rules", "(", "args", ")", ":", "global", "_cached_exclude_rules", "if", "_cached_exclude_rules", "is", "not", "None", ":", "return", "_cached_exclude_rules", "rules", "=", "[", "]", "for", "excl_path", "in", "args", ".", "exclude", ":", "a...
37.733333
0.001724
def tags_in_string(msg): """ Return the set of tags in a message string. Tags includes HTML tags, data placeholders, etc. Skips tags that might change due to translations: HTML entities, <abbr>, and so on. """ def is_linguistic_tag(tag): """Is this tag one that can change with the...
[ "def", "tags_in_string", "(", "msg", ")", ":", "def", "is_linguistic_tag", "(", "tag", ")", ":", "\"\"\"Is this tag one that can change with the language?\"\"\"", "if", "tag", ".", "startswith", "(", "\"&\"", ")", ":", "return", "True", "if", "any", "(", "x", "i...
29.4
0.001647
def make_file_exist(self): """Make sure the parent directory exists, then touch the file""" self.parent.make_directory_exist() self.parent.touch_file(self.name) return self
[ "def", "make_file_exist", "(", "self", ")", ":", "self", ".", "parent", ".", "make_directory_exist", "(", ")", "self", ".", "parent", ".", "touch_file", "(", "self", ".", "name", ")", "return", "self" ]
40
0.009804
def build_help_html(): """Build the help HTML using the shared resources.""" remove_from_help = ["not-in-help", "copyright"] if sys.platform in ["win32", "cygwin"]: remove_from_help.extend(["osx", "linux"]) elif sys.platform == "darwin": remove_from_help.extend(["linux", "windows", "linu...
[ "def", "build_help_html", "(", ")", ":", "remove_from_help", "=", "[", "\"not-in-help\"", ",", "\"copyright\"", "]", "if", "sys", ".", "platform", "in", "[", "\"win32\"", ",", "\"cygwin\"", "]", ":", "remove_from_help", ".", "extend", "(", "[", "\"osx\"", ",...
49.111111
0.002219
def read_serialized_rsa_pub_key(serialized): """ Reads serialized RSA pub key TAG|len-2B|value. 81 = exponent, 82 = modulus :param serialized: :return: n, e """ n = None e = None rsa = from_hex(serialized) pos = 0 ln = len(rsa) ...
[ "def", "read_serialized_rsa_pub_key", "(", "serialized", ")", ":", "n", "=", "None", "e", "=", "None", "rsa", "=", "from_hex", "(", "serialized", ")", "pos", "=", "0", "ln", "=", "len", "(", "rsa", ")", "while", "pos", "<", "ln", ":", "tag", "=", "...
25.5625
0.002356
def latex2text(content, tolerant_parsing=False, keep_inline_math=False, keep_comments=False): """ Extracts text from `content` meant for database indexing. `content` is some LaTeX code. .. deprecated:: 1.0 Please use :py:class:`LatexNodes2Text` instead. """ (nodelist, tpos, tlen) = late...
[ "def", "latex2text", "(", "content", ",", "tolerant_parsing", "=", "False", ",", "keep_inline_math", "=", "False", ",", "keep_comments", "=", "False", ")", ":", "(", "nodelist", ",", "tpos", ",", "tlen", ")", "=", "latexwalker", ".", "get_latex_nodes", "(", ...
43.769231
0.008606
def write(self): """Dump JSON to file""" with open(self.log_path, "w") as f: json.dump(self.log_dict, f, indent=1)
[ "def", "write", "(", "self", ")", ":", "with", "open", "(", "self", ".", "log_path", ",", "\"w\"", ")", "as", "f", ":", "json", ".", "dump", "(", "self", ".", "log_dict", ",", "f", ",", "indent", "=", "1", ")" ]
34.75
0.014085
def get_rules_import_paths(): """Yields all rules import paths. :rtype: Iterable[Path] """ # Bundled rules: yield Path(__file__).parent.joinpath('rules') # Rules defined by user: yield settings.user_dir.joinpath('rules') # Packages with third-party rules: for path in sys.path: ...
[ "def", "get_rules_import_paths", "(", ")", ":", "# Bundled rules:", "yield", "Path", "(", "__file__", ")", ".", "parent", ".", "joinpath", "(", "'rules'", ")", "# Rules defined by user:", "yield", "settings", ".", "user_dir", ".", "joinpath", "(", "'rules'", ")"...
31.5
0.001927
def _make_api_call(self, method, url, json_params=None): """ Performs the REST API Call :param method: HTTP Method :param url: The URL :param json_params: The parameters intended to be JSON serialized :return: """ if self.verbose is True: prin...
[ "def", "_make_api_call", "(", "self", ",", "method", ",", "url", ",", "json_params", "=", "None", ")", ":", "if", "self", ".", "verbose", "is", "True", ":", "print", "\"\\ncrossbarhttp: Request: %s %s\"", "%", "(", "method", ",", "url", ")", "if", "json_pa...
36.472727
0.002427
def __ngrams(s, n=3): """ Raw n-grams from a sequence If the sequence is a string, it will return char-level n-grams. If the sequence is a list of words, it will return word-level n-grams. Note: it treats space (' ') and punctuation like any other character. >>> ngrams('This i...
[ "def", "__ngrams", "(", "s", ",", "n", "=", "3", ")", ":", "return", "list", "(", "zip", "(", "*", "[", "s", "[", "i", ":", "]", "for", "i", "in", "range", "(", "n", ")", "]", ")", ")" ]
41.52
0.001883
def import_participant_element(diagram_graph, participants_dictionary, participant_element): """ Adds 'participant' element to the collaboration dictionary. :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param participants_dictionary: dictionary with particip...
[ "def", "import_participant_element", "(", "diagram_graph", ",", "participants_dictionary", ",", "participant_element", ")", ":", "participant_id", "=", "participant_element", ".", "getAttribute", "(", "consts", ".", "Consts", ".", "id", ")", "name", "=", "participant_...
68.588235
0.00846
def _load_lines(self, filename, line_generator, suite, rules): """Load a suite with lines produced by the line generator.""" line_counter = 0 for line in line_generator: line_counter += 1 if line.category in self.ignored_lines: continue if li...
[ "def", "_load_lines", "(", "self", ",", "filename", ",", "line_generator", ",", "suite", ",", "rules", ")", ":", "line_counter", "=", "0", "for", "line", "in", "line_generator", ":", "line_counter", "+=", "1", "if", "line", ".", "category", "in", "self", ...
35.12
0.002217
def _write_var_data_nonsparse(self, f, zVar, var, dataType, numElems, recVary, compression, blockingfactor, indata): ''' Creates VVRs and the corresponding VXRs full of "indata" data. If there is no compression, creates exactly one VXR and VVR If there i...
[ "def", "_write_var_data_nonsparse", "(", "self", ",", "f", ",", "zVar", ",", "var", ",", "dataType", ",", "numElems", ",", "recVary", ",", "compression", ",", "blockingfactor", ",", "indata", ")", ":", "numValues", "=", "self", ".", "_num_values", "(", "zV...
42.012987
0.000906
def update_firewall(self, firewall, body=None): """Updates a firewall.""" return self.put(self.firewall_path % (firewall), body=body)
[ "def", "update_firewall", "(", "self", ",", "firewall", ",", "body", "=", "None", ")", ":", "return", "self", ".", "put", "(", "self", ".", "firewall_path", "%", "(", "firewall", ")", ",", "body", "=", "body", ")" ]
49
0.013423
def _format_dict(self, info_dict): """Replaces empty content with 'NA's""" for key, value in info_dict.items(): if not value: info_dict[key] = "NA" return info_dict
[ "def", "_format_dict", "(", "self", ",", "info_dict", ")", ":", "for", "key", ",", "value", "in", "info_dict", ".", "items", "(", ")", ":", "if", "not", "value", ":", "info_dict", "[", "key", "]", "=", "\"NA\"", "return", "info_dict" ]
35.166667
0.009259
def merge_continued_lines(lines): """Given a list of numered Fortran source code lines, i.e., pairs of the form (n, code_line) where n is a line number and code_line is a line of code, merge_continued_lines() merges sequences of lines that are indicated to be continuation lines. """ # ...
[ "def", "merge_continued_lines", "(", "lines", ")", ":", "# Before a continuation line L1 is merged with the line L0 before it (and", "# presumably the one L1 is continuing), ensure that L0 is not a comment.", "# If L0 is a comment, swap L0 and L1.", "chg", "=", "True", "while", "chg", ":...
35.348837
0.00064
def smallest_prime_factor(Q): """Find the smallest number factorable by the small primes 2, 3, 4, and 7 that is larger than the argument Q""" A = Q; while(A != 1): if(np.mod(A, 2) == 0): A = A / 2 elif(np.mod(A, 3) == 0): A = A / 3 elif(np.mod(...
[ "def", "smallest_prime_factor", "(", "Q", ")", ":", "A", "=", "Q", "while", "(", "A", "!=", "1", ")", ":", "if", "(", "np", ".", "mod", "(", "A", ",", "2", ")", "==", "0", ")", ":", "A", "=", "A", "/", "2", "elif", "(", "np", ".", "mod", ...
24.736842
0.012295
def update(self, app_id, data): """Update app identified by app_id with data :params: * app_id (int) id in the marketplace received with :method:`create` * data (dict) some keys are required: * *name*: the title of the app. Maximum length 127 ch...
[ "def", "update", "(", "self", ",", "app_id", ",", "data", ")", ":", "assert", "(", "'name'", "in", "data", "and", "data", "[", "'name'", "]", "and", "'summary'", "in", "data", "and", "'categories'", "in", "data", "and", "data", "[", "'categories'", "]"...
44.857143
0.001247
def modify_kls(self, name): """Add a part to what will end up being the kls' superclass""" if self.kls is None: self.kls = name else: self.kls += name
[ "def", "modify_kls", "(", "self", ",", "name", ")", ":", "if", "self", ".", "kls", "is", "None", ":", "self", ".", "kls", "=", "name", "else", ":", "self", ".", "kls", "+=", "name" ]
32.166667
0.010101
def Alphanumeric(msg=None): ''' Checks whether a value is: - int, or - long, or - float without a fractional part, or - str or unicode composed only of alphanumeric characters ''' def fn(value): if not any([ isinstance(value, numbers.Integral), ...
[ "def", "Alphanumeric", "(", "msg", "=", "None", ")", ":", "def", "fn", "(", "value", ")", ":", "if", "not", "any", "(", "[", "isinstance", "(", "value", ",", "numbers", ".", "Integral", ")", ",", "(", "isinstance", "(", "value", ",", "float", ")", ...
30.4
0.001595
def check_query(query): """ Check query sanity Args: query: query string Returns: None """ q = query.lower() if "select " not in q: raise InvalidQuery("SELECT word not found in the query: {0}".format(query)) if " from " not in q: raise InvalidQuery("FROM wor...
[ "def", "check_query", "(", "query", ")", ":", "q", "=", "query", ".", "lower", "(", ")", "if", "\"select \"", "not", "in", "q", ":", "raise", "InvalidQuery", "(", "\"SELECT word not found in the query: {0}\"", ".", "format", "(", "query", ")", ")", "if", "...
25.142857
0.008219
def _is_pingable(ip): """Checks whether an IP address is reachable by pinging. Use linux utils to execute the ping (ICMP ECHO) command. Sends 5 packets with an interval of 0.2 seconds and timeout of 1 seconds. Runtime error implies unreachability else IP is pingable. :param ip: IP to check :ret...
[ "def", "_is_pingable", "(", "ip", ")", ":", "ping_cmd", "=", "[", "'ping'", ",", "'-c'", ",", "'5'", ",", "'-W'", ",", "'1'", ",", "'-i'", ",", "'0.2'", ",", "ip", "]", "try", ":", "linux_utils", ".", "execute", "(", "ping_cmd", ",", "check_exit_code...
33.8
0.001439
def chmod_plus_x(path): """Equivalent of unix `chmod a+x path`""" path_mode = os.stat(path).st_mode path_mode &= int('777', 8) if path_mode & stat.S_IRUSR: path_mode |= stat.S_IXUSR if path_mode & stat.S_IRGRP: path_mode |= stat.S_IXGRP if path_mode & stat.S_IROTH: path_mode |= stat.S_IXOTH os...
[ "def", "chmod_plus_x", "(", "path", ")", ":", "path_mode", "=", "os", ".", "stat", "(", "path", ")", ".", "st_mode", "path_mode", "&=", "int", "(", "'777'", ",", "8", ")", "if", "path_mode", "&", "stat", ".", "S_IRUSR", ":", "path_mode", "|=", "stat"...
30.272727
0.023324
def nn_dims(self, x, y, dims_x, dims_y, k=1, radius=np.inf, eps=0.0, p=2): """Find the k nearest neighbors of a subset of dims of x and y in the observed output data @see Databag.nn() for argument description @return distance and indexes of found nearest neighbors. """ assert le...
[ "def", "nn_dims", "(", "self", ",", "x", ",", "y", ",", "dims_x", ",", "dims_y", ",", "k", "=", "1", ",", "radius", "=", "np", ".", "inf", ",", "eps", "=", "0.0", ",", "p", "=", "2", ")", ":", "assert", "len", "(", "x", ")", "==", "len", ...
56.904762
0.01893
def spDiff(SP1,SP2): """ Function that compares two spatial pooler instances. Compares the static variables between the two poolers to make sure that they are equivalent. Parameters ----------------------------------------- SP1 first spatial pooler to be compared SP2 second spatial pooler ...
[ "def", "spDiff", "(", "SP1", ",", "SP2", ")", ":", "if", "(", "len", "(", "SP1", ".", "_masterConnectedM", ")", "!=", "len", "(", "SP2", ".", "_masterConnectedM", ")", ")", ":", "print", "\"Connected synapse matrices are different sizes\"", "return", "False", ...
35.089744
0.010661
def rgb_to_ryb(hue): """Maps a hue on the RGB color wheel to Itten's RYB wheel. Parameters: :hue: The hue on the RGB color wheel [0...360] Returns: An approximation of the corresponding hue on Itten's RYB wheel. >>> rgb_to_ryb(15) 26.0 """ d = hue % 15 i = int(hue / 15) x0 = _RybWhee...
[ "def", "rgb_to_ryb", "(", "hue", ")", ":", "d", "=", "hue", "%", "15", "i", "=", "int", "(", "hue", "/", "15", ")", "x0", "=", "_RybWheel", "[", "i", "]", "x1", "=", "_RybWheel", "[", "i", "+", "1", "]", "return", "x0", "+", "(", "x1", "-",...
18.894737
0.018568
def to_primitive(value, convert_instances=False, convert_datetime=True, level=0, max_depth=3): """Convert a complex object into primitives. Handy for JSON serialization. We can optionally handle instances, but since this is a recursive function, we could have cyclical data structures. ...
[ "def", "to_primitive", "(", "value", ",", "convert_instances", "=", "False", ",", "convert_datetime", "=", "True", ",", "level", "=", "0", ",", "max_depth", "=", "3", ")", ":", "# handle obvious types first - order of basic types determined by running", "# full tests on...
41.021277
0.000253
def job(func_or_queue, connection=None, *args, **kwargs): """This decorator does all what django_rq's one, plus it group all logged messages using uuid and sets job_name field as well.""" decorated_func = _job(func_or_queue, connection=connection, *args, **kwargs) if callable(func_or_queue): ...
[ "def", "job", "(", "func_or_queue", ",", "connection", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "decorated_func", "=", "_job", "(", "func_or_queue", ",", "connection", "=", "connection", ",", "*", "args", ",", "*", "*", "kwargs...
38.73913
0.002191
def Lr(self,value): """ set row rotation """ assert value.shape[0]==self._N, 'dimension mismatch' assert value.shape[1]==self._N, 'dimension mismatch' self._Lr = value self.clear_cache('Fstar','Ystar1','Ystar','Yhat','Xstar','Xhat', 'Areml','Areml_eigh','...
[ "def", "Lr", "(", "self", ",", "value", ")", ":", "assert", "value", ".", "shape", "[", "0", "]", "==", "self", ".", "_N", ",", "'dimension mismatch'", "assert", "value", ".", "shape", "[", "1", "]", "==", "self", ".", "_N", ",", "'dimension mismatch...
57
0.037677
def collect_yarn_application_diagnostics(self, *application_ids): """ DEPRECATED: use create_yarn_application_diagnostics_bundle on the Yarn service. Deprecated since v10. Collects the Diagnostics data for Yarn applications. @param application_ids: An array of strings containing the ids of the ...
[ "def", "collect_yarn_application_diagnostics", "(", "self", ",", "*", "application_ids", ")", ":", "args", "=", "dict", "(", "applicationIds", "=", "application_ids", ")", "return", "self", ".", "_cmd", "(", "'yarnApplicationDiagnosticsCollection'", ",", "api_version"...
43.076923
0.008741
def _double_as_bytes(dval): "Use struct.unpack to decode a double precision float into eight bytes" tmp = list(struct.unpack('8B',struct.pack('d', dval))) if not _big_endian: tmp.reverse() return tmp
[ "def", "_double_as_bytes", "(", "dval", ")", ":", "tmp", "=", "list", "(", "struct", ".", "unpack", "(", "'8B'", ",", "struct", ".", "pack", "(", "'d'", ",", "dval", ")", ")", ")", "if", "not", "_big_endian", ":", "tmp", ".", "reverse", "(", ")", ...
36.333333
0.008969
def text_alignment(x, y): """ Align text labels based on the x- and y-axis coordinate values. This function is used for computing the appropriate alignment of the text label. For example, if the text is on the "right" side of the plot, we want it to be left-aligned. If the text is on the "top"...
[ "def", "text_alignment", "(", "x", ",", "y", ")", ":", "if", "x", "==", "0", ":", "ha", "=", "\"center\"", "elif", "x", ">", "0", ":", "ha", "=", "\"left\"", "else", ":", "ha", "=", "\"right\"", "if", "y", "==", "0", ":", "va", "=", "\"center\"...
26.034483
0.001277
def install(self, param, author=None, constraints=None, origin=''): """Install by url or name""" if isinstance(param, SkillEntry): skill = param else: skill = self.find_skill(param, author) entry = build_skill_entry(skill.name, origin, skill.is_beta) try: ...
[ "def", "install", "(", "self", ",", "param", ",", "author", "=", "None", ",", "constraints", "=", "None", ",", "origin", "=", "''", ")", ":", "if", "isinstance", "(", "param", ",", "SkillEntry", ")", ":", "skill", "=", "param", "else", ":", "skill", ...
36.16
0.002155
def patch_anchors(parser, show_progressbar): """ Consume ``ParseEntry``s then patch docs for TOCs by calling *parser*'s ``find_and_patch_entry``. """ files = defaultdict(list) try: while True: pentry = (yield) try: fname, anchor = pentry.path.split...
[ "def", "patch_anchors", "(", "parser", ",", "show_progressbar", ")", ":", "files", "=", "defaultdict", "(", "list", ")", "try", ":", "while", "True", ":", "pentry", "=", "(", "yield", ")", "try", ":", "fname", ",", "anchor", "=", "pentry", ".", "path",...
34.644444
0.000624
def override_environment(settings, **kwargs): # type: (Settings, **str) -> Generator """ Override env vars and reload the Settings object NOTE: Obviously this context has to be in place before you import any module which reads env values at import time. NOTE: The values in `kwargs` mus...
[ "def", "override_environment", "(", "settings", ",", "*", "*", "kwargs", ")", ":", "# type: (Settings, **str) -> Generator", "old_env", "=", "os", ".", "environ", ".", "copy", "(", ")", "os", ".", "environ", ".", "update", "(", "kwargs", ")", "settings", "."...
23.862069
0.001389
def set_blend_equation(self, mode_rgb, mode_alpha=None): """Specify the equation for RGB and alpha blending Parameters ---------- mode_rgb : str Mode for RGB. mode_alpha : str | None Mode for Alpha. If None, ``mode_rgb`` is used. Notes ...
[ "def", "set_blend_equation", "(", "self", ",", "mode_rgb", ",", "mode_alpha", "=", "None", ")", ":", "mode_alpha", "=", "mode_rgb", "if", "mode_alpha", "is", "None", "else", "mode_alpha", "self", ".", "glir", ".", "command", "(", "'FUNC'", ",", "'glBlendEqua...
32.764706
0.008726
def distance_corr(x, y, tail='upper', n_boot=1000, seed=None): """Distance correlation between two arrays. Statistical significance (p-value) is evaluated with a permutation test. Parameters ---------- x, y : np.ndarray 1D or 2D input arrays, shape (n_samples, n_features). x and y ...
[ "def", "distance_corr", "(", "x", ",", "y", ",", "tail", "=", "'upper'", ",", "n_boot", "=", "1000", ",", "seed", "=", "None", ")", ":", "assert", "tail", "in", "[", "'upper'", ",", "'lower'", ",", "'two-sided'", "]", ",", "'Wrong tail argument.'", "x"...
33.257353
0.000215
def get_row(self, index, default=None): """Return the row at the given index or the default value.""" if not isinstance(index, int) or index < 0 or index >= len(self._rows): return default return self._rows[index]
[ "def", "get_row", "(", "self", ",", "index", ",", "default", "=", "None", ")", ":", "if", "not", "isinstance", "(", "index", ",", "int", ")", "or", "index", "<", "0", "or", "index", ">=", "len", "(", "self", ".", "_rows", ")", ":", "return", "def...
49
0.008032
def data_check(data,target): """ Checks data type Parameters ---------- data : pd.DataFrame or np.array Field to specify the time series data that will be used. target : int or str Target column Returns ---------- transformed_data : np.array Raw dat...
[ "def", "data_check", "(", "data", ",", "target", ")", ":", "# Check pandas or numpy", "if", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", "or", "isinstance", "(", "data", ",", "pd", ".", "core", ".", "frame", ".", "DataFrame", ")", ":", ...
30.425926
0.010613
def popen_wrapper(args): """ Friendly wrapper around Popen. Returns stdout output, stderr output and OS status code. """ try: p = Popen(args, shell=False, stdout=PIPE, stderr=PIPE, close_fds=os.name != 'nt', ...
[ "def", "popen_wrapper", "(", "args", ")", ":", "try", ":", "p", "=", "Popen", "(", "args", ",", "shell", "=", "False", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ",", "close_fds", "=", "os", ".", "name", "!=", "'nt'", ",", "universal_n...
25.909091
0.001692
def send_command(self, command): """Send a command for FastAGI request: :param command: Command to launch on FastAGI request. Ex: 'EXEC StartMusicOnHolds' :type command: String :Example: :: @asyncio.coroutine def call_waiting(request): ...
[ "def", "send_command", "(", "self", ",", "command", ")", ":", "command", "+=", "'\\n'", "self", ".", "writer", ".", "write", "(", "command", ".", "encode", "(", "self", ".", "encoding", ")", ")", "yield", "from", "self", ".", "writer", ".", "drain", ...
36.848485
0.002404
def get_reusable_executor(max_workers=None, context=None, timeout=10, kill_workers=False, reuse="auto", job_reducers=None, result_reducers=None, initializer=None, initargs=()): """Return the current ReusableExectutor instance. Start ...
[ "def", "get_reusable_executor", "(", "max_workers", "=", "None", ",", "context", "=", "None", ",", "timeout", "=", "10", ",", "kill_workers", "=", "False", ",", "reuse", "=", "\"auto\"", ",", "job_reducers", "=", "None", ",", "result_reducers", "=", "None", ...
45.168421
0.000228
def ast_parse(self, source, filename='<unknown>', symbol='exec'): """Parse code to an AST with the current compiler flags active. Arguments are exactly the same as ast.parse (in the standard library), and are passed to the built-in compile function.""" return compile(source, fil...
[ "def", "ast_parse", "(", "self", ",", "source", ",", "filename", "=", "'<unknown>'", ",", "symbol", "=", "'exec'", ")", ":", "return", "compile", "(", "source", ",", "filename", ",", "symbol", ",", "self", ".", "flags", "|", "PyCF_ONLY_AST", ",", "1", ...
60
0.008219
def nmget(o, key_path, def_val=None, path_delimiter='.', null_as_default=True): ''' A short-hand for retrieving a value from nested mappings ("nested-mapping-get"). At each level it checks if the given "path" component in the given key exists and return the default value whenever fails. Exampl...
[ "def", "nmget", "(", "o", ",", "key_path", ",", "def_val", "=", "None", ",", "path_delimiter", "=", "'.'", ",", "null_as_default", "=", "True", ")", ":", "pieces", "=", "key_path", ".", "split", "(", "path_delimiter", ")", "while", "pieces", ":", "p", ...
26.096774
0.001192
def make_duplicate_request(request): """ Since werkzeug request objects are immutable, this is needed to create an identical reuet object with immutable values so it can be retried after a POST failure. """ class FakeRequest(object): method = 'GET' path = request.path hea...
[ "def", "make_duplicate_request", "(", "request", ")", ":", "class", "FakeRequest", "(", "object", ")", ":", "method", "=", "'GET'", "path", "=", "request", ".", "path", "headers", "=", "request", ".", "headers", "GET", "=", "request", ".", "GET", "POST", ...
32.375
0.001876
def get_layer_ids(element): """ returns the layer ids from a SaltElement (i.e. a node, edge or layer). Parameters ---------- element : lxml.etree._Element an etree element parsed from a SaltXML document Returns ------- layers: list of int list of layer indices. list mig...
[ "def", "get_layer_ids", "(", "element", ")", ":", "layers", "=", "[", "]", "if", "element", ".", "xpath", "(", "'@layers'", ")", ":", "layers_string", "=", "element", ".", "xpath", "(", "'@layers'", ")", "[", "0", "]", "for", "layer_string", "in", "lay...
28.809524
0.0016
def gradient(self): """Gradient operator of the functional. The gradient is not defined in points where one or more components are less than or equal to 0. """ functional = self class KLCrossEntropyGradient(Operator): """The gradient operator of this functi...
[ "def", "gradient", "(", "self", ")", ":", "functional", "=", "self", "class", "KLCrossEntropyGradient", "(", "Operator", ")", ":", "\"\"\"The gradient operator of this functional.\"\"\"", "def", "__init__", "(", "self", ")", ":", "\"\"\"Initialize a new instance.\"\"\"", ...
37.052632
0.001384
def _get_lonely_contract(self): """Get contract number when we have only one contract.""" contracts = {} try: raw_res = yield from self._session.get(MAIN_URL, timeout=self._timeout) except OSError: raise PyHydroQu...
[ "def", "_get_lonely_contract", "(", "self", ")", ":", "contracts", "=", "{", "}", "try", ":", "raw_res", "=", "yield", "from", "self", ".", "_session", ".", "get", "(", "MAIN_URL", ",", "timeout", "=", "self", ".", "_timeout", ")", "except", "OSError", ...
40.954545
0.002169
def modify_subcommand(selected_vcard, input_from_stdin_or_file, open_editor): """Modify a contact in an external editor. :param selected_vcard: the contact to modify :type selected_vcard: carddav_object.CarddavObject :param input_from_stdin_or_file: new data from stdin (or a file) that should b...
[ "def", "modify_subcommand", "(", "selected_vcard", ",", "input_from_stdin_or_file", ",", "open_editor", ")", ":", "# show warning, if vcard version of selected contact is not 3.0 or 4.0", "if", "selected_vcard", ".", "get_version", "(", ")", "not", "in", "config", ".", "sup...
43.04918
0.000372
def exec_after_request_actions(actions, response, **kwargs): """Executes actions of the "after" and "after_METHOD" groups. A "response" var will be injected in the current context. """ current_context["response"] = response groups = ("after_" + flask.request.method.lower(), "after") try: ...
[ "def", "exec_after_request_actions", "(", "actions", ",", "response", ",", "*", "*", "kwargs", ")", ":", "current_context", "[", "\"response\"", "]", "=", "response", "groups", "=", "(", "\"after_\"", "+", "flask", ".", "request", ".", "method", ".", "lower"...
36.692308
0.002045
def add_files_via_url(self, dataset_key, files={}): """Add or update dataset files linked to source URLs :param dataset_key: Dataset identifier, in the form of owner/id :type dataset_key: str :param files: Dict containing the name of files and metadata Uses file name as a di...
[ "def", "add_files_via_url", "(", "self", ",", "dataset_key", ",", "files", "=", "{", "}", ")", ":", "file_requests", "=", "[", "_swagger", ".", "FileCreateOrUpdateRequest", "(", "name", "=", "file_name", ",", "source", "=", "_swagger", ".", "FileSourceCreateOr...
43.65
0.00112
def batches(dataset): '''Returns a callable that chooses sequences from netcdf data.''' seq_lengths = dataset.variables['seqLengths'].data seq_begins = np.concatenate(([0], np.cumsum(seq_lengths)[:-1])) def sample(): chosen = np.random.choice( list(range(len(seq_lengths))), BATCH_SI...
[ "def", "batches", "(", "dataset", ")", ":", "seq_lengths", "=", "dataset", ".", "variables", "[", "'seqLengths'", "]", ".", "data", "seq_begins", "=", "np", ".", "concatenate", "(", "(", "[", "0", "]", ",", "np", ".", "cumsum", "(", "seq_lengths", ")",...
39.714286
0.001757
def preview(self, argv): """Retrieve the preview for the specified search jobs.""" opts = cmdline(argv, FLAGS_RESULTS) self.foreach(opts.args, lambda job: output(job.preview(**opts.kwargs)))
[ "def", "preview", "(", "self", ",", "argv", ")", ":", "opts", "=", "cmdline", "(", "argv", ",", "FLAGS_RESULTS", ")", "self", ".", "foreach", "(", "opts", ".", "args", ",", "lambda", "job", ":", "output", "(", "job", ".", "preview", "(", "*", "*", ...
44.6
0.017621
def find_descendants_by_text_re(self, parent, re, immediate=False): """ :param parent: The parent element into which to search. :type parent: :class:`selenium.webdriver.remote.webelement.WebElement` or :class:`str`. When a string is specified, it ...
[ "def", "find_descendants_by_text_re", "(", "self", ",", "parent", ",", "re", ",", "immediate", "=", "False", ")", ":", "def", "cond", "(", "*", "_", ")", ":", "return", "self", ".", "driver", ".", "execute_script", "(", "\"\"\"\n var parent = argume...
44.294118
0.0013
def get_figuresize(fs, fsdef=(12,6), orient='landscape', method='xrandr'): """ Generic function to return figure size in inches Useful for str-based flags such as: - 'a4' : use orient='portrait' or 'landscape' - 'full': to get screen size use meth...
[ "def", "get_figuresize", "(", "fs", ",", "fsdef", "=", "(", "12", ",", "6", ")", ",", "orient", "=", "'landscape'", ",", "method", "=", "'xrandr'", ")", ":", "assert", "fs", "is", "None", "or", "type", "(", "fs", ")", "in", "[", "str", ",", "tupl...
39.04878
0.01036
def setsemod(module, state): ''' Enable or disable an SELinux module. CLI Example: .. code-block:: bash salt '*' selinux.setsemod nagios Enabled .. versionadded:: 2016.3.0 ''' if state.lower() == 'enabled': cmd = 'semodule -e {0}'.format(module) elif state.lower() == ...
[ "def", "setsemod", "(", "module", ",", "state", ")", ":", "if", "state", ".", "lower", "(", ")", "==", "'enabled'", ":", "cmd", "=", "'semodule -e {0}'", ".", "format", "(", "module", ")", "elif", "state", ".", "lower", "(", ")", "==", "'disabled'", ...
23.882353
0.00237
def get_encoding(headers, content): """Get encoding from request headers or page head.""" encoding = None content_type = headers.get('content-type') if content_type: _, params = cgi.parse_header(content_type) if 'charset' in params: encoding = params['charset'].strip("'\"") ...
[ "def", "get_encoding", "(", "headers", ",", "content", ")", ":", "encoding", "=", "None", "content_type", "=", "headers", ".", "get", "(", "'content-type'", ")", "if", "content_type", ":", "_", ",", "params", "=", "cgi", ".", "parse_header", "(", "content_...
38.333333
0.00106
def pathFromHere_walk(self, astr_startPath = '/'): """ Return a list of paths from "here" in the stree, using the internal cd() to walk the path space. :return: a list of paths from "here" """ self.l_lwd = [] self.treeWalk(startPath ...
[ "def", "pathFromHere_walk", "(", "self", ",", "astr_startPath", "=", "'/'", ")", ":", "self", ".", "l_lwd", "=", "[", "]", "self", ".", "treeWalk", "(", "startPath", "=", "astr_startPath", ",", "f", "=", "self", ".", "lwd", ")", "return", "self", ".", ...
33.545455
0.01847
def build(self, builder): """Build XML by appending to builder :Example: <FormData FormOID="MH" TransactionType="Update"> """ params = dict(FormOID=self.formoid) if self.transaction_type is not None: params["TransactionType"] = self.transaction_type ...
[ "def", "build", "(", "self", ",", "builder", ")", ":", "params", "=", "dict", "(", "FormOID", "=", "self", ".", "formoid", ")", "if", "self", ".", "transaction_type", "is", "not", "None", ":", "params", "[", "\"TransactionType\"", "]", "=", "self", "."...
26.516129
0.002347
def do_truncate(env, s, length=255, killwords=False, end='...', leeway=None): """Return a truncated copy of the string. The length is specified with the first parameter which defaults to ``255``. If the second parameter is ``true`` the filter will cut the text at length. Otherwise it will discard the la...
[ "def", "do_truncate", "(", "env", ",", "s", ",", "length", "=", "255", ",", "killwords", "=", "False", ",", "end", "=", "'...'", ",", "leeway", "=", "None", ")", ":", "if", "leeway", "is", "None", ":", "leeway", "=", "env", ".", "policies", "[", ...
43.205882
0.001332
def check_version(i): """ Input: { version - your version (string) } Output: { return - return code = 0 ok - if 'yes', your CK kernel version is outdated current_version - your CK kernel version } ...
[ "def", "check_version", "(", "i", ")", ":", "ok", "=", "'yes'", "r", "=", "get_version", "(", "{", "}", ")", "if", "r", "[", "'return'", "]", ">", "0", ":", "return", "r", "version", "=", "r", "[", "'version'", "]", "version_str", "=", "r", "[", ...
20.693878
0.024482
def get_repository(self, entity_cls): """Return a repository object configured with a live connection""" model_cls = self.get_model(entity_cls) return DictRepository(self, entity_cls, model_cls)
[ "def", "get_repository", "(", "self", ",", "entity_cls", ")", ":", "model_cls", "=", "self", ".", "get_model", "(", "entity_cls", ")", "return", "DictRepository", "(", "self", ",", "entity_cls", ",", "model_cls", ")" ]
53.75
0.009174
def setupQuery(self, query, op, editor): """ Returns the value from the editor. :param op | <str> editor | <QWidget> || None :return <bool> | success """ try: registry = self._operatorMap[natives...
[ "def", "setupQuery", "(", "self", ",", "query", ",", "op", ",", "editor", ")", ":", "try", ":", "registry", "=", "self", ".", "_operatorMap", "[", "nativestring", "(", "op", ")", "]", "except", "KeyError", ":", "return", "False", "op", "=", "registry",...
26.038462
0.011396
def console_output(self, instance=None): """Yields the output and metadata from all jobs in the pipeline Args: instance: The result of a :meth:`instance` call, if not supplied the latest of the pipeline will be used. Yields: tuple: (metadata (dict), output (str)...
[ "def", "console_output", "(", "self", ",", "instance", "=", "None", ")", ":", "if", "instance", "is", "None", ":", "instance", "=", "self", ".", "instance", "(", ")", "for", "stage", "in", "instance", "[", "'stages'", "]", ":", "for", "job", "in", "s...
31.377778
0.001374
def check_for_partition(self, schema, table, partition): """ Checks whether a partition exists :param schema: Name of hive schema (database) @table belongs to :type schema: str :param table: Name of hive table @partition belongs to :type schema: str :partition: E...
[ "def", "check_for_partition", "(", "self", ",", "schema", ",", "table", ",", "partition", ")", ":", "with", "self", ".", "metastore", "as", "client", ":", "partitions", "=", "client", ".", "get_partitions_by_filter", "(", "schema", ",", "table", ",", "partit...
32.230769
0.002317
def parse_request_uri_response(self, uri, state=None, scope=None): """Parse the response URI fragment. If the resource owner grants the access request, the authorization server issues an access token and delivers it to the client by adding the following parameters to the fragment compon...
[ "def", "parse_request_uri_response", "(", "self", ",", "uri", ",", "state", "=", "None", ",", "scope", "=", "None", ")", ":", "self", ".", "token", "=", "parse_implicit_response", "(", "uri", ",", "state", "=", "state", ",", "scope", "=", "scope", ")", ...
48.434211
0.002396
def setRegisterNumbersForTemporaries(ast, start): """Assign register numbers for temporary registers, keeping track of aliases and handling immediate operands. """ seen = 0 signature = '' aliases = [] for node in ast.postorderWalk(): if node.astType == 'alias': aliases.ap...
[ "def", "setRegisterNumbersForTemporaries", "(", "ast", ",", "start", ")", ":", "seen", "=", "0", "signature", "=", "''", "aliases", "=", "[", "]", "for", "node", "in", "ast", ".", "postorderWalk", "(", ")", ":", "if", "node", ".", "astType", "==", "'al...
30.454545
0.001447
def undelete_model_genes(cobra_model): """Undoes the effects of a call to delete_model_genes in place. cobra_model: A cobra.Model which will be modified in place """ if cobra_model._trimmed_genes is not None: for x in cobra_model._trimmed_genes: x.functional = True if cobra_...
[ "def", "undelete_model_genes", "(", "cobra_model", ")", ":", "if", "cobra_model", ".", "_trimmed_genes", "is", "not", "None", ":", "for", "x", "in", "cobra_model", ".", "_trimmed_genes", ":", "x", ".", "functional", "=", "True", "if", "cobra_model", ".", "_t...
33.2
0.001464
def init_report(self, reporter=None): """Initialize the report instance.""" self.options.report = (reporter or self.options.reporter)(self.options) return self.options.report
[ "def", "init_report", "(", "self", ",", "reporter", "=", "None", ")", ":", "self", ".", "options", ".", "report", "=", "(", "reporter", "or", "self", ".", "options", ".", "reporter", ")", "(", "self", ".", "options", ")", "return", "self", ".", "opti...
48.75
0.010101
def has_errors(self, form): """ Find tab fields listed as invalid """ return any([fieldname_error for fieldname_error in form.errors.keys() if fieldname_error in self])
[ "def", "has_errors", "(", "self", ",", "form", ")", ":", "return", "any", "(", "[", "fieldname_error", "for", "fieldname_error", "in", "form", ".", "errors", ".", "keys", "(", ")", "if", "fieldname_error", "in", "self", "]", ")" ]
35.833333
0.009091
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extract faulting style and rock adjustment coefficients for the ...
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "# extract faulting style and rock adjustment coefficients for the", "# given imt", "C_ADJ", "=", "self", ".", "COEFFS_FS_ROCK", "[", "imt",...
43.73913
0.001946
def total_ordering(cls): """Class decorator that fills in missing ordering methods""" convert = { # :off '__lt__': [('__gt__', _gt_from_lt), ('__le__', _le_from_lt), ('__ge__', _ge_from_lt)], '__le__': [('__ge__', _ge_from_le), ('__lt__',...
[ "def", "total_ordering", "(", "cls", ")", ":", "convert", "=", "{", "# :off", "'__lt__'", ":", "[", "(", "'__gt__'", ",", "_gt_from_lt", ")", ",", "(", "'__le__'", ",", "_le_from_lt", ")", ",", "(", "'__ge__'", ",", "_ge_from_lt", ")", "]", ",", "'__le...
39.133333
0.001663
def parse_date(dt, ignoretz=True, as_tz=None): """ :param dt: string datetime to convert into datetime object. :return: date object if the string can be parsed into a date. Otherwise, return None. :see: http://labix.org/python-dateutil Examples: >>> parse_date('2011-12-30') dateti...
[ "def", "parse_date", "(", "dt", ",", "ignoretz", "=", "True", ",", "as_tz", "=", "None", ")", ":", "dttm", "=", "parse_datetime", "(", "dt", ",", "ignoretz", "=", "ignoretz", ")", "return", "None", "if", "dttm", "is", "None", "else", "dttm", ".", "da...
29.176471
0.001953
def parser_for(self, name): """Decorator that registers a new parser method with the name ``name``. The decorated function must receive the input value for an environment variable. """ def decorator(func): self.add_parser(name, func) return func return d...
[ "def", "parser_for", "(", "self", ",", "name", ")", ":", "def", "decorator", "(", "func", ")", ":", "self", ".", "add_parser", "(", "name", ",", "func", ")", "return", "func", "return", "decorator" ]
31.9
0.009146
def load(path=None, **kwargs): ''' Loads the configuration from the file provided onto the device. path (required) Path where the configuration/template file is present. If the file has a ``.conf`` extension, the content is treated as text format. If the file has a ``.xml`` extensio...
[ "def", "load", "(", "path", "=", "None", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "__proxy__", "[", "'junos.conn'", "]", "(", ")", "ret", "=", "{", "}", "ret", "[", "'out'", "]", "=", "True", "if", "path", "is", "None", ":", "ret", "[", ...
32.048
0.001211
def find_top_level_directory(start_directory): """Finds the top-level directory of a project given a start directory inside the project. Parameters ---------- start_directory : str The directory in which test discovery will start. """ top_level = start_directory while os.path.i...
[ "def", "find_top_level_directory", "(", "start_directory", ")", ":", "top_level", "=", "start_directory", "while", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "top_level", ",", "'__init__.py'", ")", ")", ":", "top_level", "=",...
34.4375
0.001767
def StringIO(*args, **kw): """Thunk to load the real StringIO on demand""" global StringIO try: from cStringIO import StringIO except ImportError: from StringIO import StringIO return StringIO(*args,**kw)
[ "def", "StringIO", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "global", "StringIO", "try", ":", "from", "cStringIO", "import", "StringIO", "except", "ImportError", ":", "from", "StringIO", "import", "StringIO", "return", "StringIO", "(", "*", "args",...
29.125
0.008333
def characters (self, data): """ Print characters. @param data: the character data @type data: string @return: None """ data = data.encode(self.encoding, "ignore") self.fd.write(data)
[ "def", "characters", "(", "self", ",", "data", ")", ":", "data", "=", "data", ".", "encode", "(", "self", ".", "encoding", ",", "\"ignore\"", ")", "self", ".", "fd", ".", "write", "(", "data", ")" ]
23.9
0.012097
def P2(self, value): """Set private ``_P2`` and reset ``_block_matcher``.""" if value > self.P1: self._P2 = value else: raise InvalidSecondDisparityChangePenaltyError("P2 must be greater " "than P1.") self....
[ "def", "P2", "(", "self", ",", "value", ")", ":", "if", "value", ">", "self", ".", "P1", ":", "self", ".", "_P2", "=", "value", "else", ":", "raise", "InvalidSecondDisparityChangePenaltyError", "(", "\"P2 must be greater \"", "\"than P1.\"", ")", "self", "."...
40.75
0.012012
async def base_combine(source, switch=False, ordered=False, task_limit=None): """Base operator for managing an asynchronous sequence of sequences. The sequences are awaited concurrently, although it's possible to limit the amount of running sequences using the `task_limit` argument. The ``switch`` arg...
[ "async", "def", "base_combine", "(", "source", ",", "switch", "=", "False", ",", "ordered", "=", "False", ",", "task_limit", "=", "None", ")", ":", "# Task limit", "if", "task_limit", "is", "not", "None", "and", "not", "task_limit", ">", "0", ":", "raise...
35.560976
0.001001
def remap( x, oMin, oMax, nMin, nMax ): """Map to a 0 to 1 scale http://stackoverflow.com/questions/929103/convert-a-number-range-to-another-range-maintaining-ratio """ #range check if oMin == oMax: log.warning("Zero input range, unable to rescale") return x if nMin == nMa...
[ "def", "remap", "(", "x", ",", "oMin", ",", "oMax", ",", "nMin", ",", "nMax", ")", ":", "#range check", "if", "oMin", "==", "oMax", ":", "log", ".", "warning", "(", "\"Zero input range, unable to rescale\"", ")", "return", "x", "if", "nMin", "==", "nMax"...
25.315789
0.015015