text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def indx_table(node_dict, tbl_mode=False): """Print Table for dict=formatted list conditionally include numbers.""" nt = PrettyTable() nt.header = False nt.padding_width = 2 nt.border = False clr_num = C_TI + "NUM" clr_name = C_TI + "NAME" clr_state = "STATE" + C_NORM t_lu = {True: [...
[ "def", "indx_table", "(", "node_dict", ",", "tbl_mode", "=", "False", ")", ":", "nt", "=", "PrettyTable", "(", ")", "nt", ".", "header", "=", "False", "nt", ".", "padding_width", "=", "2", "nt", ".", "border", "=", "False", "clr_num", "=", "C_TI", "+...
35.612903
0.000882
def _is_national_number_suffix_of_other(numobj1, numobj2): """Returns true when one national number is the suffix of the other or both are the same. """ nn1 = str(numobj1.national_number) nn2 = str(numobj2.national_number) # Note that endswith returns True if the numbers are equal. return nn...
[ "def", "_is_national_number_suffix_of_other", "(", "numobj1", ",", "numobj2", ")", ":", "nn1", "=", "str", "(", "numobj1", ".", "national_number", ")", "nn2", "=", "str", "(", "numobj2", ".", "national_number", ")", "# Note that endswith returns True if the numbers ar...
43.625
0.002809
def echo_html_fenye_str(rec_num, fenye_num): ''' 生成分页的导航 ''' pagination_num = int(math.ceil(rec_num * 1.0 / 10)) if pagination_num == 1 or pagination_num == 0: fenye_str = '' elif pagination_num > 1: pager_mid, pager_pre, pager_next, pager_last, pager_home = '', '', '', '', ''...
[ "def", "echo_html_fenye_str", "(", "rec_num", ",", "fenye_num", ")", ":", "pagination_num", "=", "int", "(", "math", ".", "ceil", "(", "rec_num", "*", "1.0", "/", "10", ")", ")", "if", "pagination_num", "==", "1", "or", "pagination_num", "==", "0", ":", ...
32.907407
0.004918
def import_ecdsakey_from_public_pem(pem, scheme='ecdsa-sha2-nistp256'): """ <Purpose> Generate an ECDSA key object from 'pem'. In addition, a keyid identifier for the ECDSA key is generated. The object returned conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA' and has the form: {'keytype': '...
[ "def", "import_ecdsakey_from_public_pem", "(", "pem", ",", "scheme", "=", "'ecdsa-sha2-nistp256'", ")", ":", "# Does 'pem' have the correct format?", "# This check will ensure arguments has the appropriate number", "# of objects and object types, and that all dict keys are properly named.", ...
37.033333
0.009936
async def send_activities(self, context: TurnContext, activities: List[Activity]): """ Logs a series of activities to the console. :param context: :param activities: :return: """ if context is None: raise TypeError('ConsoleAdapter.send_activities(): `c...
[ "async", "def", "send_activities", "(", "self", ",", "context", ":", "TurnContext", ",", "activities", ":", "List", "[", "Activity", "]", ")", ":", "if", "context", "is", "None", ":", "raise", "TypeError", "(", "'ConsoleAdapter.send_activities(): `context` argumen...
40.526316
0.004439
def next(self): """Return the next page. The page label is defined in ``settings.NEXT_LABEL``. Return an empty string if current page is the last. """ if self._page.has_next(): return self._endless_page( self._page.next_page_number(), ...
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "_page", ".", "has_next", "(", ")", ":", "return", "self", ".", "_endless_page", "(", "self", ".", "_page", ".", "next_page_number", "(", ")", ",", "label", "=", "settings", ".", "NEXT_LABEL", ...
32.181818
0.005495
def unpack_xml(text) -> ET.ElementTree: """Unpack an XML string from AniDB API.""" etree: ET.ElementTree = ET.parse(io.StringIO(text)) _check_for_errors(etree) return etree
[ "def", "unpack_xml", "(", "text", ")", "->", "ET", ".", "ElementTree", ":", "etree", ":", "ET", ".", "ElementTree", "=", "ET", ".", "parse", "(", "io", ".", "StringIO", "(", "text", ")", ")", "_check_for_errors", "(", "etree", ")", "return", "etree" ]
36.8
0.005319
def RemoveMultiLineComments(filename, lines, error): """Removes multiline (c-style) comments from lines.""" lineix = 0 while lineix < len(lines): lineix_begin = FindNextMultiLineCommentStart(lines, lineix) if lineix_begin >= len(lines): return lineix_end = FindNextMultiLineCommentEnd(lines, line...
[ "def", "RemoveMultiLineComments", "(", "filename", ",", "lines", ",", "error", ")", ":", "lineix", "=", "0", "while", "lineix", "<", "len", "(", "lines", ")", ":", "lineix_begin", "=", "FindNextMultiLineCommentStart", "(", "lines", ",", "lineix", ")", "if", ...
42.571429
0.011494
def get_module_name(self, path_args): """returns the module_name and remaining path args. return -- tuple -- (module_name, path_args)""" controller_prefix = self.controller_prefix cset = self.module_names module_name = controller_prefix mod_name = module_name whi...
[ "def", "get_module_name", "(", "self", ",", "path_args", ")", ":", "controller_prefix", "=", "self", ".", "controller_prefix", "cset", "=", "self", ".", "module_names", "module_name", "=", "controller_prefix", "mod_name", "=", "module_name", "while", "path_args", ...
32
0.003571
def _add_parser_arguments_analyze(self, subparsers): """Create a parser for the 'analyze' subcommand. """ lyze_pars = subparsers.add_parser( "analyze", help="Perform basic analysis on this catalog.") lyze_pars.add_argument( '--count', '-c', dest='coun...
[ "def", "_add_parser_arguments_analyze", "(", "self", ",", "subparsers", ")", ":", "lyze_pars", "=", "subparsers", ".", "add_parser", "(", "\"analyze\"", ",", "help", "=", "\"Perform basic analysis on this catalog.\"", ")", "lyze_pars", ".", "add_argument", "(", "'--co...
34.307692
0.004367
def wr_dat_files(self, expanded=False, write_dir=''): """ Write each of the specified dat files """ # Get the set of dat files to be written, and # the channels to be written to each file. file_names, dat_channels = describe_list_indices(self.file_name) # Get th...
[ "def", "wr_dat_files", "(", "self", ",", "expanded", "=", "False", ",", "write_dir", "=", "''", ")", ":", "# Get the set of dat files to be written, and", "# the channels to be written to each file.", "file_names", ",", "dat_channels", "=", "describe_list_indices", "(", "...
39.029412
0.002941
def set_staff_url(parser, token): """ Assign an URL to be the "admin link" of this page. Example:: {% set_staff_url %}{% url 'admin:fluent_pages_page_change' page.id %}{% end_set_staff_url %} """ nodelist = parser.parse(('end_set_staff_url',)) parser.delete_first_token() return Admi...
[ "def", "set_staff_url", "(", "parser", ",", "token", ")", ":", "nodelist", "=", "parser", ".", "parse", "(", "(", "'end_set_staff_url'", ",", ")", ")", "parser", ".", "delete_first_token", "(", ")", "return", "AdminUrlNode", "(", "nodelist", ")" ]
32.9
0.005917
def trace_api(self): """ Helper for trace-related API calls. See https://cloud.google.com/trace/docs/reference/v2/rpc/google.devtools. cloudtrace.v2 """ if self._trace_api is None: self._trace_api = make_trace_api(self) return self._trace_api
[ "def", "trace_api", "(", "self", ")", ":", "if", "self", ".", "_trace_api", "is", "None", ":", "self", ".", "_trace_api", "=", "make_trace_api", "(", "self", ")", "return", "self", ".", "_trace_api" ]
28.090909
0.00627
def FilterItems(self, filterFn, key=None): """Filter items within a Reservoir, using a filtering function. Args: filterFn: A function that returns True for the items to be kept. key: An optional bucket key to filter. If not specified, will filter all all buckets. Returns: The num...
[ "def", "FilterItems", "(", "self", ",", "filterFn", ",", "key", "=", "None", ")", ":", "with", "self", ".", "_mutex", ":", "if", "key", ":", "if", "key", "in", "self", ".", "_buckets", ":", "return", "self", ".", "_buckets", "[", "key", "]", ".", ...
30.35
0.007987
def _validate_namespaces(namespaces): """Validate wildcards and renaming in namespaces. Target namespaces should have the same number of wildcards as the source. No target namespaces overlap exactly with each other. Logs a warning when wildcard namespaces have a chance of overlapping. """ for s...
[ "def", "_validate_namespaces", "(", "namespaces", ")", ":", "for", "source", ",", "namespace", "in", "namespaces", ".", "items", "(", ")", ":", "target", "=", "namespace", ".", "dest_name", "_validate_namespace", "(", "source", ")", "_validate_namespace", "(", ...
45.983333
0.001065
def check_job_status(self, key=JobDetails.topkey, fail_running=False, fail_pending=False, force_check=False): """Check the status of a particular job By default this checks the status of the top-level job, but can by mad...
[ "def", "check_job_status", "(", "self", ",", "key", "=", "JobDetails", ".", "topkey", ",", "fail_running", "=", "False", ",", "fail_pending", "=", "False", ",", "force_check", "=", "False", ")", ":", "if", "key", "in", "self", ".", "jobs", ":", "status",...
33.355556
0.003883
def hil_rc_inputs_raw_send(self, time_usec, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, rssi, force_mavlink1=False): ''' Sent from simulation to autopilot. The RAW values of the RC channels ...
[ "def", "hil_rc_inputs_raw_send", "(", "self", ",", "time_usec", ",", "chan1_raw", ",", "chan2_raw", ",", "chan3_raw", ",", "chan4_raw", ",", "chan5_raw", ",", "chan6_raw", ",", "chan7_raw", ",", "chan8_raw", ",", "chan9_raw", ",", "chan10_raw", ",", "chan11_raw"...
84.88
0.008854
def rangeChange(self, pw, ranges): """Adjusts the stimulus signal to keep it at the top of a plot, after any ajustment to the axes ranges takes place. This is a slot for the undocumented pyqtgraph signal sigRangeChanged. From what I can tell the arguments are: :param pw: refere...
[ "def", "rangeChange", "(", "self", ",", "pw", ",", "ranges", ")", ":", "if", "hasattr", "(", "ranges", ",", "'__iter__'", ")", ":", "# adjust the stim signal so that it falls in the correct range", "yrange_size", "=", "ranges", "[", "1", "]", "[", "1", "]", "-...
47
0.00269
def _fix_valid_indices(cls, valid_indices, insertion_index, dim): """Add indices for H&S inserted elements.""" # TODO: make this accept an immutable sequence for valid_indices # (a tuple) and return an immutable sequence rather than mutating an # argument. indices = np.array(sort...
[ "def", "_fix_valid_indices", "(", "cls", ",", "valid_indices", ",", "insertion_index", ",", "dim", ")", ":", "# TODO: make this accept an immutable sequence for valid_indices", "# (a tuple) and return an immutable sequence rather than mutating an", "# argument.", "indices", "=", "n...
51.909091
0.003442
def fromPandas(cls, df): """ Create a :class:`~amplpy.DataFrame` from a pandas DataFrame. """ assert pd is not None if isinstance(df, pd.Series): df = pd.DataFrame(df) else: assert isinstance(df, pd.DataFrame) keys = [ key if is...
[ "def", "fromPandas", "(", "cls", ",", "df", ")", ":", "assert", "pd", "is", "not", "None", "if", "isinstance", "(", "df", ",", "pd", ".", "Series", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", "df", ")", "else", ":", "assert", "isinstance", ...
30.545455
0.002886
def from_times(cls, times, delta_t=DEFAULT_OBSERVATION_TIME): """ Create a TimeMOC from a `astropy.time.Time` Parameters ---------- times : `astropy.time.Time` astropy observation times delta_t : `astropy.time.TimeDelta`, optional the duration of ...
[ "def", "from_times", "(", "cls", ",", "times", ",", "delta_t", "=", "DEFAULT_OBSERVATION_TIME", ")", ":", "times_arr", "=", "np", ".", "asarray", "(", "times", ".", "jd", "*", "TimeMOC", ".", "DAY_MICRO_SEC", ",", "dtype", "=", "int", ")", "intervals_arr",...
43.565217
0.003906
def swipe(self, x1: int, y1: int, x2: int, y2: int, duration: int = 100) -> None: '''Simulate finger swipe. (1000ms = 1s)''' self._execute('-s', self.device_sn, 'shell', 'input', 'swipe', str(x1), str(y1), str(x2), str(y2), str(duration))
[ "def", "swipe", "(", "self", ",", "x1", ":", "int", ",", "y1", ":", "int", ",", "x2", ":", "int", ",", "y2", ":", "int", ",", "duration", ":", "int", "=", "100", ")", "->", "None", ":", "self", ".", "_execute", "(", "'-s'", ",", "self", ".", ...
68.25
0.014493
def call(cls, method, *args, **kwargs): """ Call a remote api method and return the result.""" api = None empty_key = kwargs.pop('empty_key', False) try: api = cls.get_api_connector() apikey = cls.get('api.key') if not apikey and not empty_key: ...
[ "def", "call", "(", "cls", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "api", "=", "None", "empty_key", "=", "kwargs", ".", "pop", "(", "'empty_key'", ",", "False", ")", "try", ":", "api", "=", "cls", ".", "get_api_connector...
40.375
0.000864
def unescape(s): """ Unescapes a string that may contain commas, tabs, newlines and dashes Commas are decoded from tabs. :param s: (string) to unescape :returns: (string) unescaped string """ assert isinstance(s, basestring) s = s.replace('\t', ',') s = s.replace('\\,', ',') s = s.replace('\\n', '...
[ "def", "unescape", "(", "s", ")", ":", "assert", "isinstance", "(", "s", ",", "basestring", ")", "s", "=", "s", ".", "replace", "(", "'\\t'", ",", "','", ")", "s", "=", "s", ".", "replace", "(", "'\\\\,'", ",", "','", ")", "s", "=", "s", ".", ...
21.9375
0.021858
def run(self): """Run the whole impact function. :return: A tuple with the status of the IF and an error message if needed. The status is ANALYSIS_SUCCESS if everything was fine. The status is ANALYSIS_FAILED_BAD_INPUT if the client should fix somethi...
[ "def", "run", "(", "self", ")", ":", "self", ".", "_start_datetime", "=", "datetime", ".", "now", "(", ")", "if", "not", "self", ".", "_is_ready", ":", "message", "=", "generate_input_error_message", "(", "tr", "(", "'You need to run `prepare` first.'", ")", ...
43.155844
0.000294
def read_playlists(self): self.playlists = [] self.selected_playlist = -1 files = glob.glob(path.join(self.stations_dir, '*.csv')) if len(files) == 0: return 0, -1 else: for a_file in files: a_file_name = ''.join(path.basename(a_file).split...
[ "def", "read_playlists", "(", "self", ")", ":", "self", ".", "playlists", "=", "[", "]", "self", ".", "selected_playlist", "=", "-", "1", "files", "=", "glob", ".", "glob", "(", "path", ".", "join", "(", "self", ".", "stations_dir", ",", "'*.csv'", "...
44.315789
0.003488
def _volume_command(ramp, volume): """ Set the value if a volume level is provided, else print the current volume level. """ if volume is not None: ramp.set_volume(float(volume)) else: print ramp.volume
[ "def", "_volume_command", "(", "ramp", ",", "volume", ")", ":", "if", "volume", "is", "not", "None", ":", "ramp", ".", "set_volume", "(", "float", "(", "volume", ")", ")", "else", ":", "print", "ramp", ".", "volume" ]
32.571429
0.004274
def log_variable_sizes(var_list, tag, verbose=True, mesh_to_impl=None): """Log the sizes and shapes of variables, and the total size. Args: var_list: a list of variables; defaults to trainable_variables tag: a string; defaults to "Trainable Variables" verbose: bool, if True, log every weight; otherwise...
[ "def", "log_variable_sizes", "(", "var_list", ",", "tag", ",", "verbose", "=", "True", ",", "mesh_to_impl", "=", "None", ")", ":", "if", "not", "var_list", ":", "return", "name_to_var", "=", "{", "v", ".", "name", ":", "v", "for", "v", "in", "var_list"...
35
0.00951
def _update_pending_document_state(cursor, document_id, is_license_accepted, are_roles_accepted): """Update the state of the document's state values.""" args = (bool(is_license_accepted), bool(are_roles_accepted), document_id,) cursor.execute("""\ UPDATE pendin...
[ "def", "_update_pending_document_state", "(", "cursor", ",", "document_id", ",", "is_license_accepted", ",", "are_roles_accepted", ")", ":", "args", "=", "(", "bool", "(", "is_license_accepted", ")", ",", "bool", "(", "are_roles_accepted", ")", ",", "document_id", ...
41.5
0.002358
def population_variant_regions(items, merged=False): """Retrieve the variant region BED file from a population of items. If tumor/normal, return the tumor BED file. If a population, return the BED file covering the most bases. """ def _get_variant_regions(data): out = dd.get_variant_regions...
[ "def", "population_variant_regions", "(", "items", ",", "merged", "=", "False", ")", ":", "def", "_get_variant_regions", "(", "data", ")", ":", "out", "=", "dd", ".", "get_variant_regions", "(", "data", ")", "or", "dd", ".", "get_sample_callable", "(", "data...
38.40625
0.002381
def populate(self, priority, address, rtr, data): """ :return: None """ assert isinstance(data, bytes) self.needs_high_priority(priority) self.needs_no_rtr(rtr) self.needs_data(data, 3) self.set_attributes(priority, address, rtr) self.closed = self...
[ "def", "populate", "(", "self", ",", "priority", ",", "address", ",", "rtr", ",", "data", ")", ":", "assert", "isinstance", "(", "data", ",", "bytes", ")", "self", ".", "needs_high_priority", "(", "priority", ")", "self", ".", "needs_no_rtr", "(", "rtr",...
37.166667
0.004376
def length(self): """The number of elements changed. :rtype: int .. code:: python assert change.length == len(change.indices) assert change.length == len(change.elements) """ span = self._stop - self._start length, modulo = divmod(span, self._st...
[ "def", "length", "(", "self", ")", ":", "span", "=", "self", ".", "_stop", "-", "self", ".", "_start", "length", ",", "modulo", "=", "divmod", "(", "span", ",", "self", ".", "_step", ")", "if", "length", "<", "0", ":", "return", "0", "if", "modul...
25.117647
0.004515
def tracebacks_from_file(fileobj, reverse=False): """Generator that yields tracebacks found in a file object With reverse=True, searches backwards from the end of the file. """ if reverse: lines = deque() for line in BackwardsReader(fileobj): lines.appendleft(line) ...
[ "def", "tracebacks_from_file", "(", "fileobj", ",", "reverse", "=", "False", ")", ":", "if", "reverse", ":", "lines", "=", "deque", "(", ")", "for", "line", "in", "BackwardsReader", "(", "fileobj", ")", ":", "lines", ".", "appendleft", "(", "line", ")", ...
30
0.001901
def _if(ctx, logical_test, value_if_true=0, value_if_false=False): """ Returns one value if the condition evaluates to TRUE, and another value if it evaluates to FALSE """ return value_if_true if conversions.to_boolean(logical_test, ctx) else value_if_false
[ "def", "_if", "(", "ctx", ",", "logical_test", ",", "value_if_true", "=", "0", ",", "value_if_false", "=", "False", ")", ":", "return", "value_if_true", "if", "conversions", ".", "to_boolean", "(", "logical_test", ",", "ctx", ")", "else", "value_if_false" ]
53.8
0.010989
def to_drake_step(inputs, output): """ Args: inputs: collection of input Steps output: output Step Returns: a string of the drake step for the given inputs and output """ i = [output._yaml_filename] i.extend(map(lambda i: i._target_filename, list(inputs))) i.extend(output.de...
[ "def", "to_drake_step", "(", "inputs", ",", "output", ")", ":", "i", "=", "[", "output", ".", "_yaml_filename", "]", "i", ".", "extend", "(", "map", "(", "lambda", "i", ":", "i", ".", "_target_filename", ",", "list", "(", "inputs", ")", ")", ")", "...
37.269231
0.003018
def left_outer(self): """ Performs Left Outer Join :return left_outer: dict """ self.get_collections_data() left_outer_join = self.merge_join_docs( set(self.collections_data['left'].keys())) return left_outer_join
[ "def", "left_outer", "(", "self", ")", ":", "self", ".", "get_collections_data", "(", ")", "left_outer_join", "=", "self", ".", "merge_join_docs", "(", "set", "(", "self", ".", "collections_data", "[", "'left'", "]", ".", "keys", "(", ")", ")", ")", "ret...
31.222222
0.00692
def is_typing_handler(stream): """ Show message to opponent if user is typing message """ while True: packet = yield from stream.get() session_id = packet.get('session_key') user_opponent = packet.get('username') typing = packet.get('typing') if session_i...
[ "def", "is_typing_handler", "(", "stream", ")", ":", "while", "True", ":", "packet", "=", "yield", "from", "stream", ".", "get", "(", ")", "session_id", "=", "packet", ".", "get", "(", "'session_key'", ")", "user_opponent", "=", "packet", ".", "get", "("...
41.75
0.003513
def __collapse_stranded(s, proc_strands, names=False, verbose=False): """ Get the union of a set of genomic intervals. given a list of genomic intervals with chromosome, start, end and strand fields, collapse those intervals with strand in the set <proc_strands> into a set of non-overlapping intervals. Other...
[ "def", "__collapse_stranded", "(", "s", ",", "proc_strands", ",", "names", "=", "False", ",", "verbose", "=", "False", ")", ":", "def", "get_first_matching_index", "(", "s", ",", "proc_strands", ")", ":", "for", "i", "in", "range", "(", "0", ",", "len", ...
40.868421
0.008488
def visit_index(self, node, parent): """visit a Index node by returning a fresh instance of it""" newnode = nodes.Index(parent=parent) newnode.postinit(self.visit(node.value, newnode)) return newnode
[ "def", "visit_index", "(", "self", ",", "node", ",", "parent", ")", ":", "newnode", "=", "nodes", ".", "Index", "(", "parent", "=", "parent", ")", "newnode", ".", "postinit", "(", "self", ".", "visit", "(", "node", ".", "value", ",", "newnode", ")", ...
45.4
0.008658
def power_off(self): """Power the device off.""" status = self.status() if status['power']: # Setting power off when it is already off can cause hangs self._send(self.CMD_POWERSAVE + self.CMD_OFF)
[ "def", "power_off", "(", "self", ")", ":", "status", "=", "self", ".", "status", "(", ")", "if", "status", "[", "'power'", "]", ":", "# Setting power off when it is already off can cause hangs", "self", ".", "_send", "(", "self", ".", "CMD_POWERSAVE", "+", "se...
45.8
0.012876
def get_assign_groups(line, ops=ops): """ Split a line into groups by assignment (including augmented assignment) """ group = [] for item in line: group.append(item) if item in ops: yield group group = [] yield group
[ "def", "get_assign_groups", "(", "line", ",", "ops", "=", "ops", ")", ":", "group", "=", "[", "]", "for", "item", "in", "line", ":", "group", ".", "append", "(", "item", ")", "if", "item", "in", "ops", ":", "yield", "group", "group", "=", "[", "]...
24.909091
0.003521
def _connect(self): """ Use the appropriate connection class; optionally with security. """ timeout = None if self._options is not None and 'timeout' in self._options: timeout = self._options['timeout'] if self._client._credentials: self._connecti...
[ "def", "_connect", "(", "self", ")", ":", "timeout", "=", "None", "if", "self", ".", "_options", "is", "not", "None", "and", "'timeout'", "in", "self", ".", "_options", ":", "timeout", "=", "self", ".", "_options", "[", "'timeout'", "]", "if", "self", ...
37.272727
0.002378
def give_str_indented(self, tags=False): """ Give indented string representation of the callable. This is used in :ref:`automate-webui`. """ args = self._args[:] kwargs = self._kwargs rv = self._give_str_indented(args, kwargs, tags) if not tags: ...
[ "def", "give_str_indented", "(", "self", ",", "tags", "=", "False", ")", ":", "args", "=", "self", ".", "_args", "[", ":", "]", "kwargs", "=", "self", ".", "_kwargs", "rv", "=", "self", ".", "_give_str_indented", "(", "args", ",", "kwargs", ",", "tag...
33.454545
0.005291
def moran_cultural(network): """Generalized cultural Moran process. At eachtime step, an individual is chosen to receive information from another individual. Nobody dies, but perhaps their ideas do. """ if not network.transmissions(): # first step, replacer is a source replacer = random.ch...
[ "def", "moran_cultural", "(", "network", ")", ":", "if", "not", "network", ".", "transmissions", "(", ")", ":", "# first step, replacer is a source", "replacer", "=", "random", ".", "choice", "(", "network", ".", "nodes", "(", "type", "=", "Source", ")", ")"...
36.736842
0.001397
def init_app(self, app=None, blueprint=None, additional_blueprints=None): """Update flask application with our api :param Application app: a flask application """ if app is not None: self.app = app if blueprint is not None: self.blueprint = blueprint ...
[ "def", "init_app", "(", "self", ",", "app", "=", "None", ",", "blueprint", "=", "None", ",", "additional_blueprints", "=", "None", ")", ":", "if", "app", "is", "not", "None", ":", "self", ".", "app", "=", "app", "if", "blueprint", "is", "not", "None"...
33.36
0.002331
def _get_keycache(self, parentity, branch, turn, tick, *, forward): """Get a frozenset of keys that exist in the entity at the moment. With ``forward=True``, enable an optimization that copies old key sets forward and updates them. """ lru_append(self.keycache, self._kc_lru, (p...
[ "def", "_get_keycache", "(", "self", ",", "parentity", ",", "branch", ",", "turn", ",", "tick", ",", "*", ",", "forward", ")", ":", "lru_append", "(", "self", ".", "keycache", ",", "self", ".", "_kc_lru", ",", "(", "parentity", "+", "(", "branch", ",...
43.833333
0.005587
def getVC(self): """ Variance componenrs """ _Cr = decompose_GxE(self.full['Cr']) RV = {} for key in list(_Cr.keys()): RV['var_%s' % key] = sp.array([var_CoXX(_Cr[key], self.Xr)]) RV['var_c'] = self.full['var_c'] RV['var_n'] = self.full['var_n...
[ "def", "getVC", "(", "self", ")", ":", "_Cr", "=", "decompose_GxE", "(", "self", ".", "full", "[", "'Cr'", "]", ")", "RV", "=", "{", "}", "for", "key", "in", "list", "(", "_Cr", ".", "keys", "(", ")", ")", ":", "RV", "[", "'var_%s'", "%", "ke...
30.090909
0.01173
def load(self, content): """Parse yaml content.""" # Try parsing the YAML with global tags try: config = yaml.load(content, Loader=self._loader(self._global_tags)) except yaml.YAMLError: raise InvalidConfigError(_("Config is not valid yaml.")) # Try extra...
[ "def", "load", "(", "self", ",", "content", ")", ":", "# Try parsing the YAML with global tags", "try", ":", "config", "=", "yaml", ".", "load", "(", "content", ",", "Loader", "=", "self", ".", "_loader", "(", "self", ".", "_global_tags", ")", ")", "except...
35.804878
0.001989
def unsubscribe(self, client): """Unsubscribe a client from the channel.""" if client in self.clients: self.clients.remove(client) log("Unsubscribed client {} from channel {}".format(client, self.name))
[ "def", "unsubscribe", "(", "self", ",", "client", ")", ":", "if", "client", "in", "self", ".", "clients", ":", "self", ".", "clients", ".", "remove", "(", "client", ")", "log", "(", "\"Unsubscribed client {} from channel {}\"", ".", "format", "(", "client", ...
47.6
0.012397
def create_Container(client, id): """ Execute the most basic Create of collection. This will create a collection with 400 RUs throughput and default indexing policy """ print("\n2.1 Create Collection - Basic") try: client.CreateContainer(database_link, {"id": id}) ...
[ "def", "create_Container", "(", "client", ",", "id", ")", ":", "print", "(", "\"\\n2.1 Create Collection - Basic\"", ")", "try", ":", "client", ".", "CreateContainer", "(", "database_link", ",", "{", "\"id\"", ":", "id", "}", ")", "print", "(", "'Collection wi...
42.157303
0.011458
def make_gromacs(simulation, directory, clean=False): """Create gromacs directory structure""" if clean is False and os.path.exists(directory): raise ValueError( 'Cannot override {}, use option clean=True'.format(directory)) else: shutil.rmtree(directory, ignore_errors=True) ...
[ "def", "make_gromacs", "(", "simulation", ",", "directory", ",", "clean", "=", "False", ")", ":", "if", "clean", "is", "False", "and", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "raise", "ValueError", "(", "'Cannot override {}, use option ...
37.176471
0.007194
def from_xarray(cls, arr: "xarray.Dataset") -> "Histogram1D": """Convert form xarray.Dataset Parameters ---------- arr: The data in xarray representation """ kwargs = {'frequencies': arr["frequencies"], 'binning': arr["bins"], 'errors2...
[ "def", "from_xarray", "(", "cls", ",", "arr", ":", "\"xarray.Dataset\"", ")", "->", "\"Histogram1D\"", ":", "kwargs", "=", "{", "'frequencies'", ":", "arr", "[", "\"frequencies\"", "]", ",", "'binning'", ":", "arr", "[", "\"bins\"", "]", ",", "'errors2'", ...
36.4
0.003571
def normalized_mean_square_error(output, target, name="normalized_mean_squared_error_loss"): """Return the TensorFlow expression of normalized mean-square-error of two distributions. Parameters ---------- output : Tensor 2D, 3D or 4D tensor i.e. [batch_size, n_feature], [batch_size, height, wid...
[ "def", "normalized_mean_square_error", "(", "output", ",", "target", ",", "name", "=", "\"normalized_mean_squared_error_loss\"", ")", ":", "# with tf.name_scope(\"normalized_mean_squared_error_loss\"):", "if", "output", ".", "get_shape", "(", ")", ".", "ndims", "==", "2",...
52.6
0.005228
def _increment_flaky_attribute(cls, test_item, flaky_attribute): """ Increments the value of an attribute on a flaky test. :param test_item: The test callable on which to set the attribute :type test_item: `callable` or :class:`nose.case.Test` or :class:`Function...
[ "def", "_increment_flaky_attribute", "(", "cls", ",", "test_item", ",", "flaky_attribute", ")", ":", "cls", ".", "_set_flaky_attribute", "(", "test_item", ",", "flaky_attribute", ",", "cls", ".", "_get_flaky_attribute", "(", "test_item", ",", "flaky_attribute", ")",...
40.642857
0.005155
def set_names(self, names): """ Change names of all columns in the frame. :param List[str] names: The list of new names for every column in the frame. """ assert_is_type(names, [str]) assert_satisfies(names, len(names) == self.ncol) self._ex = ExprNode("colnames=...
[ "def", "set_names", "(", "self", ",", "names", ")", ":", "assert_is_type", "(", "names", ",", "[", "str", "]", ")", "assert_satisfies", "(", "names", ",", "len", "(", "names", ")", "==", "self", ".", "ncol", ")", "self", ".", "_ex", "=", "ExprNode", ...
39.9
0.009804
def get_cds_time(days, msecs): """Get the datetime object of the time since epoch given in days and milliseconds of day """ return datetime(1958, 1, 1) + timedelta(days=float(days), milliseconds=float(msecs))
[ "def", "get_cds_time", "(", "days", ",", "msecs", ")", ":", "return", "datetime", "(", "1958", ",", "1", ",", "1", ")", "+", "timedelta", "(", "days", "=", "float", "(", "days", ")", ",", "milliseconds", "=", "float", "(", "msecs", ")", ")" ]
43.833333
0.003731
def update_score_summary(sender, **kwargs): """ Listen for new Scores and update the relevant ScoreSummary. Args: sender: not used Kwargs: instance (Score): The score model whose save triggered this receiver. """ score = kwargs['instance'] ...
[ "def", "update_score_summary", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "score", "=", "kwargs", "[", "'instance'", "]", "try", ":", "score_summary", "=", "ScoreSummary", ".", "objects", ".", "get", "(", "student_item", "=", "score", ".", "student_...
36.710526
0.003492
def scene_remove(frames): """parse a scene.rm message""" # "scene.rm" <scene_id> reader = MessageReader(frames) results = reader.string("command").uint32("scene_id").assert_end().get() if results.command != "scene.rm": raise MessageParserError("Command is not 'scene.r...
[ "def", "scene_remove", "(", "frames", ")", ":", "# \"scene.rm\" <scene_id>", "reader", "=", "MessageReader", "(", "frames", ")", "results", "=", "reader", ".", "string", "(", "\"command\"", ")", ".", "uint32", "(", "\"scene_id\"", ")", ".", "assert_end", "(", ...
44
0.008357
def check_edge(self, name1, name2): ''' API: check_edge(self, name1, name2) Description: Return True if edge exists, False otherwise. Input: name1: name of the source node. name2: name of the sink node. Return: Returns True if edge exis...
[ "def", "check_edge", "(", "self", ",", "name1", ",", "name2", ")", ":", "if", "self", ".", "graph_type", "is", "DIRECTED_GRAPH", ":", "return", "(", "name1", ",", "name2", ")", "in", "self", ".", "edge_attr", "else", ":", "return", "(", "(", "name1", ...
34.9375
0.003484
def plot_txn_time_hist(transactions, bin_minutes=5, tz='America/New_York', ax=None, **kwargs): """ Plots a histogram of transaction times, binning the times into buckets of a given duration. Parameters ---------- transactions : pd.DataFrame Prices and amounts of e...
[ "def", "plot_txn_time_hist", "(", "transactions", ",", "bin_minutes", "=", "5", ",", "tz", "=", "'America/New_York'", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", ...
36.571429
0.000476
def _wrap(self, line: str) -> str: """ Returns an import wrapped to the specified line-length, if possible. """ wrap_mode = self.config['multi_line_output'] if len(line) > self.config['line_length'] and wrap_mode != WrapModes.NOQA: line_without_comment = line ...
[ "def", "_wrap", "(", "self", ",", "line", ":", "str", ")", "->", "str", ":", "wrap_mode", "=", "self", ".", "config", "[", "'multi_line_output'", "]", "if", "len", "(", "line", ")", ">", "self", ".", "config", "[", "'line_length'", "]", "and", "wrap_...
60.071429
0.00663
def discard(self, key): """Remove a item from its member if it is a member. Usage:: >>> s = OrderedSet([1, 2, 3]) >>> s.discard(2) >>> s OrderedSet([1, 3]) **中文文档** 从有序集合中删除一个元素, 同时保持集合依然有序。 """ ...
[ "def", "discard", "(", "self", ",", "key", ")", ":", "if", "key", "in", "self", ".", "map", ":", "key", ",", "prev", ",", "next_item", "=", "self", ".", "map", ".", "pop", "(", "key", ")", "prev", "[", "2", "]", "=", "next_item", "next_item", "...
25
0.012848
def connect(self, f, t): """Connect two existing vertices. Nothing happens if the vertices are already connected. """ if t not in self._vertices: raise KeyError(t) self._forwards[f].add(t) self._backwards[t].add(f)
[ "def", "connect", "(", "self", ",", "f", ",", "t", ")", ":", "if", "t", "not", "in", "self", ".", "_vertices", ":", "raise", "KeyError", "(", "t", ")", "self", ".", "_forwards", "[", "f", "]", ".", "add", "(", "t", ")", "self", ".", "_backwards...
29.666667
0.007273
def predict(self, test_data, custom_metric = None, custom_metric_func = None): """ Predict on a dataset. :param H2OFrame test_data: Data on which to make predictions. :param custom_metric: custom evaluation function defined as class reference, the class get uploaded into cluste...
[ "def", "predict", "(", "self", ",", "test_data", ",", "custom_metric", "=", "None", ",", "custom_metric_func", "=", "None", ")", ":", "# Upload evaluation function into DKV", "if", "custom_metric", ":", "assert_satisfies", "(", "custom_metric_func", ",", "custom_metri...
56.809524
0.011542
def formfield_for_manytomany(self, db_field, request, **kwargs): """ Filter the disposable authors. """ if db_field.name == 'authors': kwargs['queryset'] = Author.objects.filter( Q(is_staff=True) | Q(entries__isnull=False) ).distinct() ...
[ "def", "formfield_for_manytomany", "(", "self", ",", "db_field", ",", "request", ",", "*", "*", "kwargs", ")", ":", "if", "db_field", ".", "name", "==", "'authors'", ":", "kwargs", "[", "'queryset'", "]", "=", "Author", ".", "objects", ".", "filter", "("...
37.090909
0.004785
def patch(*module_names): """apply monkey-patches to stdlib modules in-place imports the relevant modules and simply overwrites attributes on the module objects themselves. those attributes may be functions, classes or other attributes. valid arguments are: - __builtin__ - Queue - fcn...
[ "def", "patch", "(", "*", "module_names", ")", ":", "if", "not", "module_names", ":", "module_names", "=", "_patchers", ".", "keys", "(", ")", "log", ".", "info", "(", "\"monkey-patching in-place (%d modules)\"", "%", "len", "(", "module_names", ")", ")", "f...
30.735849
0.000595
def istextfile(fname, blocksize=512): """ Uses heuristics to guess whether the given file is text or binary, by reading a single block of bytes from the file. If more than 30% of the chars in the block are non-text, or there are NUL ('\x00') bytes in the block, assume this is a binary file. ...
[ "def", "istextfile", "(", "fname", ",", "blocksize", "=", "512", ")", ":", "with", "open", "(", "fname", ",", "\"rb\"", ")", "as", "fobj", ":", "block", "=", "fobj", ".", "read", "(", "blocksize", ")", "if", "not", "block", ":", "# An empty file is con...
37.333333
0.001244
def command_help_long(self): """ Return command help for use in global parser usage string @TODO update to support self.current_indent from formatter """ indent = " " * 2 # replace with current_indent help = "Command must be one of:\n" for action_name in self.parser.valid_commands...
[ "def", "command_help_long", "(", "self", ")", ":", "indent", "=", "\" \"", "*", "2", "# replace with current_indent", "help", "=", "\"Command must be one of:\\n\"", "for", "action_name", "in", "self", ".", "parser", ".", "valid_commands", ":", "help", "+=", "\"%s%...
44.833333
0.010929
def lint_fileset(*dirnames, **kwargs): """Lints a group of files using a given rcfile. Keyword arguments are * ``rc_filename`` (``str``): The name of the Pylint config RC file. * ``description`` (``str``): A description of the files and configuration currently being ru...
[ "def", "lint_fileset", "(", "*", "dirnames", ",", "*", "*", "kwargs", ")", ":", "try", ":", "rc_filename", "=", "kwargs", "[", "'rc_filename'", "]", "description", "=", "kwargs", "[", "'description'", "]", "if", "len", "(", "kwargs", ")", "!=", "2", ":...
34.606061
0.000852
def getAsWkt(self, session): """ Retrieve the geometry in Well Known Text format. This method is a veneer for an SQL query that calls the ``ST_AsText()`` function on the geometry column. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound ...
[ "def", "getAsWkt", "(", "self", ",", "session", ")", ":", "statement", "=", "\"\"\"\n SELECT ST_AsText({0}) AS wkt\n FROM {1}\n WHERE id={2};\n \"\"\"", ".", "format", "(", "self", ".", "geometryColumnName", ...
33.416667
0.004848
def clone(self, choices): """ Make a copy of this parameter, supply different choices. @param choices: A sequence of L{Option} instances. @type choices: C{list} @rtype: L{ChoiceParameter} """ return self.__class__( self.name, choices, ...
[ "def", "clone", "(", "self", ",", "choices", ")", ":", "return", "self", ".", "__class__", "(", "self", ".", "name", ",", "choices", ",", "self", ".", "label", ",", "self", ".", "description", ",", "self", ".", "multiple", ",", "self", ".", "viewFact...
25.75
0.004684
def kernel_matrix_xX(svm_model, original_x, original_X): if (svm_model.svm_kernel == 'polynomial_kernel' or svm_model.svm_kernel == 'soft_polynomial_kernel'): K = (svm_model.zeta + svm_model.gamma * np.dot(original_x, original_X.T)) ** svm_model.Q elif (svm_model.svm_kernel == 'gaussian_ker...
[ "def", "kernel_matrix_xX", "(", "svm_model", ",", "original_x", ",", "original_X", ")", ":", "if", "(", "svm_model", ".", "svm_kernel", "==", "'polynomial_kernel'", "or", "svm_model", ".", "svm_kernel", "==", "'soft_polynomial_kernel'", ")", ":", "K", "=", "(", ...
57.526316
0.009001
def long_banner(self): """Banner for IPython widgets with pylab message""" # Default banner try: from IPython.core.usage import quick_guide except Exception: quick_guide = '' banner_parts = [ 'Python %s\n' % self.interpreter_versions['python_ve...
[ "def", "long_banner", "(", "self", ")", ":", "# Default banner", "try", ":", "from", "IPython", ".", "core", ".", "usage", "import", "quick_guide", "except", "Exception", ":", "quick_guide", "=", "''", "banner_parts", "=", "[", "'Python %s\\n'", "%", "self", ...
37.577778
0.003458
def add_scalebar(ax, matchx=True, matchy=True, hidex=True, hidey=True, unitsx='', unitsy='', scalex=1, scaley=1, **kwargs): """ Add scalebars to axes Adds a set of scale bars to *ax*, matching the size to the ticks of the plot and optionally hiding the x and y axes - ax : the axis to attach ticks to ...
[ "def", "add_scalebar", "(", "ax", ",", "matchx", "=", "True", ",", "matchy", "=", "True", ",", "hidex", "=", "True", ",", "hidey", "=", "True", ",", "unitsx", "=", "''", ",", "unitsy", "=", "''", ",", "scalex", "=", "1", ",", "scaley", "=", "1", ...
41.645161
0.013626
def get_option_type(self, key, subkey): """Get the type of a particular option. :param str key: First identifier of the option. :param str subkey: Second identifier of the option. :return: :class:`str` - description of the type. :raise: :NotRegisteredError: If ``ke...
[ "def", "get_option_type", "(", "self", ",", "key", ",", "subkey", ")", ":", "key", ",", "subkey", "=", "_lower_keys", "(", "key", ",", "subkey", ")", "_entry_must_exist", "(", "self", ".", "gc", ",", "key", ",", "subkey", ")", "return", "self", ".", ...
34.529412
0.003317
def convert(self, value, param, ctx): """ Convert value to int. """ self.gandi = ctx.obj value = click.Choice.convert(self, value, param, ctx) return int(value)
[ "def", "convert", "(", "self", ",", "value", ",", "param", ",", "ctx", ")", ":", "self", ".", "gandi", "=", "ctx", ".", "obj", "value", "=", "click", ".", "Choice", ".", "convert", "(", "self", ",", "value", ",", "param", ",", "ctx", ")", "return...
37.6
0.010417
def derivative_factory(name): """Create derivative function for some ufuncs.""" if name == 'sin': def derivative(self, point): """Return the derivative operator.""" return MultiplyOperator(cos(self.domain)(point)) elif name == 'cos': def derivative(self, point): ...
[ "def", "derivative_factory", "(", "name", ")", ":", "if", "name", "==", "'sin'", ":", "def", "derivative", "(", "self", ",", "point", ")", ":", "\"\"\"Return the derivative operator.\"\"\"", "return", "MultiplyOperator", "(", "cos", "(", "self", ".", "domain", ...
38.754717
0.000475
def _ensure_annotations(dashboard): '''Explode annotation_tags into annotations.''' if 'annotation_tags' not in dashboard: return tags = dashboard['annotation_tags'] annotations = { 'enable': True, 'list': [], } for tag in tags: annotations['list'].append({ ...
[ "def", "_ensure_annotations", "(", "dashboard", ")", ":", "if", "'annotation_tags'", "not", "in", "dashboard", ":", "return", "tags", "=", "dashboard", "[", "'annotation_tags'", "]", "annotations", "=", "{", "'enable'", ":", "True", ",", "'list'", ":", "[", ...
29.545455
0.00149
def find_file_match(folder_path, regex=''): """ Returns absolute paths of files that match the regex within folder_path and all its children folders. Note: The regex matching is done using the match function of the re module. Parameters ---------- folder_path: string regex: string...
[ "def", "find_file_match", "(", "folder_path", ",", "regex", "=", "''", ")", ":", "outlist", "=", "[", "]", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "folder_path", ")", ":", "outlist", ".", "extend", "(", "[", "os", "....
22
0.001742
def split_grads_by_size(threshold_size, device_grads): """Break gradients into two sets according to tensor size. Args: threshold_size: int size cutoff for small vs large tensor. device_grads: List of lists of (gradient, variable) tuples. The outer list is over devices. The inner list is over in...
[ "def", "split_grads_by_size", "(", "threshold_size", ",", "device_grads", ")", ":", "small_grads", "=", "[", "]", "large_grads", "=", "[", "]", "for", "dl", "in", "device_grads", ":", "small_dl", "=", "[", "]", "large_dl", "=", "[", "]", "for", "(", "g",...
33.5
0.000967
def mod_run_check(cmd_kwargs, onlyif, unless, creates): ''' Execute the onlyif and unless logic. Return a result dict if: * onlyif failed (onlyif != 0) * unless succeeded (unless == 0) else return True ''' # never use VT for onlyif/unless executions because this will lead # to quote ...
[ "def", "mod_run_check", "(", "cmd_kwargs", ",", "onlyif", ",", "unless", ",", "creates", ")", ":", "# never use VT for onlyif/unless executions because this will lead", "# to quote problems", "cmd_kwargs", "=", "copy", ".", "deepcopy", "(", "cmd_kwargs", ")", "cmd_kwargs"...
43.666667
0.002488
def compute_grouped_sigma(ungrouped_sigma, group_matrix): ''' Returns sigma for the groups of parameter values in the argument ungrouped_metric where the group consists of no more than one parameter ''' group_matrix = np.array(group_matrix, dtype=np.bool) sigma_masked = np.ma.masked_array(...
[ "def", "compute_grouped_sigma", "(", "ungrouped_sigma", ",", "group_matrix", ")", ":", "group_matrix", "=", "np", ".", "array", "(", "group_matrix", ",", "dtype", "=", "np", ".", "bool", ")", "sigma_masked", "=", "np", ".", "ma", ".", "masked_array", "(", ...
39.058824
0.001471
def parse_cli_args_into(): """ Creates the cli argparser for application specifics and AWS credentials. :return: A dict of values from the cli arguments :rtype: TemplaterCommand """ cli_arg_parser = argparse.ArgumentParser(parents=[ AWSArgumentParser(default_role_session_name='aws-autodi...
[ "def", "parse_cli_args_into", "(", ")", ":", "cli_arg_parser", "=", "argparse", ".", "ArgumentParser", "(", "parents", "=", "[", "AWSArgumentParser", "(", "default_role_session_name", "=", "'aws-autodiscovery-templater'", ")", "]", ")", "main_parser", "=", "cli_arg_pa...
56.710526
0.005931
def energy(self, strand, dotparens, temp=37.0, pseudo=False, material=None, dangles='some', sodium=1.0, magnesium=0.0): '''Calculate the free energy of a given sequence structure. Runs the \'energy\' command. :param strand: Strand on which to run energy. Strands must be either ...
[ "def", "energy", "(", "self", ",", "strand", ",", "dotparens", ",", "temp", "=", "37.0", ",", "pseudo", "=", "False", ",", "material", "=", "None", ",", "dangles", "=", "'some'", ",", "sodium", "=", "1.0", ",", "magnesium", "=", "0.0", ")", ":", "#...
47.627451
0.00121
def finalize(self, **kwargs): """ Finalize the drawing by adding a title and legend, and removing the axes objects that do not convey information about TNSE. """ self.set_title( "TSNE Projection of {} Documents".format(self.n_instances_) ) # Remove th...
[ "def", "finalize", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "set_title", "(", "\"TSNE Projection of {} Documents\"", ".", "format", "(", "self", ".", "n_instances_", ")", ")", "# Remove the ticks", "self", ".", "ax", ".", "set_yticks", "(...
36.47619
0.002545
def H_n(self, n, x): """ constructs the Hermite polynomial of order n at position x (dimensionless) :param n: The n'the basis function. :type name: int. :param x: 1-dim position (dimensionless) :type state: float or numpy array. :returns: array-- H_n(x). ...
[ "def", "H_n", "(", "self", ",", "n", ",", "x", ")", ":", "if", "not", "self", ".", "_interpolation", ":", "n_array", "=", "np", ".", "zeros", "(", "n", "+", "1", ")", "n_array", "[", "n", "]", "=", "1", "return", "self", ".", "hermval", "(", ...
41.411765
0.005556
def pre_release(version): """Generates new docs, release announcements and creates a local tag.""" announce(version) regen() changelog(version, write_out=True) fix_formatting() msg = "Preparing release version {}".format(version) check_call(["git", "commit", "-a", "-m", msg]) print() ...
[ "def", "pre_release", "(", "version", ")", ":", "announce", "(", "version", ")", "regen", "(", ")", "changelog", "(", "version", ",", "write_out", "=", "True", ")", "fix_formatting", "(", ")", "msg", "=", "\"Preparing release version {}\"", ".", "format", "(...
31.428571
0.002208
def parse_rst_params(doc): """ Parse a reStructuredText docstring and return a dictionary with parameter names and descriptions. >>> doc = ''' ... :param foo: foo parameter ... foo parameter ... ... :param bar: bar parameter ... :param baz: baz parameter ... ...
[ "def", "parse_rst_params", "(", "doc", ")", ":", "param_re", "=", "re", ".", "compile", "(", "r\"\"\"^([ \\t]*):param\\ \n (?P<param>\\w+):\\ \n (?P<body>.*\\n(\\1[ \\t]+\\w.*\\n)*)\"\"\"", ",", "re", ".", "MULTILINE", "|", ...
30.235294
0.00754
def render_flow(self, data): """render the OpenDocument with the user data @param data: the input stream of user data. This should be a dictionary mapping, keys being the values accessible to your report. @type data: dictionary """ self.render_tree(data) # then...
[ "def", "render_flow", "(", "self", ",", "data", ")", ":", "self", ".", "render_tree", "(", "data", ")", "# then reconstruct a new ODT document with the generated content", "for", "status", "in", "self", ".", "__save_output", "(", ")", ":", "yield", "status" ]
33.461538
0.004474
def dgrep(pat,*opts): """Return grep() on dir()+dir(__builtins__). A very common use of grep() when working interactively.""" return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
[ "def", "dgrep", "(", "pat", ",", "*", "opts", ")", ":", "return", "grep", "(", "pat", ",", "dir", "(", "__main__", ")", "+", "dir", "(", "__main__", ".", "__builtins__", ")", ",", "*", "opts", ")" ]
33
0.019704
def filter_savitzky_golay(y, window_size=5, order=2, deriv=0, rate=1): """Smooth (and optionally differentiate) with a Savitzky-Golay filter.""" try: window_size = np.abs(np.int(window_size)) order = np.abs(np.int(order)) except ValueError: raise ValueError('window_size and order mus...
[ "def", "filter_savitzky_golay", "(", "y", ",", "window_size", "=", "5", ",", "order", "=", "2", ",", "deriv", "=", "0", ",", "rate", "=", "1", ")", ":", "try", ":", "window_size", "=", "np", ".", "abs", "(", "np", ".", "int", "(", "window_size", ...
37.441176
0.000766
def bottleneck_block_v1(cnn, depth, depth_bottleneck, stride): """Bottleneck block with identity short-cut for ResNet v1. Args: cnn: the network to append bottleneck blocks. depth: the number of output filters for this bottleneck block. depth_bottleneck: the number of bottleneck filters for this bloc...
[ "def", "bottleneck_block_v1", "(", "cnn", ",", "depth", ",", "depth_bottleneck", ",", "stride", ")", ":", "input_layer", "=", "cnn", ".", "top_layer", "in_size", "=", "cnn", ".", "top_size", "name_key", "=", "\"resnet_v1\"", "name", "=", "name_key", "+", "st...
29.587302
0.000519
def add_info_widget(self, widget): ''' Add widget string to right panel of the screen ''' index = widget.get_index() while index in self.info_widgets.keys(): index += 1 self.info_widgets[widget.get_index()] = widget
[ "def", "add_info_widget", "(", "self", ",", "widget", ")", ":", "index", "=", "widget", ".", "get_index", "(", ")", "while", "index", "in", "self", ".", "info_widgets", ".", "keys", "(", ")", ":", "index", "+=", "1", "self", ".", "info_widgets", "[", ...
33.5
0.007273
def set(self, key, val): """ Return a new PMap with key and val inserted. >>> m1 = m(a=1, b=2) >>> m2 = m1.set('a', 3) >>> m3 = m1.set('c' ,4) >>> m1 pmap({'a': 1, 'b': 2}) >>> m2 pmap({'a': 3, 'b': 2}) >>> m3 pmap({'a': 1, 'c': 4,...
[ "def", "set", "(", "self", ",", "key", ",", "val", ")", ":", "return", "self", ".", "evolver", "(", ")", ".", "set", "(", "key", ",", "val", ")", ".", "persistent", "(", ")" ]
25.6
0.005025
def on_unexpected_error(e): # pragma: no cover """Catch-all error handler Unexpected errors will be handled by this function. """ sys.stderr.write('Unexpected error: {} ({})\n'.format( str(e), e.__class__.__name__)) sys.stderr.write('See file slam_error.log for additional details.\n') ...
[ "def", "on_unexpected_error", "(", "e", ")", ":", "# pragma: no cover", "sys", ".", "stderr", ".", "write", "(", "'Unexpected error: {} ({})\\n'", ".", "format", "(", "str", "(", "e", ")", ",", "e", ".", "__class__", ".", "__name__", ")", ")", "sys", ".", ...
35.888889
0.003021
def make_node(cls, id_, arglist, lineno): """ Creates an array access. A(x1, x2, ..., xn) """ assert isinstance(arglist, SymbolARGLIST) variable = gl.SYMBOL_TABLE.access_array(id_, lineno) if variable is None: return None if len(variable.bounds) != len(arglis...
[ "def", "make_node", "(", "cls", ",", "id_", ",", "arglist", ",", "lineno", ")", ":", "assert", "isinstance", "(", "arglist", ",", "SymbolARGLIST", ")", "variable", "=", "gl", ".", "SYMBOL_TABLE", ".", "access_array", "(", "id_", ",", "lineno", ")", "if",...
46.896552
0.002882
def delete(cls, group, admin): """Delete admin from group. :param group: Group object. :param admin: Admin object. """ with db.session.begin_nested(): obj = cls.query.filter( cls.admin == admin, cls.group == group).one() db.session.delete(...
[ "def", "delete", "(", "cls", ",", "group", ",", "admin", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "obj", "=", "cls", ".", "query", ".", "filter", "(", "cls", ".", "admin", "==", "admin", ",", "cls", ".", "group"...
31.5
0.006173
def trace_incoming_web_request( self, webapp_info, url, method, headers=None, remote_address=None, str_tag=None, byte_tag=None): '''Create a tracer for an incoming webrequest. :param WebapplicationInfoHandle...
[ "def", "trace_incoming_web_request", "(", "self", ",", "webapp_info", ",", "url", ",", "method", ",", "headers", "=", "None", ",", "remote_address", "=", "None", ",", "str_tag", "=", "None", ",", "byte_tag", "=", "None", ")", ":", "assert", "isinstance", "...
42.565217
0.000998
def difference(self,other): """ Return a new DiscreteSet with the difference of the two sets, i.e. all elements that are in self but not in other. :param DiscreteSet other: Set to subtract :rtype: DiscreteSet :raises ValueError: if self is a set of everything """...
[ "def", "difference", "(", "self", ",", "other", ")", ":", "if", "self", ".", "everything", ":", "raise", "ValueError", "(", "\"Can not remove from everything\"", ")", "elif", "other", ".", "everything", ":", "return", "DiscreteSet", "(", "[", "]", ")", "else...
36.666667
0.005319
def _extract_table_root(d, current, pc): """ Extract data from the root level of a paleoData table. :param dict d: paleoData table :param dict current: Current root data :param str pc: paleoData or chronData :return dict current: Current root data """ logger_ts.info("enter extract_table_...
[ "def", "_extract_table_root", "(", "d", ",", "current", ",", "pc", ")", ":", "logger_ts", ".", "info", "(", "\"enter extract_table_root\"", ")", "try", ":", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", "...
33.375
0.001821