text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _sent_by(self, origin, cable): """\ `origin` Topic identity (commonly a subject identifier) of the originator of the cable `cable` Topic identity (commonly a subject identifier) of the cable. """ self._assoc(psis.SENT_BY_TYPE, psis...
[ "def", "_sent_by", "(", "self", ",", "origin", ",", "cable", ")", ":", "self", ".", "_assoc", "(", "psis", ".", "SENT_BY_TYPE", ",", "psis", ".", "SENDER_TYPE", ",", "origin", ",", "psis", ".", "CABLE_TYPE", ",", "cable", ")" ]
34.090909
16.909091
def _writeMzmlIndexList(xmlWriter, spectrumIndexList, chromatogramIndexList): """ #TODO: docstring :param xmlWriter: #TODO: docstring :param spectrumIndexList: #TODO: docstring :param chromatogramIndexList: #TODO: docstring """ counts = 0 if spectrumIndexList: counts += 1 if chr...
[ "def", "_writeMzmlIndexList", "(", "xmlWriter", ",", "spectrumIndexList", ",", "chromatogramIndexList", ")", ":", "counts", "=", "0", "if", "spectrumIndexList", ":", "counts", "+=", "1", "if", "chromatogramIndexList", ":", "counts", "+=", "1", "if", "counts", "=...
31
19.28
def _construct_first_indent(self, pos): """ build spacer to occupy the first indentation level from pos to the left. This is separate as it adds arrowtip and sibling connector. """ cols = [] void = urwid.AttrMap(urwid.SolidFill(' '), self._arrow_att) available_wid...
[ "def", "_construct_first_indent", "(", "self", ",", "pos", ")", ":", "cols", "=", "[", "]", "void", "=", "urwid", ".", "AttrMap", "(", "urwid", ".", "SolidFill", "(", "' '", ")", ",", "self", ".", "_arrow_att", ")", "available_width", "=", "self", ".",...
42.186047
14.55814
def _has_population_germline(rec): """Check if header defines population annotated germline samples for tumor only. """ for k in population_keys: if k in rec.header.info: return True return False
[ "def", "_has_population_germline", "(", "rec", ")", ":", "for", "k", "in", "population_keys", ":", "if", "k", "in", "rec", ".", "header", ".", "info", ":", "return", "True", "return", "False" ]
32.142857
9.428571
def addresses(self): """ Return a new raw REST interface to address resources :rtype: :py:class:`ns1.rest.ipam.Adresses` """ import ns1.rest.ipam return ns1.rest.ipam.Addresses(self.config)
[ "def", "addresses", "(", "self", ")", ":", "import", "ns1", ".", "rest", ".", "ipam", "return", "ns1", ".", "rest", ".", "ipam", ".", "Addresses", "(", "self", ".", "config", ")" ]
28.875
14.125
def server_check(arg): """Check and format --server arg """ if arg.startswith(('http://', 'https://', 'http+unix://')): return arg if arg.startswith('./'): arg = os.path.abspath(arg) elif not arg.startswith('/'): raise argparse.ArgumentTypeError( 'Unix socket path...
[ "def", "server_check", "(", "arg", ")", ":", "if", "arg", ".", "startswith", "(", "(", "'http://'", ",", "'https://'", ",", "'http+unix://'", ")", ")", ":", "return", "arg", "if", "arg", ".", "startswith", "(", "'./'", ")", ":", "arg", "=", "os", "."...
35.333333
10.583333
def fit(self, weighted, show_progress=True): """ Computes and stores the similarity matrix """ self.similarity = all_pairs_knn(weighted, self.K, show_progress=show_progress, num_threads=self.num_threads).tocsr() self...
[ "def", "fit", "(", "self", ",", "weighted", ",", "show_progress", "=", "True", ")", ":", "self", ".", "similarity", "=", "all_pairs_knn", "(", "weighted", ",", "self", ".", "K", ",", "show_progress", "=", "show_progress", ",", "num_threads", "=", "self", ...
60.833333
18
def _read_opt_home(self, code, *, desc): """Read HOPOPT Home Address option. Structure of HOPOPT Home Address option [RFC 6275]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ...
[ "def", "_read_opt_home", "(", "self", ",", "code", ",", "*", ",", "desc", ")", ":", "_type", "=", "self", ".", "_read_opt_type", "(", "code", ")", "_size", "=", "self", ".", "_read_unpack", "(", "1", ")", "if", "_size", "!=", "16", ":", "raise", "P...
49.926829
27.341463
def start(config, bugnumber=""): """Create a new topic branch.""" repo = config.repo if bugnumber: summary, bugnumber, url = get_summary(config, bugnumber) else: url = None summary = None if summary: summary = input('Summary ["{}"]: '.format(summary)).strip() or sum...
[ "def", "start", "(", "config", ",", "bugnumber", "=", "\"\"", ")", ":", "repo", "=", "config", ".", "repo", "if", "bugnumber", ":", "summary", ",", "bugnumber", ",", "url", "=", "get_summary", "(", "config", ",", "bugnumber", ")", "else", ":", "url", ...
31.5
20.666667
def proxied_get(self, *args, **kwargs): """ Perform the query and returns a single object matching the given keyword arguments. This customizes the queryset to return an instance of ``ProxyDataSharingConsent`` when the searched-for ``DataSharingConsent`` instance does not exist. ...
[ "def", "proxied_get", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "original_kwargs", "=", "kwargs", ".", "copy", "(", ")", "if", "'course_id'", "in", "kwargs", ":", "try", ":", "# Check if we have a course ID or a course run ID", "course_...
46.724138
23.275862
def continuous_partition_data(data, bins='auto', n_bins=10): """Convenience method for building a partition object on continuous data Args: data (list-like): The data from which to construct the estimate. bins (string): One of 'uniform' (for uniformly spaced bins), 'ntile' (for percentile-space...
[ "def", "continuous_partition_data", "(", "data", ",", "bins", "=", "'auto'", ",", "n_bins", "=", "10", ")", ":", "if", "bins", "==", "'uniform'", ":", "bins", "=", "np", ".", "linspace", "(", "start", "=", "np", ".", "min", "(", "data", ")", ",", "...
36.1
26.466667
def add_host_mapping(host_id, nexus_ip, interface, ch_grp, is_static): """Add Host to interface mapping entry into mapping data base. :param host_id: is the name of the host to add :param interface: is the interface for this host :param nexus_ip: is the ip addr of the nexus switch for this interface ...
[ "def", "add_host_mapping", "(", "host_id", ",", "nexus_ip", ",", "interface", ",", "ch_grp", ",", "is_static", ")", ":", "LOG", ".", "debug", "(", "\"add_nexusport_binding() called\"", ")", "session", "=", "bc", ".", "get_writer_session", "(", ")", "mapping", ...
40.233333
17.066667
async def auth_complete_async(self): """Whether the authentication handshake is complete during connection initialization. :rtype: bool """ timeout = False auth_in_progress = False if self._connection.cbs: timeout, auth_in_progress = await self._auth....
[ "async", "def", "auth_complete_async", "(", "self", ")", ":", "timeout", "=", "False", "auth_in_progress", "=", "False", "if", "self", ".", "_connection", ".", "cbs", ":", "timeout", ",", "auth_in_progress", "=", "await", "self", ".", "_auth", ".", "handle_t...
38.3
16.95
def write_how_many(self, file): """ Writes component numbers to a table. """ report = CaseReport(self.case) # Map component labels to attribute names components = [("Bus", "n_buses"), ("Generator", "n_generators"), ("Committed Generator", "n_online_generators"), ...
[ "def", "write_how_many", "(", "self", ",", "file", ")", ":", "report", "=", "CaseReport", "(", "self", ".", "case", ")", "# Map component labels to attribute names", "components", "=", "[", "(", "\"Bus\"", ",", "\"n_buses\"", ")", ",", "(", "\"Generator\"", ",...
31.159091
21
def mmatch(expr, delimiter, greedy, search_type, regex_match=False, exact_match=False, opts=None): ''' Helper function to search for minions in master caches If 'greedy' return accepted minions that matched by the condition or absent in the c...
[ "def", "mmatch", "(", "expr", ",", "delimiter", ",", "greedy", ",", "search_type", ",", "regex_match", "=", "False", ",", "exact_match", "=", "False", ",", "opts", "=", "None", ")", ":", "if", "not", "opts", ":", "opts", "=", "__opts__", "ckminions", "...
35.6
26.5
def fetchThreads(self, thread_location, before=None, after=None, limit=None): """ Get all threads in thread_location. Threads will be sorted from newest to oldest. :param thread_location: models.ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER :param before: Fetch only thread b...
[ "def", "fetchThreads", "(", "self", ",", "thread_location", ",", "before", "=", "None", ",", "after", "=", "None", ",", "limit", "=", "None", ")", ":", "threads", "=", "[", "]", "last_thread_timestamp", "=", "None", "while", "True", ":", "# break if limit ...
38.903846
23.288462
def add_inner_product(self, name, W, b, input_channels, output_channels, has_bias, input_name, output_name, **kwargs): """ Add an inner product layer to the model. Parameters ---------- name: str The name of this layer W: numpy.array...
[ "def", "add_inner_product", "(", "self", ",", "name", ",", "W", ",", "b", ",", "input_channels", ",", "output_channels", ",", "has_bias", ",", "input_name", ",", "output_name", ",", "*", "*", "kwargs", ")", ":", "spec", "=", "self", ".", "spec", "nn_spec...
37.923077
24.538462
def run(self, options): """ .. todo:: check network connection :param Namespace options: parse result from argparse :return: """ self.logger.debug("debug enabled...") depends = ['git'] nil_tools = [] self.logger.info("depends list: ...
[ "def", "run", "(", "self", ",", "options", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"debug enabled...\"", ")", "depends", "=", "[", "'git'", "]", "nil_tools", "=", "[", "]", "self", ".", "logger", ".", "info", "(", "\"depends list: %s\"", ...
30.325581
20.651163
def grade(PmagRec, ACCEPT, type, data_model=2.5): """ Finds the 'grade' (pass/fail; A/F) of a record (specimen,sample,site) given the acceptance criteria """ GREATERTHAN = ['specimen_q', 'site_k', 'site_n', 'site_n_lines', 'site_int_n', 'measurement_step_min', 'specimen_int_ptrm_n', 'specimen_fvds', 'sp...
[ "def", "grade", "(", "PmagRec", ",", "ACCEPT", ",", "type", ",", "data_model", "=", "2.5", ")", ":", "GREATERTHAN", "=", "[", "'specimen_q'", ",", "'site_k'", ",", "'site_n'", ",", "'site_n_lines'", ",", "'site_int_n'", ",", "'measurement_step_min'", ",", "'...
58.1125
28.8875
def match_local(self, prefix, includes, excludes): """ Filters os.walk() with include and exclude patterns. See: http://stackoverflow.com/a/5141829/93559 """ includes_pattern = r"|".join([fnmatch.translate(x) for x in includes]) excludes_pattern = r"|".join([fnmatch.trans...
[ "def", "match_local", "(", "self", ",", "prefix", ",", "includes", ",", "excludes", ")", ":", "includes_pattern", "=", "r\"|\"", ".", "join", "(", "[", "fnmatch", ".", "translate", "(", "x", ")", "for", "x", "in", "includes", "]", ")", "excludes_pattern"...
49.5
18.409091
def _function(self, type, name, args=""): """ Returns a context manager for writing a function. :param str type: The return type of the function :param str name: The name of the functino :param str args: The argument specification for the function """ return Func...
[ "def", "_function", "(", "self", ",", "type", ",", "name", ",", "args", "=", "\"\"", ")", ":", "return", "FunctionManager", "(", "self", ",", "type", "=", "type", ",", "name", "=", "name", ",", "args", "=", "args", ")" ]
40.222222
15.555556
def __neuron_evolution(self, index): """! @brief Calculates state of the neuron with specified index. @param[in] index (uint): Index of neuron in the network. @return (double) New output of the specified neuron. """ value = 0.0 ...
[ "def", "__neuron_evolution", "(", "self", ",", "index", ")", ":", "value", "=", "0.0", "for", "index_neighbor", "in", "range", "(", "self", ".", "__num_osc", ")", ":", "value", "+=", "self", ".", "__weights", "[", "index", "]", "[", "index_neighbor", "]"...
35.866667
23.266667
def interpreter_versions(self): """Python and IPython versions used by clients""" if CONF.get('main_interpreter', 'default'): from IPython.core import release versions = dict( python_version = sys.version.split("\n")[0].strip(), ipython_versi...
[ "def", "interpreter_versions", "(", "self", ")", ":", "if", "CONF", ".", "get", "(", "'main_interpreter'", ",", "'default'", ")", ":", "from", "IPython", ".", "core", "import", "release", "versions", "=", "dict", "(", "python_version", "=", "sys", ".", "ve...
42.517241
17.068966
def run(main=None, argv=None, **flags): """ :param main: main or sys.modules['__main__'].main :param argv: argument list used in argument parse :param flags: flags to define with defaults :return: """ """Runs the program with an optional 'main' function and 'argv' list.""" import sys as ...
[ "def", "run", "(", "main", "=", "None", ",", "argv", "=", "None", ",", "*", "*", "flags", ")", ":", "\"\"\"Runs the program with an optional 'main' function and 'argv' list.\"\"\"", "import", "sys", "as", "_sys", "import", "inspect", "main", "=", "main", "or", "...
29.418182
18.8
def init_options(self): """ Initialize the underlying map options. """ self.options = GoogleMapOptions() d = self.declaration self.set_map_type(d.map_type) if d.ambient_mode: self.set_ambient_mode(d.ambient_mode) if (d.camera_position or d.camera_zoom...
[ "def", "init_options", "(", "self", ")", ":", "self", ".", "options", "=", "GoogleMapOptions", "(", ")", "d", "=", "self", ".", "declaration", "self", ".", "set_map_type", "(", "d", ".", "map_type", ")", "if", "d", ".", "ambient_mode", ":", "self", "."...
36.852941
10.294118
def list_parameters_as_df(self): """ Only really useful when running from a jupyter notebook. Lists the parameters in the model in a pandas dataframe Columns: id, matrix coordinates, description, function """ to_df = [] for i, e in enumerate(self.ext_params): ...
[ "def", "list_parameters_as_df", "(", "self", ")", ":", "to_df", "=", "[", "]", "for", "i", ",", "e", "in", "enumerate", "(", "self", ".", "ext_params", ")", ":", "row", "=", "{", "}", "row", "[", "'id'", "]", "=", "e", "[", "'name'", "]", "row", ...
25.96875
18.28125
def _get_group_object(name): ''' A helper function to get a specified group object Args: name (str): The name of the object Returns: object: The specified group object ''' with salt.utils.winapi.Com(): nt = win32com.client.Dispatch('AdsNameSpaces') return nt.GetObj...
[ "def", "_get_group_object", "(", "name", ")", ":", "with", "salt", ".", "utils", ".", "winapi", ".", "Com", "(", ")", ":", "nt", "=", "win32com", ".", "client", ".", "Dispatch", "(", "'AdsNameSpaces'", ")", "return", "nt", ".", "GetObject", "(", "''", ...
24.714286
22.428571
def _construct_callbacks(self): """ Initializes any callbacks for streams which have defined the plotted object as a source. """ cb_classes = set() registry = list(Stream.registry.items()) callbacks = Stream._callbacks['bokeh'] for source in self.link_sour...
[ "def", "_construct_callbacks", "(", "self", ")", ":", "cb_classes", "=", "set", "(", ")", "registry", "=", "list", "(", "Stream", ".", "registry", ".", "items", "(", ")", ")", "callbacks", "=", "Stream", ".", "_callbacks", "[", "'bokeh'", "]", "for", "...
45.681818
16.227273
def _make_params_pb(params, param_types): """Helper for :meth:`execute_update`. :type params: dict, {str -> column value} :param params: values for parameter replacement. Keys must match the names used in ``dml``. :type param_types: dict[str -> Union[dict, .type...
[ "def", "_make_params_pb", "(", "params", ",", "param_types", ")", ":", "if", "params", "is", "not", "None", ":", "if", "param_types", "is", "None", ":", "raise", "ValueError", "(", "\"Specify 'param_types' when passing 'params'.\"", ")", "return", "Struct", "(", ...
39.7
20.766667
def remove_archive(self, archive_path): """Remove an archive. This method deletes from the filesystem the archive stored in `archive_path`. :param archive_path: path to the archive :raises ArchiveManangerError: when an error occurs removing the archive """ ...
[ "def", "remove_archive", "(", "self", ",", "archive_path", ")", ":", "try", ":", "Archive", "(", "archive_path", ")", "except", "ArchiveError", "as", "e", ":", "raise", "ArchiveManagerError", "(", "cause", "=", "str", "(", "e", ")", ")", "os", ".", "remo...
27.588235
19
def handle_error(self, e): """ Resolve the problem about sometimes error message specified by programmer won't output to user. Flask-RESTFul's error handler handling format different exceptions has different behavior. If we raise an normal Exception, it will raise it again. If ...
[ "def", "handle_error", "(", "self", ",", "e", ")", ":", "if", "isinstance", "(", "e", ",", "HTTPException", ")", "and", "not", "hasattr", "(", "e", ",", "'data'", ")", ":", "e", ".", "data", "=", "dict", "(", "message", "=", "e", ".", "description"...
41.142857
27.22449
async def format(self, fstype, *, uuid=None): """Format this block device.""" self._data = await self._handler.format( system_id=self.node.system_id, id=self.id, fstype=fstype, uuid=uuid)
[ "async", "def", "format", "(", "self", ",", "fstype", ",", "*", ",", "uuid", "=", "None", ")", ":", "self", ".", "_data", "=", "await", "self", ".", "_handler", ".", "format", "(", "system_id", "=", "self", ".", "node", ".", "system_id", ",", "id",...
44.6
6
def isconstant(args, quoted=False): """Checks if value is a boolean, number or string.""" check = lambda c: isbool(c) or isnumber(c) or isstring(c, quoted) if isinstance(args, list): return all(map(check, args)) else: return check(args)
[ "def", "isconstant", "(", "args", ",", "quoted", "=", "False", ")", ":", "check", "=", "lambda", "c", ":", "isbool", "(", "c", ")", "or", "isnumber", "(", "c", ")", "or", "isstring", "(", "c", ",", "quoted", ")", "if", "isinstance", "(", "args", ...
37.428571
13.285714
def calc_area_under_PSD(self, lowerFreq, upperFreq): """ Sums the area under the PSD from lowerFreq to upperFreq. Parameters ---------- lowerFreq : float The lower limit of frequency to sum from upperFreq : float The upper limit of frequency to su...
[ "def", "calc_area_under_PSD", "(", "self", ",", "lowerFreq", ",", "upperFreq", ")", ":", "Freq_startAreaPSD", "=", "take_closest", "(", "self", ".", "freqs", ",", "lowerFreq", ")", "index_startAreaPSD", "=", "int", "(", "_np", ".", "where", "(", "self", ".",...
37.772727
21.227273
def get_plugin(self, name): """ Get a plugin by its name from the plugins loaded for the current namespace :param name: :return: """ for p in self._plugins: if p.name == name: return p return None
[ "def", "get_plugin", "(", "self", ",", "name", ")", ":", "for", "p", "in", "self", ".", "_plugins", ":", "if", "p", ".", "name", "==", "name", ":", "return", "p", "return", "None" ]
27.1
15.5
def _axes(self): """Set the _force_vertical flag when rendering axes""" self.view._force_vertical = True super(HorizontalGraph, self)._axes() self.view._force_vertical = False
[ "def", "_axes", "(", "self", ")", ":", "self", ".", "view", ".", "_force_vertical", "=", "True", "super", "(", "HorizontalGraph", ",", "self", ")", ".", "_axes", "(", ")", "self", ".", "view", ".", "_force_vertical", "=", "False" ]
40.6
5.8
def create_corpus(src, out_dir, no_below=20, keep_words=_DEFAULT_KEEP_WORDS): """\ """ wordid_filename = os.path.join(out_dir, 'cables_wordids.pickle') bow_filename = os.path.join(out_dir, 'cables_bow.mm') tfidf_filename = os.path.join(out_dir, 'cables_tfidf.mm') predicate = None # Could be set...
[ "def", "create_corpus", "(", "src", ",", "out_dir", ",", "no_below", "=", "20", ",", "keep_words", "=", "_DEFAULT_KEEP_WORDS", ")", ":", "wordid_filename", "=", "os", ".", "path", ".", "join", "(", "out_dir", ",", "'cables_wordids.pickle'", ")", "bow_filename"...
44.2
17.6
def extract_geometry(self, branch, branch_begin): """ It adds to self.geometries a specific geometry as (x, y) """ raw_geometry = [] with open(self.abspath) as fobj: for line in fobj.readlines()[branch_begin:]: points = [] for p...
[ "def", "extract_geometry", "(", "self", ",", "branch", ",", "branch_begin", ")", ":", "raw_geometry", "=", "[", "]", "with", "open", "(", "self", ".", "abspath", ")", "as", "fobj", ":", "for", "line", "in", "fobj", ".", "readlines", "(", ")", "[", "b...
40.368421
11.421053
def set_input_format(self, file_type=None, rate=None, bits=None, channels=None, encoding=None, ignore_length=None): '''Sets input file format arguments. This is primarily useful when dealing with audio files without a file extension. Overwrites any previously set input f...
[ "def", "set_input_format", "(", "self", ",", "file_type", "=", "None", ",", "rate", "=", "None", ",", "bits", "=", "None", ",", "channels", "=", "None", ",", "encoding", "=", "None", ",", "ignore_length", "=", "None", ")", ":", "if", "file_type", "is",...
45
24.587097
def initialize(self, grid, num_of_paths, seed): """ inits producer for a simulation run """ self.grid = grid self.num_of_paths = num_of_paths self.seed = seed if self.initial_state.date is None: self.initial_state.date = grid[0]
[ "def", "initialize", "(", "self", ",", "grid", ",", "num_of_paths", ",", "seed", ")", ":", "self", ".", "grid", "=", "grid", "self", ".", "num_of_paths", "=", "num_of_paths", "self", ".", "seed", "=", "seed", "if", "self", ".", "initial_state", ".", "d...
39.142857
6.714286
def run_on_all_sites(self, cmd, *args, **kwargs): """ Like run(), but re-runs the command for each site in the current role. """ r = self.local_renderer for _site, _data in iter_sites(): r.env.SITE = _site with self.settings(warn_only=True): ...
[ "def", "run_on_all_sites", "(", "self", ",", "cmd", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "r", "=", "self", ".", "local_renderer", "for", "_site", ",", "_data", "in", "iter_sites", "(", ")", ":", "r", ".", "env", ".", "SITE", "=", ...
40.777778
11.444444
def load_commands_from_entry_point(self, specifier): """ Load commands defined within a pkg_resources entry point. Each entry will be a module that should be searched for functions decorated with the :func:`subparse.command` decorator. This operation is not recursive. "...
[ "def", "load_commands_from_entry_point", "(", "self", ",", "specifier", ")", ":", "for", "ep", "in", "pkg_resources", ".", "iter_entry_points", "(", "specifier", ")", ":", "module", "=", "ep", ".", "load", "(", ")", "command", ".", "discover_and_call", "(", ...
38.666667
19.333333
def pkdecrypt(self, conn): """Handle decryption using ECDH.""" for msg in [b'S INQUIRE_MAXLEN 4096', b'INQUIRE CIPHERTEXT']: keyring.sendline(conn, msg) line = keyring.recvline(conn) assert keyring.recvline(conn) == b'END' remote_pubkey = parse_ecdh(line) id...
[ "def", "pkdecrypt", "(", "self", ",", "conn", ")", ":", "for", "msg", "in", "[", "b'S INQUIRE_MAXLEN 4096'", ",", "b'INQUIRE CIPHERTEXT'", "]", ":", "keyring", ".", "sendline", "(", "conn", ",", "msg", ")", "line", "=", "keyring", ".", "recvline", "(", "...
41.75
17.833333
def load_metadata_from_desc_file(self, desc_file, partition='train', max_duration=16.0,): """ Read metadata from the description file (possibly takes long, depending on the filesize) Params: desc_file (str): Path to a JSON-line file that cont...
[ "def", "load_metadata_from_desc_file", "(", "self", ",", "desc_file", ",", "partition", "=", "'train'", ",", "max_duration", "=", "16.0", ",", ")", ":", "logger", "=", "logUtil", ".", "getlogger", "(", ")", "logger", ".", "info", "(", "'Reading description fil...
46.408163
13.22449
def webify_file(srcfilename: str, destfilename: str) -> None: """ Rewrites a file from ``srcfilename`` to ``destfilename``, HTML-escaping it in the process. """ with open(srcfilename) as infile, open(destfilename, 'w') as ofile: for line_ in infile: ofile.write(escape(line_))
[ "def", "webify_file", "(", "srcfilename", ":", "str", ",", "destfilename", ":", "str", ")", "->", "None", ":", "with", "open", "(", "srcfilename", ")", "as", "infile", ",", "open", "(", "destfilename", ",", "'w'", ")", "as", "ofile", ":", "for", "line_...
38.625
15.625
def collect_api_results(input_data, url, headers, api, batch_size, kwargs): """ Optionally split up a single request into a series of requests to ensure timely HTTP responses. Could eventually speed up the time required to receive a response by sending batches to the indico API concurrently """...
[ "def", "collect_api_results", "(", "input_data", ",", "url", ",", "headers", ",", "api", ",", "batch_size", ",", "kwargs", ")", ":", "if", "batch_size", ":", "results", "=", "[", "]", "for", "batch", "in", "batched", "(", "input_data", ",", "size", "=", ...
42.947368
19.894737
def set_app_id(self, id, version, icon): '''Sets some meta-information about the application. See also L{set_user_agent}(). @param id: Java-style application identifier, e.g. "com.acme.foobar". @param version: application version numbers, e.g. "1.2.3". @param icon: application ic...
[ "def", "set_app_id", "(", "self", ",", "id", ",", "version", ",", "icon", ")", ":", "return", "libvlc_set_app_id", "(", "self", ",", "str_to_bytes", "(", "id", ")", ",", "str_to_bytes", "(", "version", ")", ",", "str_to_bytes", "(", "icon", ")", ")" ]
54.222222
21.333333
def get_status(video_id, _connection=None): """ Get the status of a video given the ``video_id`` parameter. """ c = _connection if not c: c = connection.APIConnection() return c.post('get_upload_status', video_id=video_id)
[ "def", "get_status", "(", "video_id", ",", "_connection", "=", "None", ")", ":", "c", "=", "_connection", "if", "not", "c", ":", "c", "=", "connection", ".", "APIConnection", "(", ")", "return", "c", ".", "post", "(", "'get_upload_status'", ",", "video_i...
34.375
11.625
def set_dword_at_offset(self, offset, dword): """Set the double word value at the given file offset.""" return self.set_bytes_at_offset(offset, self.get_data_from_dword(dword))
[ "def", "set_dword_at_offset", "(", "self", ",", "offset", ",", "dword", ")", ":", "return", "self", ".", "set_bytes_at_offset", "(", "offset", ",", "self", ".", "get_data_from_dword", "(", "dword", ")", ")" ]
63.333333
15
def nfa_complementation(nfa: dict) -> dict: """ Returns a DFA reading the complemented language read by input NFA. Complement a nondeterministic automaton is possible complementing the determinization of it. The construction is effective, but it involves an exponential blow-up, since determiniz...
[ "def", "nfa_complementation", "(", "nfa", ":", "dict", ")", "->", "dict", ":", "determinized_nfa", "=", "nfa_determinization", "(", "nfa", ")", "return", "DFA", ".", "dfa_complementation", "(", "determinized_nfa", ")" ]
38.875
13.875
def parse(self): """Parse a Supybot IRC stream. Returns an iterator of dicts. Each dicts contains information about the date, type, nick and body of a single log entry. :returns: iterator of parsed lines :raises ParseError: when an invalid line is found parsing the given ...
[ "def", "parse", "(", "self", ")", ":", "for", "line", "in", "self", ".", "stream", ":", "line", "=", "line", ".", "rstrip", "(", "'\\n'", ")", "self", ".", "nline", "+=", "1", "if", "self", ".", "SUPYBOT_EMPTY_REGEX", ".", "match", "(", "line", ")"...
30.935484
22.451613
def list_component_status(self, **kwargs): """ list objects of kind ComponentStatus This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_component_status(async_req=True) >>> result ...
[ "def", "list_component_status", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "list_component_status_with_http_info", ...
166.962963
137.185185
def cluster_reset(self, *, hard=False): """Reset a Redis Cluster node.""" reset = hard and b'HARD' or b'SOFT' fut = self.execute(b'CLUSTER', b'RESET', reset) return wait_ok(fut)
[ "def", "cluster_reset", "(", "self", ",", "*", ",", "hard", "=", "False", ")", ":", "reset", "=", "hard", "and", "b'HARD'", "or", "b'SOFT'", "fut", "=", "self", ".", "execute", "(", "b'CLUSTER'", ",", "b'RESET'", ",", "reset", ")", "return", "wait_ok",...
41
6.4
def paginate_queryset(self, queryset, request, view=None): """ adds `max_count` as a running tally of the largest table size. Used for calculating next/previous links later """ result = super(MultipleModelLimitOffsetPagination, self).paginate_queryset(queryset, request, view) ...
[ "def", "paginate_queryset", "(", "self", ",", "queryset", ",", "request", ",", "view", "=", "None", ")", ":", "result", "=", "super", "(", "MultipleModelLimitOffsetPagination", ",", "self", ")", ".", "paginate_queryset", "(", "queryset", ",", "request", ",", ...
32.263158
19.736842
def _crates_cache() -> str: """ Return the path to the crates cache folder """ return os.environ.get( 'XDG_CACHE_HOME', os.path.join(os.path.expanduser('~'), '.cache', 'cr8', 'crates'))
[ "def", "_crates_cache", "(", ")", "->", "str", ":", "return", "os", ".", "environ", ".", "get", "(", "'XDG_CACHE_HOME'", ",", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", ",", "'.cache'", ",", "'cr8'", ...
41
15
def html_with_encoding(self, url, timeout=None, encoding="utf-8"): """Manually get html with user encoding setting. """ response = self.get_response(url, timeout=timeout) if response: return self.decoder.decode(response.content, encoding)[0] else: return N...
[ "def", "html_with_encoding", "(", "self", ",", "url", ",", "timeout", "=", "None", ",", "encoding", "=", "\"utf-8\"", ")", ":", "response", "=", "self", ".", "get_response", "(", "url", ",", "timeout", "=", "timeout", ")", "if", "response", ":", "return"...
39.5
17.125
def print_kernel_code(self, output_file=sys.stdout): """Print source code of kernel.""" print(self.kernel_code, file=output_file)
[ "def", "print_kernel_code", "(", "self", ",", "output_file", "=", "sys", ".", "stdout", ")", ":", "print", "(", "self", ".", "kernel_code", ",", "file", "=", "output_file", ")" ]
47.666667
7
def update_db(self, new_values): """Update database values and application configuration. The provided keys must be defined in the ``WAFFLE_CONFS`` setting. Arguments: new_values (dict): dict of configuration variables and their values The dict has the following str...
[ "def", "update_db", "(", "self", ",", "new_values", ")", ":", "confs", "=", "self", ".", "app", ".", "config", ".", "get", "(", "'WAFFLE_CONFS'", ",", "{", "}", ")", "to_update", "=", "{", "}", "for", "key", "in", "new_values", ".", "keys", "(", ")...
28.780488
19.439024
def set_secure_cookie( self, name: str, value: Union[str, bytes], expires_days: int = 30, version: int = None, **kwargs: Any ) -> None: """Signs and timestamps a cookie so it cannot be forged. You must specify the ``cookie_secret`` setting in your App...
[ "def", "set_secure_cookie", "(", "self", ",", "name", ":", "str", ",", "value", ":", "Union", "[", "str", ",", "bytes", "]", ",", "expires_days", ":", "int", "=", "30", ",", "version", ":", "int", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ...
33.972973
22.432432
async def set(self, full, valu): ''' A set operation at the hive level (full path). ''' node = await self._getHiveNode(full) oldv = node.valu node.valu = await self.storNodeValu(full, valu) await node.fire('hive:set', path=full, valu=valu, oldv=oldv) r...
[ "async", "def", "set", "(", "self", ",", "full", ",", "valu", ")", ":", "node", "=", "await", "self", ".", "_getHiveNode", "(", "full", ")", "oldv", "=", "node", ".", "valu", "node", ".", "valu", "=", "await", "self", ".", "storNodeValu", "(", "ful...
24.461538
24.923077
def isdir(self, path): """ Is the parameter S3 path a directory? """ (bucket, key) = self._path_to_bucket_and_key(path) s3_bucket = self.s3.Bucket(bucket) # root is a directory if self._is_root(key): return True for suffix in (S3_DIRECTORY_M...
[ "def", "isdir", "(", "self", ",", "path", ")", ":", "(", "bucket", ",", "key", ")", "=", "self", ".", "_path_to_bucket_and_key", "(", "path", ")", "s3_bucket", "=", "self", ".", "s3", ".", "Bucket", "(", "bucket", ")", "# root is a directory", "if", "s...
30.935484
17.516129
def get_all_option_pool(self, option_type=None): """Get all Option Pool. :return: Dictionary with the following structure: :: {[{‘id’: < id >, ‘type’: < tipo_opcao >, ‘name’: < nome_opcao_txt >}, ... other option pool ...] } :raise optionpoolNotFou...
[ "def", "get_all_option_pool", "(", "self", ",", "option_type", "=", "None", ")", ":", "if", "option_type", ":", "url", "=", "'api/pools/options/?type='", "+", "option_type", "else", ":", "url", "=", "'api/pools/options/'", "return", "self", ".", "get", "(", "u...
29.181818
22.272727
def factory(cls, object_raw): """Return a proper object """ if object_raw is None: return None if object_raw.type is ObjectRaw.Types.object: return ObjectObject(object_raw) elif object_raw.type is ObjectRaw.Types.type: return ObjectType(object_...
[ "def", "factory", "(", "cls", ",", "object_raw", ")", ":", "if", "object_raw", "is", "None", ":", "return", "None", "if", "object_raw", ".", "type", "is", "ObjectRaw", ".", "Types", ".", "object", ":", "return", "ObjectObject", "(", "object_raw", ")", "e...
39.578947
8.631579
def log(prefix = ''): '''Add start and stop logging messages to the function. Parameters ---------- :``prefix``: a prefix for the function name (optional) ''' function = None if inspect.isfunction(prefix): prefix, function = '', prefix def _(function): @functools.wr...
[ "def", "log", "(", "prefix", "=", "''", ")", ":", "function", "=", "None", "if", "inspect", ".", "isfunction", "(", "prefix", ")", ":", "prefix", ",", "function", "=", "''", ",", "prefix", "def", "_", "(", "function", ")", ":", "@", "functools", "....
30.56
28.44
def __get_securities(self, currency: str, agent: str, symbol: str, namespace: str) -> List[dal.Security]: """ Fetches the securities that match the given filters """ repo = self.get_security_repository() query = repo.query if currency is not None: qu...
[ "def", "__get_securities", "(", "self", ",", "currency", ":", "str", ",", "agent", ":", "str", ",", "symbol", ":", "str", ",", "namespace", ":", "str", ")", "->", "List", "[", "dal", ".", "Security", "]", ":", "repo", "=", "self", ".", "get_security_...
34.869565
22.913043
def lvresize(size=None, lvpath=None, extents=None): ''' Return information about the logical volume(s) CLI Examples: .. code-block:: bash salt '*' lvm.lvresize +12M /dev/mapper/vg1-test salt '*' lvm.lvresize lvpath=/dev/mapper/vg1-test extents=+100%FREE ''' if size and exten...
[ "def", "lvresize", "(", "size", "=", "None", ",", "lvpath", "=", "None", ",", "extents", "=", "None", ")", ":", "if", "size", "and", "extents", ":", "log", ".", "error", "(", "'Error: Please specify only one of size or extents'", ")", "return", "{", "}", "...
26.166667
26.5
def round_point_coords(pt, precision): """ Round the coordinates of a shapely Point to some decimal precision. Parameters ---------- pt : shapely Point the Point to round the coordinates of precision : int decimal precision to round coordinates to Returns ------- Po...
[ "def", "round_point_coords", "(", "pt", ",", "precision", ")", ":", "return", "Point", "(", "[", "round", "(", "x", ",", "precision", ")", "for", "x", "in", "pt", ".", "coords", "[", "0", "]", "]", ")" ]
22.470588
21.411765
def extend_substation_voltage(crit_stations, grid_level='LV'): """ Extend substation if voltage issues at the substation occur Follows a two-step procedure: i) Existing transformers are extended by replacement with large nominal apparent power ii) New additional transformers adde...
[ "def", "extend_substation_voltage", "(", "crit_stations", ",", "grid_level", "=", "'LV'", ")", ":", "grid", "=", "crit_stations", "[", "0", "]", "[", "'node'", "]", ".", "grid", "trafo_params", "=", "grid", ".", "network", ".", "_static_data", "[", "'{grid_l...
38.379747
22
def n_sections(neurites, neurite_type=NeuriteType.all, iterator_type=Tree.ipreorder): '''Number of sections in a collection of neurites''' return sum(1 for _ in iter_sections(neurites, iterator_type=iterator_type, neurite_filter=is_...
[ "def", "n_sections", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ",", "iterator_type", "=", "Tree", ".", "ipreorder", ")", ":", "return", "sum", "(", "1", "for", "_", "in", "iter_sections", "(", "neurites", ",", "iterator_type", "...
67.2
27.2
async def prover_create_master_secret(wallet_handle: int, master_secret_name: Optional[str]) -> str: """ Creates a master secret with a given name and stores it in the wallet. The name must be unique. :param wallet_handle: wallet handler (created by open_wallet). ...
[ "async", "def", "prover_create_master_secret", "(", "wallet_handle", ":", "int", ",", "master_secret_name", ":", "Optional", "[", "str", "]", ")", "->", "str", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "debug", "("...
45.612903
26.580645
def xmlrpc_method(**kwargs): """ Support multiple endpoints serving the same views by chaining calls to xmlrpc_method """ # Add some default arguments kwargs.update( require_csrf=False, require_methods=["POST"], decorator=(submit_xmlrpc_metrics(method=kwargs["method"]),),...
[ "def", "xmlrpc_method", "(", "*", "*", "kwargs", ")", ":", "# Add some default arguments", "kwargs", ".", "update", "(", "require_csrf", "=", "False", ",", "require_methods", "=", "[", "\"POST\"", "]", ",", "decorator", "=", "(", "submit_xmlrpc_metrics", "(", ...
30.7
18.2
def filtered_data(self, pin): """Return filtered data register value for the provided pin (0-11). Useful for debugging. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' return self._i2c_retry(self._device.readU16LE, MPR121_FILTDATA_0L + pin*2)
[ "def", "filtered_data", "(", "self", ",", "pin", ")", ":", "assert", "pin", ">=", "0", "and", "pin", "<", "12", ",", "'pin must be between 0-11 (inclusive)'", "return", "self", ".", "_i2c_retry", "(", "self", ".", "_device", ".", "readU16LE", ",", "MPR121_FI...
50.333333
16.666667
def coroutine(func): """ Decorator for priming co-routines that use (yield) """ def wrapper(*args, **kwargs): c = func(*args, **kwargs) c.next() # prime it for iteration return c return wrapper
[ "def", "coroutine", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "c", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "c", ".", "next", "(", ")", "# prime it for iteration", "return", ...
31.857143
11.571429
def record(self, i=0): """Returns a specific dbf record based on the supplied index.""" f = self.__getFileObj(self.dbf) if self.numRecords is None: self.__dbfHeader() i = self.__restrictIndex(i) recSize = self.__recStruct.size f.seek(0) f.seek(...
[ "def", "record", "(", "self", ",", "i", "=", "0", ")", ":", "f", "=", "self", ".", "__getFileObj", "(", "self", ".", "dbf", ")", "if", "self", ".", "numRecords", "is", "None", ":", "self", ".", "__dbfHeader", "(", ")", "i", "=", "self", ".", "_...
38.4
7.3
def IsDirty(self, proto): """Return and clear the dirty state of the python object.""" if proto.dirty: return True for python_format, _, type_descriptor in itervalues(proto.GetRawData()): if python_format is not None and type_descriptor.IsDirty(python_format): proto.dirty = True ...
[ "def", "IsDirty", "(", "self", ",", "proto", ")", ":", "if", "proto", ".", "dirty", ":", "return", "True", "for", "python_format", ",", "_", ",", "type_descriptor", "in", "itervalues", "(", "proto", ".", "GetRawData", "(", ")", ")", ":", "if", "python_...
30.909091
24.727273
def _regexp(expr, item): ''' REGEXP function for Sqlite ''' reg = re.compile(expr) return reg.search(item) is not None
[ "def", "_regexp", "(", "expr", ",", "item", ")", ":", "reg", "=", "re", ".", "compile", "(", "expr", ")", "return", "reg", ".", "search", "(", "item", ")", "is", "not", "None" ]
26
14
def lower(self): """Lower bound""" if self._reaction in self._view._flipped: return -super(FlipableFluxBounds, self).upper return super(FlipableFluxBounds, self).lower
[ "def", "lower", "(", "self", ")", ":", "if", "self", ".", "_reaction", "in", "self", ".", "_view", ".", "_flipped", ":", "return", "-", "super", "(", "FlipableFluxBounds", ",", "self", ")", ".", "upper", "return", "super", "(", "FlipableFluxBounds", ",",...
39.8
12.4
def _options_method_response_for_cors(self, allowed_origins, allowed_headers=None, allowed_methods=None, max_age=None, allow_credentials=None): """ Returns a Swagger snippet containing configuration for OPTIONS HTTP Method to configure CORS. This snippe...
[ "def", "_options_method_response_for_cors", "(", "self", ",", "allowed_origins", ",", "allowed_headers", "=", "None", ",", "allowed_methods", "=", "None", ",", "max_age", "=", "None", ",", "allow_credentials", "=", "None", ")", ":", "ALLOW_ORIGIN", "=", "\"Access-...
47.204545
26.568182
def uf(sigla): """ Valida a sigla da Unidade Federativa. Se não for uma sigla de UF válida, será lançada a exceção :exc:`UnidadeFederativaError`. """ if not sigla in [s for s, i, n, r in UNIDADES_FEDERACAO]: raise UnidadeFederativaError('Estado (sigla) UF "%s" ' 'inexistente'...
[ "def", "uf", "(", "sigla", ")", ":", "if", "not", "sigla", "in", "[", "s", "for", "s", ",", "i", ",", "n", ",", "r", "in", "UNIDADES_FEDERACAO", "]", ":", "raise", "UnidadeFederativaError", "(", "'Estado (sigla) UF \"%s\" '", "'inexistente'", "%", "sigla",...
40.25
15.5
def write_tree_to_json_tree(destpath, json_tree): """ Save contents of `json_tree` (dict) to json file at `destpath`. """ parent_dir, _ = os.path.split(destpath) if not os.path.exists(parent_dir): os.makedirs(parent_dir, exist_ok=True) with open(destpath, 'w', encoding='utf8') as json_fi...
[ "def", "write_tree_to_json_tree", "(", "destpath", ",", "json_tree", ")", ":", "parent_dir", ",", "_", "=", "os", ".", "path", ".", "split", "(", "destpath", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "parent_dir", ")", ":", "os", ".", ...
42.777778
10.555556
def find_argname(self, argname, rec=False): """Get the index and :class:`AssignName` node for given name. :param argname: The name of the argument to search for. :type argname: str :param rec: Whether or not to include arguments in unpacked tuples in the search. :ty...
[ "def", "find_argname", "(", "self", ",", "argname", ",", "rec", "=", "False", ")", ":", "if", "self", ".", "args", ":", "# self.args may be None in some cases (builtin function)", "return", "_find_arg", "(", "argname", ",", "self", ".", "args", ",", "rec", ")"...
37.5
20
def exists(provider, config_location=DEFAULT_CONFIG_DIR): """Check whether provider info is already stored """ config_dir = os.path.join(config_location, NOIPY_CONFIG) auth_file = os.path.join(config_dir, provider) return os.path.exists(auth_file)
[ "def", "exists", "(", "provider", ",", "config_location", "=", "DEFAULT_CONFIG_DIR", ")", ":", "config_dir", "=", "os", ".", "path", ".", "join", "(", "config_location", ",", "NOIPY_CONFIG", ")", "auth_file", "=", "os", ".", "path", ".", "join", "(", "conf...
43.166667
15.166667
def tempfile(cls, suffix='', prefix=None, dir=None, text=False): """Returns a new temporary file. The return value is a pair (fd, path) where fd is the file descriptor returned by :func:`os.open`, and path is a :class:`~rpaths.Path` to it. :param suffix: If specified, the file name wil...
[ "def", "tempfile", "(", "cls", ",", "suffix", "=", "''", ",", "prefix", "=", "None", ",", "dir", "=", "None", ",", "text", "=", "False", ")", ":", "if", "prefix", "is", "None", ":", "prefix", "=", "tempfile", ".", "template", "if", "dir", "is", "...
45.735294
25.235294
def get_item_creator(item_type): """Get item creator according registered item type. :param item_type: The type of item to be checed. :type item_type: types.TypeType. :returns: Creator function. None if type not found. """ if item_type not in Pipe.pipe_item_types: for registered_type in...
[ "def", "get_item_creator", "(", "item_type", ")", ":", "if", "item_type", "not", "in", "Pipe", ".", "pipe_item_types", ":", "for", "registered_type", "in", "Pipe", ".", "pipe_item_types", ":", "if", "issubclass", "(", "item_type", ",", "registered_type", ")", ...
37.285714
13.428571
def vector_unit_nullnull(v): """Return unit vectors. Any null vectors remain null vectors. Parameters ---------- v: array, shape (a1, a2, ..., d) Cartesian vectors, with last axis indexing the dimension. Returns ------- v_new: array, shape of v """ if v.size == 0: ...
[ "def", "vector_unit_nullnull", "(", "v", ")", ":", "if", "v", ".", "size", "==", "0", ":", "return", "v", "mag", "=", "vector_mag", "(", "v", ")", "v_new", "=", "v", ".", "copy", "(", ")", "v_new", "[", "mag", ">", "0.0", "]", "/=", "mag", "[",...
22.684211
19.210526
def _handle_recipient(self, typ, recipient): """\ """ route, name, precedence, mcn = recipient.route, recipient.name, recipient.precedence, recipient.mcn if not name: return h = self._handler h.startAssociation(typ) h.role(psis.CABLE_TYPE, self._cable...
[ "def", "_handle_recipient", "(", "self", ",", "typ", ",", "recipient", ")", ":", "route", ",", "name", ",", "precedence", ",", "mcn", "=", "recipient", ".", "route", ",", "recipient", ".", "name", ",", "recipient", ".", "precedence", ",", "recipient", "....
35.833333
19.666667
def set(self, **kwargs): """Sets an internal setting for acquistion, using keywords. Available parameters to set: :param acqtime: duration of recording (input) window (seconds) :type acqtime: float :param aifs: sample rate of the recording (input) operation (Hz) ...
[ "def", "set", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "player_lock", ".", "acquire", "(", ")", "if", "'acqtime'", "in", "kwargs", ":", "self", ".", "player", ".", "set_aidur", "(", "kwargs", "[", "'acqtime'", "]", ")", "if", "'...
42.847222
15.791667
def confd_state_loaded_data_models_data_model_namespace(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") loaded_data_models = ET.SubElement(confd_state, "l...
[ "def", "confd_state_loaded_data_models_data_model_namespace", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "confd_state", "=", "ET", ".", "SubElement", "(", "config", ",", "\"confd-state\"", ",", ...
49.285714
19.5
def CheckHeaderFileIncluded(filename, include_state, error): """Logs an error if a source file does not include its header.""" # Do not check test files fileinfo = FileInfo(filename) if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()): return for ext in GetHeaderExtensions(): basefilename = filename...
[ "def", "CheckHeaderFileIncluded", "(", "filename", ",", "include_state", ",", "error", ")", ":", "# Do not check test files", "fileinfo", "=", "FileInfo", "(", "filename", ")", "if", "Search", "(", "_TEST_FILE_SUFFIX", ",", "fileinfo", ".", "BaseName", "(", ")", ...
38.28
18.32
def term(name): ''' Send a TERM to service via daemontools CLI Example: .. code-block:: bash salt '*' daemontools.term <service name> ''' cmd = 'svc -t {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd, python_shell=False)
[ "def", "term", "(", "name", ")", ":", "cmd", "=", "'svc -t {0}'", ".", "format", "(", "_service_path", "(", "name", ")", ")", "return", "not", "__salt__", "[", "'cmd.retcode'", "]", "(", "cmd", ",", "python_shell", "=", "False", ")" ]
22.666667
24.5
def get_all(self): '''Return an iterator of name-value pairs.''' for name, values in self._map.items(): for value in values: yield (name, value)
[ "def", "get_all", "(", "self", ")", ":", "for", "name", ",", "values", "in", "self", ".", "_map", ".", "items", "(", ")", ":", "for", "value", "in", "values", ":", "yield", "(", "name", ",", "value", ")" ]
36.8
10.8
def overall_MCC_calc(classes, table, TOP, P): """ Calculate Overall_MCC. :param classes: classes :type classes : list :param table: input matrix :type table : dict :param TOP: test outcome positive :type TOP : dict :param P: condition positive :type P : dict :return: Overal...
[ "def", "overall_MCC_calc", "(", "classes", ",", "table", ",", "TOP", ",", "P", ")", ":", "try", ":", "cov_x_y", "=", "0", "cov_x_x", "=", "0", "cov_y_y", "=", "0", "matrix_sum", "=", "sum", "(", "list", "(", "TOP", ".", "values", "(", ")", ")", "...
27.961538
14.961538
def list_(): ''' List the profiles available CLI Example: .. code-block:: bash salt '*' tuned.list ''' result = __salt__['cmd.run']('tuned-adm list').splitlines() # Remove "Available profiles:" result.pop(0) # Remove "Current active profile:.*" result.pop() # Outp...
[ "def", "list_", "(", ")", ":", "result", "=", "__salt__", "[", "'cmd.run'", "]", "(", "'tuned-adm list'", ")", ".", "splitlines", "(", ")", "# Remove \"Available profiles:\"", "result", ".", "pop", "(", "0", ")", "# Remove \"Current active profile:.*\"", "result",...
23.5
22.9
def build_list(self): """Return a list of tuples taken from self.args.stdout [(plugin, attribute), ... ]""" ret = [] for p in self.args.stdout.split(','): if '.' in p: p, a = p.split('.') else: a = None ret.append((p, a)...
[ "def", "build_list", "(", "self", ")", ":", "ret", "=", "[", "]", "for", "p", "in", "self", ".", "args", ".", "stdout", ".", "split", "(", "','", ")", ":", "if", "'.'", "in", "p", ":", "p", ",", "a", "=", "p", ".", "split", "(", "'.'", ")",...
30
12.727273
def byvalue(proxy): '''Return a copy of the underlying object for which the argument is a proxy.''' assert isinstance(proxy, Proxy) return proxy.client.execute(ByValueDelegate(proxy))
[ "def", "byvalue", "(", "proxy", ")", ":", "assert", "isinstance", "(", "proxy", ",", "Proxy", ")", "return", "proxy", ".", "client", ".", "execute", "(", "ByValueDelegate", "(", "proxy", ")", ")" ]
39
18.2
def is_identity_matrix(mat, ignore_phase=False, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT): """Test if an array is an identity matrix.""" if atol is None: atol = ATOL_DEFAULT if rtol is None: rtol = RTOL_DEFAULT mat = np.arr...
[ "def", "is_identity_matrix", "(", "mat", ",", "ignore_phase", "=", "False", ",", "rtol", "=", "RTOL_DEFAULT", ",", "atol", "=", "ATOL_DEFAULT", ")", ":", "if", "atol", "is", "None", ":", "atol", "=", "ATOL_DEFAULT", "if", "rtol", "is", "None", ":", "rtol...
35.904762
13
def get_netconf_client_capabilities_output_session_af_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_netconf_client_capabilities = ET.Element("get_netconf_client_capabilities") config = get_netconf_client_capabilities output = ET.SubEle...
[ "def", "get_netconf_client_capabilities_output_session_af_type", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_netconf_client_capabilities", "=", "ET", ".", "Element", "(", "\"get_netconf_client_capab...
45.692308
16.692308
def print_ast(f): """ :param f: :type f: file :return: """ for linenum,indent,value in iter_lines(f): print("{0}{1}|{2}".format(str(linenum).rjust(3), ' ' * indent, value))
[ "def", "print_ast", "(", "f", ")", ":", "for", "linenum", ",", "indent", ",", "value", "in", "iter_lines", "(", "f", ")", ":", "print", "(", "\"{0}{1}|{2}\"", ".", "format", "(", "str", "(", "linenum", ")", ".", "rjust", "(", "3", ")", ",", "' '", ...
24.625
18.125
def _fuzzy_custom_query(issn, titles): """ Este metodo constroi a lista de filtros por título de periódico que será aplicada na pesquisa boleana como match por similaridade "should". A lista de filtros é coletada do template de pesquisa customizada do periódico, q...
[ "def", "_fuzzy_custom_query", "(", "issn", ",", "titles", ")", ":", "custom_queries", "=", "journal_titles", ".", "load", "(", "issn", ")", ".", "get", "(", "'should'", ",", "[", "]", ")", "titles", "=", "[", "{", "'title'", ":", "i", "}", "for", "i"...
36.962963
22.296296
def intervals_containing(t, p): """Query the interval tree :param t: root of the interval tree :param p: value :returns: a list of intervals containing p :complexity: O(log n + m), where n is the number of intervals in t, and m the length of the returned list """ INF = float...
[ "def", "intervals_containing", "(", "t", ",", "p", ")", ":", "INF", "=", "float", "(", "'inf'", ")", "if", "t", "is", "None", ":", "return", "[", "]", "if", "p", "<", "t", ".", "center", ":", "retval", "=", "intervals_containing", "(", "t", ".", ...
32.565217
13.826087