text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def pad_to_size(text, x, y): """ Adds whitespace to text to center it within a frame of the given dimensions. """ input_lines = text.rstrip().split("\n") longest_input_line = max(map(len, input_lines)) number_of_input_lines = len(input_lines) x = max(x, longest_input_line) y = max(y,...
[ "def", "pad_to_size", "(", "text", ",", "x", ",", "y", ")", ":", "input_lines", "=", "text", ".", "rstrip", "(", ")", ".", "split", "(", "\"\\n\"", ")", "longest_input_line", "=", "max", "(", "map", "(", "len", ",", "input_lines", ")", ")", "number_o...
33.636364
17.181818
def fsdecode(path, os_name=os.name, fs_encoding=FS_ENCODING, errors=None): ''' Decode given path. :param path: path will be decoded if using bytes :type path: bytes or str :param os_name: operative system name, defaults to os.name :type os_name: str :param fs_encoding: current filesystem en...
[ "def", "fsdecode", "(", "path", ",", "os_name", "=", "os", ".", "name", ",", "fs_encoding", "=", "FS_ENCODING", ",", "errors", "=", "None", ")", ":", "if", "not", "isinstance", "(", "path", ",", "bytes", ")", ":", "return", "path", "if", "not", "erro...
34.210526
21.157895
def extract_rows(self, result={}, selector='', table_headers=[], attr='', connector='', default='', verbosity=0, *args, **kwargs): """ Row data extraction for extract_tabular """ result_list = [] try: values = self.get_tree_tag(selector) if len(table_headers) >= len(values): from itertools import i...
[ "def", "extract_rows", "(", "self", ",", "result", "=", "{", "}", ",", "selector", "=", "''", ",", "table_headers", "=", "[", "]", ",", "attr", "=", "''", ",", "connector", "=", "''", ",", "default", "=", "''", ",", "verbosity", "=", "0", ",", "*...
33.542857
20
def _py_pattern_from_bracket_expression(bracket_expression, path_name): u""" This does not handle exclusion of separators in the bracket expression when pathname is True :param bracket_expression: :return: """ single_chars = set() multi_chars = set() ranges = set() matching, items = ...
[ "def", "_py_pattern_from_bracket_expression", "(", "bracket_expression", ",", "path_name", ")", ":", "single_chars", "=", "set", "(", ")", "multi_chars", "=", "set", "(", ")", "ranges", "=", "set", "(", ")", "matching", ",", "items", "=", "_read_bracket_expressi...
45.056604
21.424528
def calculate_linear_attenuation_coefficient(atoms_per_cm3: np.float, sigma_b: np.array): """calculate the transmission signal using the formula transmission = exp( - thickness_cm * atoms_per_cm3 * 1e-24 * sigma_b) Parameters: =========== thickness: float (in cm) atoms_per_cm3: float (number o...
[ "def", "calculate_linear_attenuation_coefficient", "(", "atoms_per_cm3", ":", "np", ".", "float", ",", "sigma_b", ":", "np", ".", "array", ")", ":", "miu_per_cm", "=", "1e-24", "*", "sigma_b", "*", "atoms_per_cm3", "return", "np", ".", "array", "(", "miu_per_c...
31.352941
23.411765
def buy_market_order(self, amount, base="btc", quote="usd"): """ Order to buy amount of bitcoins for market price. """ data = {'amount': amount} url = self._construct_url("buy/market/", base, quote) return self._post(url, data=data, return_json=True, version=2)
[ "def", "buy_market_order", "(", "self", ",", "amount", ",", "base", "=", "\"btc\"", ",", "quote", "=", "\"usd\"", ")", ":", "data", "=", "{", "'amount'", ":", "amount", "}", "url", "=", "self", ".", "_construct_url", "(", "\"buy/market/\"", ",", "base", ...
43.285714
13.571429
def _paramsShared(self, exclude=None, prefix="") -> MakeParamsShared: """ Auto-propagate params by name to child components and interfaces Usage: .. code-block:: python with self._paramsShared(): # your interfaces and unit which should share all params with ...
[ "def", "_paramsShared", "(", "self", ",", "exclude", "=", "None", ",", "prefix", "=", "\"\"", ")", "->", "MakeParamsShared", ":", "return", "MakeParamsShared", "(", "self", ",", "exclude", "=", "exclude", ",", "prefix", "=", "prefix", ")" ]
38.8
23.733333
def horizontal_border(self, style, outer_widths): """Build any kind of horizontal border for the table. :param str style: Type of border to return. :param iter outer_widths: List of widths (with padding) for each column. :return: Prepared border as a tuple of strings. :rtype: t...
[ "def", "horizontal_border", "(", "self", ",", "style", ",", "outer_widths", ")", ":", "if", "style", "==", "'top'", ":", "horizontal", "=", "self", ".", "CHAR_OUTER_TOP_HORIZONTAL", "left", "=", "self", ".", "CHAR_OUTER_TOP_LEFT", "intersect", "=", "self", "."...
51.15
23.3
def get_errno(exc): """:exc:`socket.error` and :exc:`IOError` first got the ``.errno`` attribute in Py2.7""" try: return exc.errno except AttributeError: try: # e.args = (errno, reason) if isinstance(exc.args, tuple) and len(exc.args) == 2: return ...
[ "def", "get_errno", "(", "exc", ")", ":", "try", ":", "return", "exc", ".", "errno", "except", "AttributeError", ":", "try", ":", "# e.args = (errno, reason)", "if", "isinstance", "(", "exc", ".", "args", ",", "tuple", ")", "and", "len", "(", "exc", ".",...
29.230769
15.923077
def receive(self): """ receive the next PDU from the watchman service If the client has activated subscriptions or logs then this PDU may be a unilateral PDU sent by the service to inform the client of a log event or subscription change. It may also simply be the response porti...
[ "def", "receive", "(", "self", ")", ":", "self", ".", "_connect", "(", ")", "result", "=", "self", ".", "recvConn", ".", "receive", "(", ")", "if", "self", ".", "_hasprop", "(", "result", ",", "\"error\"", ")", ":", "raise", "CommandError", "(", "res...
36.026316
17.263158
def property_on_depth_profile(lat, lon, depths, quantity_ID="DENSITY"): """ Lat / Lon are in degrees Depth in km quantity_ID needs to match those in the litho1 model Points that are not found are given the out-of-range value of -99999 """ lon1 = np.array((lon,)) lat1 = np.array((lat,)...
[ "def", "property_on_depth_profile", "(", "lat", ",", "lon", ",", "depths", ",", "quantity_ID", "=", "\"DENSITY\"", ")", ":", "lon1", "=", "np", ".", "array", "(", "(", "lon", ",", ")", ")", "lat1", "=", "np", ".", "array", "(", "(", "lat", ",", ")"...
32.641026
26.487179
def query_builds_by_revision(self, revision, job_type_name='Build', debug_build=False): """Retrieve build folders for a given revision with the help of Treeherder. :param revision: Revision of the build to download. :param job_type_name: Name of the job to look for. For builds it should be ...
[ "def", "query_builds_by_revision", "(", "self", ",", "revision", ",", "job_type_name", "=", "'Build'", ",", "debug_build", "=", "False", ")", ":", "builds", "=", "set", "(", ")", "try", ":", "self", ".", "logger", ".", "info", "(", "'Querying {url} for list ...
45.125
25.5
def haydavies(surface_tilt, surface_azimuth, dhi, dni, dni_extra, solar_zenith=None, solar_azimuth=None, projection_ratio=None): r''' Determine diffuse irradiance from the sky on a tilted surface using Hay & Davies' 1980 model .. math:: I_{d} = DHI ( A R_b + (1 - A) (\frac{1 + \co...
[ "def", "haydavies", "(", "surface_tilt", ",", "surface_azimuth", ",", "dhi", ",", "dni", ",", "dni_extra", ",", "solar_zenith", "=", "None", ",", "solar_azimuth", "=", "None", ",", "projection_ratio", "=", "None", ")", ":", "# if necessary, calculate ratio of titl...
36.255556
24.144444
def _on_expose_event(self, widget, event): ''' .. versionchanged:: 0.20 Renamed from ``on_widget__expose_event`` to allow wrapping for debouncing to improve responsiveness. Called when drawing area is first displayed and, for example, when part of drawing area is...
[ "def", "_on_expose_event", "(", "self", ",", "widget", ",", "event", ")", ":", "logger", ".", "info", "(", "'on_widget__expose_event'", ")", "# Request immediate paint of pre-rendered off-screen Cairo surface to", "# drawing area widget, but also mark as dirty to redraw after next"...
38.888889
25.444444
def nmf_ensemble(data, k, n_runs=10, W_list=[], **nmf_params): """ Runs an ensemble method on the list of NMF W matrices... Args: data: genes x cells array (should be log + cell-normalized) k: number of classes n_runs (optional): number of random initializations of state estimation ...
[ "def", "nmf_ensemble", "(", "data", ",", "k", ",", "n_runs", "=", "10", ",", "W_list", "=", "[", "]", ",", "*", "*", "nmf_params", ")", ":", "nmf", "=", "NMF", "(", "k", ")", "if", "len", "(", "W_list", ")", "==", "0", ":", "W_list", "=", "["...
33.096774
18.774194
def parse_header(self, parsed_samples=None): """Read and parse :py:class:`vcfpy.header.Header` from file, set into ``self.header`` and return it :param list parsed_samples: ``list`` of ``str`` for subsetting the samples to parse :returns: ``vcfpy.header.Header`` :rai...
[ "def", "parse_header", "(", "self", ",", "parsed_samples", "=", "None", ")", ":", "# parse header lines", "sub_parser", "=", "HeaderParser", "(", ")", "header_lines", "=", "[", "]", "while", "self", ".", "_line", "and", "self", ".", "_line", ".", "startswith...
43.580645
14.193548
def _build_query(self, query_string, no_params=False): """ Set request parameters. Will always add the user ID if it hasn't been specifically set by an API method """ try: query = quote(query_string.format(u=self.library_id, t=self.library_type)) except KeyErr...
[ "def", "_build_query", "(", "self", ",", "query_string", ",", "no_params", "=", "False", ")", ":", "try", ":", "query", "=", "quote", "(", "query_string", ".", "format", "(", "u", "=", "self", ".", "library_id", ",", "t", "=", "self", ".", "library_typ...
43.066667
16.933333
def dephasing_kraus_map(p=0.10): """ Generate the Kraus operators corresponding to a dephasing channel. :params float p: The one-step dephasing probability. :return: A list [k1, k2] of the Kraus operators that parametrize the map. :rtype: list """ return [np.sqrt(1 - p) * np.eye(2), np.sqrt...
[ "def", "dephasing_kraus_map", "(", "p", "=", "0.10", ")", ":", "return", "[", "np", ".", "sqrt", "(", "1", "-", "p", ")", "*", "np", ".", "eye", "(", "2", ")", ",", "np", ".", "sqrt", "(", "p", ")", "*", "np", ".", "diag", "(", "[", "1", ...
37.222222
20.555556
def get_go2nt(self, usr_go2nt): """Combine user namedtuple fields, GO object fields, and format_txt.""" gos_all = self.get_gos_all() # Minimum set of namedtuple fields available for use with Sorter on grouped GO IDs prt_flds_all = get_hdridx_flds() + self.gosubdag.prt_attr['flds'] ...
[ "def", "get_go2nt", "(", "self", ",", "usr_go2nt", ")", ":", "gos_all", "=", "self", ".", "get_gos_all", "(", ")", "# Minimum set of namedtuple fields available for use with Sorter on grouped GO IDs", "prt_flds_all", "=", "get_hdridx_flds", "(", ")", "+", "self", ".", ...
61.384615
22.692308
def authenticate_http_request(token=None): """Validate auth0 tokens passed in the request's header, hence ensuring that the user is authenticated. Code copied from: https://github.com/auth0/auth0-python/tree/master/examples/flask-api Return a PntCommonException if failed to validate authentication. ...
[ "def", "authenticate_http_request", "(", "token", "=", "None", ")", ":", "if", "token", ":", "auth", "=", "token", "else", ":", "auth", "=", "request", ".", "headers", ".", "get", "(", "'Authorization'", ",", "None", ")", "if", "not", "auth", ":", "aut...
32.888889
25.666667
def greenlet(func, args=(), kwargs=None): """create a new greenlet from a function and arguments :param func: the function the new greenlet should run :type func: function :param args: any positional arguments for the function :type args: tuple :param kwargs: any keyword arguments for the funct...
[ "def", "greenlet", "(", "func", ",", "args", "=", "(", ")", ",", "kwargs", "=", "None", ")", ":", "if", "args", "or", "kwargs", ":", "def", "target", "(", ")", ":", "return", "func", "(", "*", "args", ",", "*", "*", "(", "kwargs", "or", "{", ...
37.714286
18.619048
def write_title(self, title, level=1, id=None): """Writes a title header in the document body, with an optional depth level """ if id: self.write('<h{lv} id="{id}">{title}</h{lv}>', title=title, lv=level, id=id) else: self.write('...
[ "def", "write_title", "(", "self", ",", "title", ",", "level", "=", "1", ",", "id", "=", "None", ")", ":", "if", "id", ":", "self", ".", "write", "(", "'<h{lv} id=\"{id}\">{title}</h{lv}>'", ",", "title", "=", "title", ",", "lv", "=", "level", ",", "...
38.1
10.4
def chunks(raw): """Yield successive EVENT_SIZE sized chunks from raw.""" for i in range(0, len(raw), EVENT_SIZE): yield struct.unpack(EVENT_FORMAT, raw[i:i+EVENT_SIZE])
[ "def", "chunks", "(", "raw", ")", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "raw", ")", ",", "EVENT_SIZE", ")", ":", "yield", "struct", ".", "unpack", "(", "EVENT_FORMAT", ",", "raw", "[", "i", ":", "i", "+", "EVENT_SIZE", "]", ...
45.5
12.5
def loss(params, batch, model_predict, rng): """Calculate loss.""" inputs, targets = batch predictions = model_predict(inputs, params, rng=rng) predictions, targets = _make_list(predictions, targets) xent = [] for (pred, target) in zip(predictions, targets): xent.append(np.sum(pred * layers.one_hot(targ...
[ "def", "loss", "(", "params", ",", "batch", ",", "model_predict", ",", "rng", ")", ":", "inputs", ",", "targets", "=", "batch", "predictions", "=", "model_predict", "(", "inputs", ",", "params", ",", "rng", "=", "rng", ")", "predictions", ",", "targets",...
42.222222
14.555556
def merge_dicts(dict_a, dict_b): """Recursively merge dictionary b into dictionary a. If override_nones is True, then """ def _merge_dicts_(a, b): for key in set(a.keys()).union(b.keys()): if key in a and key in b: if isinstance(a[key], dict) and isinstance(b[key], d...
[ "def", "merge_dicts", "(", "dict_a", ",", "dict_b", ")", ":", "def", "_merge_dicts_", "(", "a", ",", "b", ")", ":", "for", "key", "in", "set", "(", "a", ".", "keys", "(", ")", ")", ".", "union", "(", "b", ".", "keys", "(", ")", ")", ":", "if"...
36.947368
10.157895
def generate_enum(self): """ Means that only value specified in the enum is valid. .. code-block:: python { 'enum': ['a', 'b'], } """ enum = self._definition['enum'] if not isinstance(enum, (list, tuple)): raise JsonSc...
[ "def", "generate_enum", "(", "self", ")", ":", "enum", "=", "self", ".", "_definition", "[", "'enum'", "]", "if", "not", "isinstance", "(", "enum", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "JsonSchemaDefinitionException", "(", "'enum must be...
33.5625
17.9375
def write_antenna(page, args, seg_plot=None, grid=False, ipn=False): """ Write antenna factors to merkup.page object page and generate John's detector response plot. """ from pylal import antenna page.h3() page.add('Antenna factors and sky locations') page.h3.close() th = [] t...
[ "def", "write_antenna", "(", "page", ",", "args", ",", "seg_plot", "=", "None", ",", "grid", "=", "False", ",", "ipn", "=", "False", ")", ":", "from", "pylal", "import", "antenna", "page", ".", "h3", "(", ")", "page", ".", "add", "(", "'Antenna facto...
30.604839
18.685484
def document(self, document): """ Associate a :class:`~elasticsearch_dsl.Document` subclass with an index. This means that, when this index is created, it will contain the mappings for the ``Document``. If the ``Document`` class doesn't have a default index yet (by defining ``cla...
[ "def", "document", "(", "self", ",", "document", ")", ":", "self", ".", "_doc_types", ".", "append", "(", "document", ")", "# If the document index does not have any name, that means the user", "# did not set any index already to the document.", "# So set this index as document i...
35.2
20.533333
def write(self): """Pull features from the instream and write them to the output.""" for entry in self._instream: if isinstance(entry, Feature): for feature in entry: if feature.num_children > 0 or feature.is_multi: if feature.is_mu...
[ "def", "write", "(", "self", ")", ":", "for", "entry", "in", "self", ".", "_instream", ":", "if", "isinstance", "(", "entry", ",", "Feature", ")", ":", "for", "feature", "in", "entry", ":", "if", "feature", ".", "num_children", ">", "0", "or", "featu...
51.444444
15.055556
def open(self, init_board=True): """! @brief Open the session. This method does everything necessary to begin a debug session. It first loads the user script, if there is one. The user script will be available via the _user_script_proxy_ property. Then it opens the debug probe a...
[ "def", "open", "(", "self", ",", "init_board", "=", "True", ")", ":", "if", "not", "self", ".", "_inited", ":", "assert", "self", ".", "_probe", "is", "not", "None", ",", "\"Cannot open a session without a probe.\"", "assert", "self", ".", "_board", "is", ...
48.185185
26.62963
def substructure(mol, query, largest_only=True, ignore_hydrogen=True): """ if mol is a substructure of the query, return True Args: mol: Compound query: Compound largest_only: compare only largest graph molecule """ def subset_filter(cnt1, cnt2): diff = cnt2 diff.subtra...
[ "def", "substructure", "(", "mol", ",", "query", ",", "largest_only", "=", "True", ",", "ignore_hydrogen", "=", "True", ")", ":", "def", "subset_filter", "(", "cnt1", ",", "cnt2", ")", ":", "diff", "=", "cnt2", "diff", ".", "subtract", "(", "cnt1", ")"...
33.148148
13.703704
def mark_all_read(user): """ Mark all message instances for a user as read. :param user: user instance for the recipient """ BackendClass = stored_messages_settings.STORAGE_BACKEND backend = BackendClass() backend.inbox_purge(user)
[ "def", "mark_all_read", "(", "user", ")", ":", "BackendClass", "=", "stored_messages_settings", ".", "STORAGE_BACKEND", "backend", "=", "BackendClass", "(", ")", "backend", ".", "inbox_purge", "(", "user", ")" ]
28
12.888889
def _read_charge_and_multiplicity(self): """ Parses charge and multiplicity. """ temp_charge = read_pattern( self.text, { "key": r"\$molecule\s+([\-\d]+)\s+\d" }, terminate_on_match=True).get('key') if temp_charge != None: ...
[ "def", "_read_charge_and_multiplicity", "(", "self", ")", ":", "temp_charge", "=", "read_pattern", "(", "self", ".", "text", ",", "{", "\"key\"", ":", "r\"\\$molecule\\s+([\\-\\d]+)\\s+\\d\"", "}", ",", "terminate_on_match", "=", "True", ")", ".", "get", "(", "'...
36.4
13.65
def index_sparse(column_count, indices): """ Return a sparse matrix for which vertices are contained in which faces. Returns --------- sparse: scipy.sparse.coo_matrix of shape (column_count, len(faces)) dtype is boolean Examples ---------- In [1]: sparse = faces_sparse(len...
[ "def", "index_sparse", "(", "column_count", ",", "indices", ")", ":", "indices", "=", "np", ".", "asanyarray", "(", "indices", ")", "column_count", "=", "int", "(", "column_count", ")", "row", "=", "indices", ".", "reshape", "(", "-", "1", ")", "col", ...
35.527273
23.309091
def _parse_schedule(self, schedule): """ Parse a job schedule. """ result = {} for param in shlex.split(str(schedule)): # do not feed unicode to shlex try: key, val = param.split('=', 1) except (TypeError, ValueError): self.fatal("...
[ "def", "_parse_schedule", "(", "self", ",", "schedule", ")", ":", "result", "=", "{", "}", "for", "param", "in", "shlex", ".", "split", "(", "str", "(", "schedule", ")", ")", ":", "# do not feed unicode to shlex", "try", ":", "key", ",", "val", "=", "p...
31.357143
19.357143
def get_messages(self): """ Retrieves the error or status messages associated with the specified profile. Returns: dict: Server Profile Health. """ uri = '{}/messages'.format(self.data["uri"]) return self._helper.do_get(uri)
[ "def", "get_messages", "(", "self", ")", ":", "uri", "=", "'{}/messages'", ".", "format", "(", "self", ".", "data", "[", "\"uri\"", "]", ")", "return", "self", ".", "_helper", ".", "do_get", "(", "uri", ")" ]
30.777778
15.444444
def on_tick_data(self, ticks): """Process the incoming tick data array""" for tick in XmlHelper.node_iter(ticks): names = [str(tick.getElement(_).name()) for _ in range(tick.numElements())] tickmap = {n: XmlHelper.get_child_value(tick, n) for n in names} self.response...
[ "def", "on_tick_data", "(", "self", ",", "ticks", ")", ":", "for", "tick", "in", "XmlHelper", ".", "node_iter", "(", "ticks", ")", ":", "names", "=", "[", "str", "(", "tick", ".", "getElement", "(", "_", ")", ".", "name", "(", ")", ")", "for", "_...
56.166667
17.833333
def translate_exception(exc_info, initial_skip=0): """If passed an exc_info it will automatically rewrite the exceptions all the way down to the correct line numbers and frames. """ tb = exc_info[2] frames = [] # skip some internal frames if wanted for x in xrange(initial_skip): if ...
[ "def", "translate_exception", "(", "exc_info", ",", "initial_skip", "=", "0", ")", ":", "tb", "=", "exc_info", "[", "2", "]", "frames", "=", "[", "]", "# skip some internal frames if wanted", "for", "x", "in", "xrange", "(", "initial_skip", ")", ":", "if", ...
33.866667
19.777778
def save_config(self, cmd="save config", confirm=False, confirm_response=""): """Save Config""" return super(ExtremeErsSSH, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
[ "def", "save_config", "(", "self", ",", "cmd", "=", "\"save config\"", ",", "confirm", "=", "False", ",", "confirm_response", "=", "\"\"", ")", ":", "return", "super", "(", "ExtremeErsSSH", ",", "self", ")", ".", "save_config", "(", "cmd", "=", "cmd", ",...
47.2
22.6
def configure(self, config): """ Initialize the plugin. This creates a data object which holds a BudgetDataPackage parser which operates based on a specification which is either provided in the config via: ``ckan.budgets.specification`` or the included version. """ ...
[ "def", "configure", "(", "self", ",", "config", ")", ":", "specification", "=", "config", ".", "get", "(", "'ckan.budgets.specification'", ",", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'data'", ...
40.711538
15.75
def wait_for_ajax_calls_to_complete(self, timeout=5): """ Waits until there are no active or pending ajax requests. Raises TimeoutException should silence not be had. :param timeout: time to wait for silence (default: 5 seconds) :return: None """ from selenium.w...
[ "def", "wait_for_ajax_calls_to_complete", "(", "self", ",", "timeout", "=", "5", ")", ":", "from", "selenium", ".", "webdriver", ".", "support", ".", "ui", "import", "WebDriverWait", "WebDriverWait", "(", "self", ".", "driver", ",", "timeout", ")", ".", "unt...
38.166667
26.166667
def create_contribution(self, metadata): """Create a new contribution given a dictionary of metadata { "contribution_name": "HelloWorld", "contribution_collection": "Cooee", "contribution_text": "This is contribution description", "con...
[ "def", "create_contribution", "(", "self", ",", "metadata", ")", ":", "result", "=", "self", ".", "api_request", "(", "'/contrib/'", ",", "method", "=", "'POST'", ",", "data", "=", "json", ".", "dumps", "(", "metadata", ")", ")", "# add the contrib id into t...
32.238095
24.047619
def sodium_unpad(s, blocksize): """ Remove ISO/IEC 7816-4 padding from the input byte array ``s`` :param s: input bytes string :type s: bytes :param blocksize: :type blocksize: int :return: unpadded string :rtype: bytes """ ensure(isinstance(s, bytes), raising=exc.Typ...
[ "def", "sodium_unpad", "(", "s", ",", "blocksize", ")", ":", "ensure", "(", "isinstance", "(", "s", ",", "bytes", ")", ",", "raising", "=", "exc", ".", "TypeError", ")", "ensure", "(", "isinstance", "(", "blocksize", ",", "integer_types", ")", ",", "ra...
28.095238
14.095238
def fail(self, msg, lineno=None, exc=TemplateSyntaxError): """Convenience method that raises `exc` with the message, passed line number or last line number as well as the current name and filename. """ if lineno is None: lineno = self.stream.current.lineno rai...
[ "def", "fail", "(", "self", ",", "msg", ",", "lineno", "=", "None", ",", "exc", "=", "TemplateSyntaxError", ")", ":", "if", "lineno", "is", "None", ":", "lineno", "=", "self", ".", "stream", ".", "current", ".", "lineno", "raise", "exc", "(", "msg", ...
44.75
13.625
def get_keeper_token(base_url, username, password): """Get a temporary auth token from LTD Keeper.""" token_endpoint = base_url + '/token' r = requests.get(token_endpoint, auth=(username, password)) if r.status_code != 200: raise RuntimeError('Could not authenticate to {0}: error {1:d}\n{2}'. ...
[ "def", "get_keeper_token", "(", "base_url", ",", "username", ",", "password", ")", ":", "token_endpoint", "=", "base_url", "+", "'/token'", "r", "=", "requests", ".", "get", "(", "token_endpoint", ",", "auth", "=", "(", "username", ",", "password", ")", ")...
51.125
15.5
def _download_and_clean_file(filename, url): """Downloads data from url, and makes changes to match the CSV format.""" temp_file, _ = urllib.request.urlretrieve(url) with tf.gfile.Open(temp_file, 'r') as temp_eval_file: with tf.gfile.Open(filename, 'w') as eval_file: for line in temp_eval_file: ...
[ "def", "_download_and_clean_file", "(", "filename", ",", "url", ")", ":", "temp_file", ",", "_", "=", "urllib", ".", "request", ".", "urlretrieve", "(", "url", ")", "with", "tf", ".", "gfile", ".", "Open", "(", "temp_file", ",", "'r'", ")", "as", "temp...
37.2
10.2
def _distill_params(multiparams, params): """Given arguments from the calling form *multiparams, **params, return a list of bind parameter structures, usually a list of dictionaries. In the case of 'raw' execution which accepts positional parameters, it may be a list of tuples or lists. """ ...
[ "def", "_distill_params", "(", "multiparams", ",", "params", ")", ":", "if", "not", "multiparams", ":", "if", "params", ":", "return", "[", "params", "]", "else", ":", "return", "[", "]", "elif", "len", "(", "multiparams", ")", "==", "1", ":", "zero", ...
32.052632
15.763158
def put(request, obj_id): """Updates the content of a comment :param obj_id: ID of comment object :type obj_id: int :returns: json """ res = Result() c = Comment.objects.get(pk=obj_id) data = request.PUT or json.loads(request.body)['body'] content = data.get('comment', None) if c...
[ "def", "put", "(", "request", ",", "obj_id", ")", ":", "res", "=", "Result", "(", ")", "c", "=", "Comment", ".", "objects", ".", "get", "(", "pk", "=", "obj_id", ")", "data", "=", "request", ".", "PUT", "or", "json", ".", "loads", "(", "request",...
25.470588
14.647059
def _remove(self, client_kwargs): """ Remove an object. args: client_kwargs (dict): Client arguments. """ with _handle_client_error(): # Object if 'Key' in client_kwargs: return self.client.delete_object(**client_kwargs) ...
[ "def", "_remove", "(", "self", ",", "client_kwargs", ")", ":", "with", "_handle_client_error", "(", ")", ":", "# Object", "if", "'Key'", "in", "client_kwargs", ":", "return", "self", ".", "client", ".", "delete_object", "(", "*", "*", "client_kwargs", ")", ...
28.5
17.642857
def build_wheel(platform): """Create a wheel""" if platform in ['x86_64', 'i686']: system = 'manylinux1' else: system = 'linux' setuptools.sandbox.run_setup( 'setup.py', ['-q', 'clean', '--all', 'bdist_wheel', '--plat-name', '{}_{}'.format(system, platform)] )
[ "def", "build_wheel", "(", "platform", ")", ":", "if", "platform", "in", "[", "'x86_64'", ",", "'i686'", "]", ":", "system", "=", "'manylinux1'", "else", ":", "system", "=", "'linux'", "setuptools", ".", "sandbox", ".", "run_setup", "(", "'setup.py'", ",",...
25.25
22.75
def concatenate(input_files, output_file): """ Concatenates the input files into the single output file. In debug mode this function adds a comment with the filename before the contents of each file. """ from .modules import utils, concat if not isinstance(input_files, (list, tuple)): ...
[ "def", "concatenate", "(", "input_files", ",", "output_file", ")", ":", "from", ".", "modules", "import", "utils", ",", "concat", "if", "not", "isinstance", "(", "input_files", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "RuntimeError", "(", ...
30.315789
17.789474
def get_hosting_device_configuration(self, context, id): """Fetch configuration of hosting device with id. The configuration agent should respond with the running config of the hosting device. """ admin_context = context.is_admin and context or context.elevated() agents ...
[ "def", "get_hosting_device_configuration", "(", "self", ",", "context", ",", "id", ")", ":", "admin_context", "=", "context", ".", "is_admin", "and", "context", "or", "context", ".", "elevated", "(", ")", "agents", "=", "self", ".", "_dmplugin", ".", "get_cf...
50.076923
22.538462
def windowed_iterable(self): """ That returns only the window """ # Seek to offset effective_offset = max(0,self.item_view.iterable_index) for i,item in enumerate(self.iterable): if i<effective_offset: continue elif i>=(effective_offset+self.item_v...
[ "def", "windowed_iterable", "(", "self", ")", ":", "# Seek to offset", "effective_offset", "=", "max", "(", "0", ",", "self", ".", "item_view", ".", "iterable_index", ")", "for", "i", ",", "item", "in", "enumerate", "(", "self", ".", "iterable", ")", ":", ...
38.2
15
def fixed_legend_filter_field(self, fixed_legend_filter_field): """Sets the fixed_legend_filter_field of this ChartSettings. Statistic to use for determining whether a series is displayed on the fixed legend # noqa: E501 :param fixed_legend_filter_field: The fixed_legend_filter_field of this ...
[ "def", "fixed_legend_filter_field", "(", "self", ",", "fixed_legend_filter_field", ")", ":", "allowed_values", "=", "[", "\"CURRENT\"", ",", "\"MEAN\"", ",", "\"MEDIAN\"", ",", "\"SUM\"", ",", "\"MIN\"", ",", "\"MAX\"", ",", "\"COUNT\"", "]", "# noqa: E501", "if",...
50.4375
33
def load(filename): """Load a pickled database. Return a Database instance. """ file = open(filename, 'rb') container = std_pickle.load(file) file.close() db = Database(file.name) chains = 0 funs = set() for k, v in six.iteritems(container): if k == '_state_': ...
[ "def", "load", "(", "filename", ")", ":", "file", "=", "open", "(", "filename", ",", "'rb'", ")", "container", "=", "std_pickle", ".", "load", "(", "file", ")", "file", ".", "close", "(", ")", "db", "=", "Database", "(", "file", ".", "name", ")", ...
23.916667
16.083333
def signUserCsr(self, xcsr, signas, outp=None): ''' Signs a user CSR with a CA keypair. Args: cert (OpenSSL.crypto.X509Req): The certificate signing request. signas (str): The CA keypair name to sign the CSR with. outp (synapse.lib.output.Output): The output ...
[ "def", "signUserCsr", "(", "self", ",", "xcsr", ",", "signas", ",", "outp", "=", "None", ")", ":", "pkey", "=", "xcsr", ".", "get_pubkey", "(", ")", "name", "=", "xcsr", ".", "get_subject", "(", ")", ".", "CN", "return", "self", ".", "genUserCert", ...
36.777778
26.111111
def get_comps(cluster, environ, topology, role=None): ''' Get the list of component names for the topology from Heron Nest :param cluster: :param environ: :param topology: :param role: :return: ''' params = dict(cluster=cluster, environ=environ, topology=topology) if role is not None: params['ro...
[ "def", "get_comps", "(", "cluster", ",", "environ", ",", "topology", ",", "role", "=", "None", ")", ":", "params", "=", "dict", "(", "cluster", "=", "cluster", ",", "environ", "=", "environ", ",", "topology", "=", "topology", ")", "if", "role", "is", ...
32.058824
19.588235
def Msg(validator, message): """ Wraps the given validator callable, replacing any error messages raised. """ @wraps(Msg) def built(value): try: return validator(value) except Error as e: e.message = message raise e return built
[ "def", "Msg", "(", "validator", ",", "message", ")", ":", "@", "wraps", "(", "Msg", ")", "def", "built", "(", "value", ")", ":", "try", ":", "return", "validator", "(", "value", ")", "except", "Error", "as", "e", ":", "e", ".", "message", "=", "m...
24.416667
16.083333
def _request_bulk(self, urls: List[str]) -> List: """Batch the requests going out.""" if not urls: raise Exception("No results were found") session: FuturesSession = FuturesSession(max_workers=len(urls)) self.log.info("Bulk requesting: %d" % len(urls)) futures = [sess...
[ "def", "_request_bulk", "(", "self", ",", "urls", ":", "List", "[", "str", "]", ")", "->", "List", ":", "if", "not", "urls", ":", "raise", "Exception", "(", "\"No results were found\"", ")", "session", ":", "FuturesSession", "=", "FuturesSession", "(", "ma...
43.4
14.8
def _assign_curtailment(curtailment, edisgo, generators, curtailment_key): """ Helper function to write curtailment time series to generator objects. This function also writes a list of the curtailed generators to curtailment in :class:`edisgo.grid.network.TimeSeries` and :class:`edisgo.grid.networ...
[ "def", "_assign_curtailment", "(", "curtailment", ",", "edisgo", ",", "generators", ",", "curtailment_key", ")", ":", "gen_object_list", "=", "[", "]", "for", "gen", "in", "curtailment", ".", "columns", ":", "# get generator object from representative", "gen_object", ...
45.608696
21.434783
def whitespace_around_operator(logical_line): r"""Avoid extraneous whitespace around an operator. Okay: a = 12 + 3 E221: a = 4 + 5 E222: a = 4 + 5 E223: a = 4\t+ 5 E224: a = 4 +\t5 """ for match in OPERATOR_REGEX.finditer(logical_line): before, after = match.groups() ...
[ "def", "whitespace_around_operator", "(", "logical_line", ")", ":", "for", "match", "in", "OPERATOR_REGEX", ".", "finditer", "(", "logical_line", ")", ":", "before", ",", "after", "=", "match", ".", "groups", "(", ")", "if", "'\\t'", "in", "before", ":", "...
31.904762
18.857143
def transformer_clean(): """No dropout, label smoothing, max_length.""" hparams = transformer_base_v2() hparams.label_smoothing = 0.0 hparams.layer_prepostprocess_dropout = 0.0 hparams.attention_dropout = 0.0 hparams.relu_dropout = 0.0 hparams.max_length = 0 return hparams
[ "def", "transformer_clean", "(", ")", ":", "hparams", "=", "transformer_base_v2", "(", ")", "hparams", ".", "label_smoothing", "=", "0.0", "hparams", ".", "layer_prepostprocess_dropout", "=", "0.0", "hparams", ".", "attention_dropout", "=", "0.0", "hparams", ".", ...
31.222222
10.555556
def enact(self, billing_cycle, disable_if_done=True): """Enact this RecurringCost for the given billing cycle This will: - Create a RecurredCost and the relevant Transactions & Transaction Legs - Mark this RecurringCost as disabled if this is its final billing cycle """ ...
[ "def", "enact", "(", "self", ",", "billing_cycle", ",", "disable_if_done", "=", "True", ")", ":", "as_of", "=", "billing_cycle", ".", "date_range", ".", "lower", "if", "not", "self", ".", "is_enactable", "(", "as_of", ")", ":", "raise", "CannotEnactUnenactab...
36.655172
19.689655
def _obj_display(obj, display=''): """Returns string representation of an object, either the default or based on the display template passed in. """ result = '' if not display: result = str(obj) else: template = Template(display) context = Context({'obj':obj}) res...
[ "def", "_obj_display", "(", "obj", ",", "display", "=", "''", ")", ":", "result", "=", "''", "if", "not", "display", ":", "result", "=", "str", "(", "obj", ")", "else", ":", "template", "=", "Template", "(", "display", ")", "context", "=", "Context",...
27.461538
13.076923
def runWizard(self, parent): """ Runs the wizard instance for this plugin. :param parent | <QWidget> :return <bool> | success """ wizard = XScaffoldWizard(self._scaffold, parent) return wizard.exec_()
[ "def", "runWizard", "(", "self", ",", "parent", ")", ":", "wizard", "=", "XScaffoldWizard", "(", "self", ".", "_scaffold", ",", "parent", ")", "return", "wizard", ".", "exec_", "(", ")" ]
28.3
11.5
def read(path): """ Read the contents of a LockFile. Arguments: path (str): Path to lockfile. Returns: Tuple(int, datetime): The integer PID of the lock owner, and the date the lock was required. If the lock is not claimed, both v...
[ "def", "read", "(", "path", ")", ":", "if", "fs", ".", "exists", "(", "path", ")", ":", "with", "open", "(", "path", ")", "as", "infile", ":", "components", "=", "infile", ".", "read", "(", ")", ".", "split", "(", ")", "pid", "=", "int", "(", ...
31.65
16.95
def pythonize(self, val): """Convert value into a address ip format:: * If value is a list, try to take the last element * match ip address and port (if available) :param val: value to convert :type val: :return: address/port corresponding to value :rtype: dict ...
[ "def", "pythonize", "(", "self", ",", "val", ")", ":", "val", "=", "unique_value", "(", "val", ")", "matches", "=", "re", ".", "match", "(", "r\"^([^:]*)(?::(\\d+))?$\"", ",", "val", ")", "if", "matches", "is", "None", ":", "raise", "ValueError", "addr",...
29.238095
16.380952
def add_bridge(name, datapath_type=None): ''' Add the named bridge to openvswitch ''' log('Creating bridge {}'.format(name)) cmd = ["ovs-vsctl", "--", "--may-exist", "add-br", name] if datapath_type is not None: cmd += ['--', 'set', 'bridge', name, 'datapath_type={}'.format(datap...
[ "def", "add_bridge", "(", "name", ",", "datapath_type", "=", "None", ")", ":", "log", "(", "'Creating bridge {}'", ".", "format", "(", "name", ")", ")", "cmd", "=", "[", "\"ovs-vsctl\"", ",", "\"--\"", ",", "\"--may-exist\"", ",", "\"add-br\"", ",", "name"...
44.25
8.5
def add_component(self, component): ''' Adds a Component to an Entity ''' if component not in self._components: self._components.append(component) else: # Replace Component self._components[self._components.index(component)] = component
[ "def", "add_component", "(", "self", ",", "component", ")", ":", "if", "component", "not", "in", "self", ".", "_components", ":", "self", ".", "_components", ".", "append", "(", "component", ")", "else", ":", "# Replace Component", "self", ".", "_components"...
36.75
14.75
def get_composition_search_session(self, proxy): """Gets a composition search session. arg proxy (osid.proxy.Proxy): a proxy return: (osid.repository.CompositionSearchSession) - a CompositionSearchSession raise: OperationFailed - unable to complete request r...
[ "def", "get_composition_search_session", "(", "self", ",", "proxy", ")", ":", "if", "not", "self", ".", "supports_composition_search", "(", ")", ":", "raise", "Unimplemented", "(", ")", "try", ":", "from", ".", "import", "sessions", "except", "ImportError", ":...
38.791667
15.958333
def generate(self, *args, **kwargs): """ Implementation for generate method from ReportBase. Generates the xml and saves the report in Junit xml format. :param args: 1 argument, filename is used. :param kwargs: Not used :return: Nothing """ xmlstr = str(s...
[ "def", "generate", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "xmlstr", "=", "str", "(", "self", ")", "filename", "=", "args", "[", "0", "]", "with", "open", "(", "filename", ",", "'w'", ")", "as", "fil", ":", "fil", ".",...
33
15.875
def get_project_info(configs, heartbeat, data): """Find the current project and branch. First looks for a .wakatime-project file. Second, uses the --project arg. Third, uses the folder name from a revision control repository. Last, uses the --alternate-project arg. Returns a project, branch tuple....
[ "def", "get_project_info", "(", "configs", ",", "heartbeat", ",", "data", ")", ":", "project_name", ",", "branch_name", "=", "heartbeat", ".", "project", ",", "heartbeat", ".", "branch", "if", "heartbeat", ".", "type", "!=", "'file'", ":", "project_name", "=...
37.306452
22.5
def _CollectArguments(function, args, kwargs): """Merges positional and keyword arguments into a single dict.""" all_args = dict(kwargs) arg_names = inspect.getargspec(function)[0] for position, arg in enumerate(args): if position < len(arg_names): all_args[arg_names[position]] = arg return all_args
[ "def", "_CollectArguments", "(", "function", ",", "args", ",", "kwargs", ")", ":", "all_args", "=", "dict", "(", "kwargs", ")", "arg_names", "=", "inspect", ".", "getargspec", "(", "function", ")", "[", "0", "]", "for", "position", ",", "arg", "in", "e...
39.125
7.25
def getResourceTypes(self): """ Get the list of resource types supported by the HydroShare server :return: A set of strings representing the HydroShare resource types :raises: HydroShareHTTPException to signal an HTTP error """ url = "{url_base}/resource/types".format(url_base=...
[ "def", "getResourceTypes", "(", "self", ")", ":", "url", "=", "\"{url_base}/resource/types\"", ".", "format", "(", "url_base", "=", "self", ".", "url_base", ")", "r", "=", "self", ".", "_request", "(", "'GET'", ",", "url", ")", "if", "r", ".", "status_co...
37.533333
22.466667
def legislators(request, abbr): ''' Context: - metadata - chamber - chamber_title - chamber_select_template - chamber_select_collection - chamber_select_chambers - show_chamber_column - abbr - legislators - sort_order - sort...
[ "def", "legislators", "(", "request", ",", "abbr", ")", ":", "try", ":", "meta", "=", "Metadata", ".", "get_object", "(", "abbr", ")", "except", "DoesNotExist", ":", "raise", "Http404", "spec", "=", "{", "'active'", ":", "True", ",", "'district'", ":", ...
32.170732
21
def _choice_format(self, occur): """Return the serialization format for a choice node.""" middle = "%s" if self.rng_children() else "<empty/>%s" fmt = self.start_tag() + middle + self.end_tag() if self.occur != 2: return "<optional>" + fmt + "</optional>" else: ...
[ "def", "_choice_format", "(", "self", ",", "occur", ")", ":", "middle", "=", "\"%s\"", "if", "self", ".", "rng_children", "(", ")", "else", "\"<empty/>%s\"", "fmt", "=", "self", ".", "start_tag", "(", ")", "+", "middle", "+", "self", ".", "end_tag", "(...
41.25
14.625
def composite_join(separator, items): """ Join a list of items with a separator. This is used in joining strings, responses and Composites. The output will be a Composite. """ output = Composite() first_item = True for item in items: # skip emp...
[ "def", "composite_join", "(", "separator", ",", "items", ")", ":", "output", "=", "Composite", "(", ")", "first_item", "=", "True", "for", "item", "in", "items", ":", "# skip empty items", "if", "not", "item", ":", "continue", "# skip separator on first item", ...
30.421053
10.105263
def store(self, stream, linesep=os.linesep): """ Serialize this section and write it to a binary stream """ for k, v in self.items(): write_key_val(stream, k, v, linesep) stream.write(linesep.encode('utf-8'))
[ "def", "store", "(", "self", ",", "stream", ",", "linesep", "=", "os", ".", "linesep", ")", ":", "for", "k", ",", "v", "in", "self", ".", "items", "(", ")", ":", "write_key_val", "(", "stream", ",", "k", ",", "v", ",", "linesep", ")", "stream", ...
28.222222
14
def callproc(self, procname, parameters=()): """ Call a stored procedure with the given name. :param procname: The name of the procedure to call :type procname: str :keyword parameters: The optional parameters for the procedure :type parameters: sequence Note: I...
[ "def", "callproc", "(", "self", ",", "procname", ",", "parameters", "=", "(", ")", ")", ":", "conn", "=", "self", ".", "_assert_open", "(", ")", "conn", ".", "_try_activate_cursor", "(", "self", ")", "return", "self", ".", "_callproc", "(", "procname", ...
40.25
17.125
def merge(self, resource_type, resource_properties): """ Adds global properties to the resource, if necessary. This method is a no-op if there are no global properties for this resource type :param string resource_type: Type of the resource (Ex: AWS::Serverless::Function) :param...
[ "def", "merge", "(", "self", ",", "resource_type", ",", "resource_properties", ")", ":", "if", "resource_type", "not", "in", "self", ".", "template_globals", ":", "# Nothing to do. Return the template unmodified", "return", "resource_properties", "global_props", "=", "s...
42.352941
26
def send_meta_data(socket, conf, name): '''Sends the config via ZeroMQ to a specified socket. Is called at the beginning of a run and when the config changes. Conf can be any config dictionary. ''' meta_data = dict( name=name, conf=conf ) try: socket.send_json(meta_data, flag...
[ "def", "send_meta_data", "(", "socket", ",", "conf", ",", "name", ")", ":", "meta_data", "=", "dict", "(", "name", "=", "name", ",", "conf", "=", "conf", ")", "try", ":", "socket", ".", "send_json", "(", "meta_data", ",", "flags", "=", "zmq", ".", ...
32.636364
31.181818
def unflag_field(self, move_x, move_y): """Unflag or unquestion a grid by given position.""" field_status = self.info_map[move_y, move_x] if field_status == 9 or field_status == 10: self.info_map[move_y, move_x] = 11
[ "def", "unflag_field", "(", "self", ",", "move_x", ",", "move_y", ")", ":", "field_status", "=", "self", ".", "info_map", "[", "move_y", ",", "move_x", "]", "if", "field_status", "==", "9", "or", "field_status", "==", "10", ":", "self", ".", "info_map", ...
41.333333
11.666667
def generate_anstar_3d_lattice(maxv1, minv1, maxv2, minv2, maxv3, minv3, \ mindist): """ This function calls into LAL routines to generate a 3-dimensional array of points using the An^* lattice. Parameters ----------- maxv1 : float Largest value in the 1st...
[ "def", "generate_anstar_3d_lattice", "(", "maxv1", ",", "minv1", ",", "maxv2", ",", "minv2", ",", "maxv3", ",", "minv3", ",", "mindist", ")", ":", "# Lalpulsar not a requirement for the rest of pycbc, so check if we have it", "# here in this function.", "try", ":", "impor...
34.736111
20.486111
def reset(self): """Reset itself and recursively all its children.""" watchers.MATCHER.debug("Node <%s> reset", self) self._reset() for child in self.children: child.node.reset()
[ "def", "reset", "(", "self", ")", ":", "watchers", ".", "MATCHER", ".", "debug", "(", "\"Node <%s> reset\"", ",", "self", ")", "self", ".", "_reset", "(", ")", "for", "child", "in", "self", ".", "children", ":", "child", ".", "node", ".", "reset", "(...
36.166667
12.166667
def _route(self, action, method): """ Given an action method, generates a route for it. """ # First thing, determine the path for the method path = method._wsgi_path methods = None if path is None: map_rule = self.wsgi_method_map.get(method.__name__) ...
[ "def", "_route", "(", "self", ",", "action", ",", "method", ")", ":", "# First thing, determine the path for the method", "path", "=", "method", ".", "_wsgi_path", "methods", "=", "None", "if", "path", "is", "None", ":", "map_rule", "=", "self", ".", "wsgi_met...
36.948718
18.487179
def linseg(params, start=0, end=1): ''' Signal starts at start value, ramps linearly up to end value :param params: buffer parameters, controls length of signal created :param start: start value (number) :param end: end value (number) :return: array of resulting signal ''' return np.lins...
[ "def", "linseg", "(", "params", ",", "start", "=", "0", ",", "end", "=", "1", ")", ":", "return", "np", ".", "linspace", "(", "start", ",", "end", ",", "num", "=", "params", ".", "length", ",", "endpoint", "=", "True", ")" ]
40.222222
18.222222
def get_parameter_limits(xval, loglike, cl_limit=0.95, cl_err=0.68269, tol=1E-2, bounds=None): """Compute upper/lower limits, peak position, and 1-sigma errors from a 1-D likelihood function. This function uses the delta-loglikelihood method to evaluate parameter limits by sear...
[ "def", "get_parameter_limits", "(", "xval", ",", "loglike", ",", "cl_limit", "=", "0.95", ",", "cl_err", "=", "0.68269", ",", "tol", "=", "1E-2", ",", "bounds", "=", "None", ")", ":", "dlnl_limit", "=", "onesided_cl_to_dlnl", "(", "cl_limit", ")", "dlnl_er...
33.323944
21.683099
def synthesize(self, message_text, voice_id='Nicole', output_format='mp3', sample_rate='22050', stream_response=False): ''' a method to synthesize speech from text :param message_text: string with text to synthesize :param voice_id: string with name of voice id in A...
[ "def", "synthesize", "(", "self", ",", "message_text", ",", "voice_id", "=", "'Nicole'", ",", "output_format", "=", "'mp3'", ",", "sample_rate", "=", "'22050'", ",", "stream_response", "=", "False", ")", ":", "title", "=", "'%s.synthesize'", "%", "self", "."...
33.5625
18.8625
def db_migrate(): """Migrate DB """ print("Not ready for use") exit() cwd_to_sys_path() alembic = _set_flask_alembic() with application.app.app_context(): p = db.Model.__subclasses__() print(p) # Auto-generate a migration alembic.revision('making changes') ...
[ "def", "db_migrate", "(", ")", ":", "print", "(", "\"Not ready for use\"", ")", "exit", "(", ")", "cwd_to_sys_path", "(", ")", "alembic", "=", "_set_flask_alembic", "(", ")", "with", "application", ".", "app", ".", "app_context", "(", ")", ":", "p", "=", ...
23.8
15.2
def pat(p): """Given a string `p` with feature matrices (features grouped with square brackets into segments, return a list of sets of (value, feature) tuples. Args: p (str): list of feature matrices as strings Return: list: list of sets of (value, feature) tuples """ pattern =...
[ "def", "pat", "(", "p", ")", ":", "pattern", "=", "[", "]", "for", "matrix", "in", "[", "m", ".", "group", "(", "0", ")", "for", "m", "in", "MT_REGEX", ".", "finditer", "(", "p", ")", "]", ":", "segment", "=", "set", "(", "[", "m", ".", "gr...
32.866667
22.466667
def set_standard(self): """Set the charger to standard range for daily commute.""" if self.__maxrange_state: data = self._controller.command(self._id, 'charge_standard', wake_if_asleep=True) if data and data['response']['result']: ...
[ "def", "set_standard", "(", "self", ")", ":", "if", "self", ".", "__maxrange_state", ":", "data", "=", "self", ".", "_controller", ".", "command", "(", "self", ".", "_id", ",", "'charge_standard'", ",", "wake_if_asleep", "=", "True", ")", "if", "data", "...
50.625
13.375
def form_valid(self, forms): """ If the form is valid, save the associated model. """ for key, form in forms.items(): setattr(self, '{}_object'.format(key), form.save()) return super(MultipleModelFormMixin, self).form_valid(forms)
[ "def", "form_valid", "(", "self", ",", "forms", ")", ":", "for", "key", ",", "form", "in", "forms", ".", "items", "(", ")", ":", "setattr", "(", "self", ",", "'{}_object'", ".", "format", "(", "key", ")", ",", "form", ".", "save", "(", ")", ")", ...
39.428571
11.428571
def list_nodes(call=None): ''' Return a list of the BareMetal servers that are on the provider. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) items = query(method='servers') ret = {} for node in...
[ "def", "list_nodes", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The list_nodes function must be called with -f or --function.'", ")", "items", "=", "query", "(", "method", "=", "'servers'", ")", ...
26.705882
19.117647
def _one_to_one(self): """Perform one-to-one file conversion. :return: None :rtype: :py:obj:`None` """ if not self.file_generator.to_path_compression: self._to_textfile(self.file_generator) elif self.file_generator.to_path_compression == "gz": self...
[ "def", "_one_to_one", "(", "self", ")", ":", "if", "not", "self", ".", "file_generator", ".", "to_path_compression", ":", "self", ".", "_to_textfile", "(", "self", ".", "file_generator", ")", "elif", "self", ".", "file_generator", ".", "to_path_compression", "...
55.625
26.3125
def get_raw_blast(pdb_id, output_form='HTML', chain_id='A'): '''Look up full BLAST page for a given PDB ID get_blast() uses this function internally Parameters ---------- pdb_id : string A 4 character string giving a pdb entry of interest chain_id : string A single character ...
[ "def", "get_raw_blast", "(", "pdb_id", ",", "output_form", "=", "'HTML'", ",", "chain_id", "=", "'A'", ")", ":", "url_root", "=", "'http://www.rcsb.org/pdb/rest/getBlastPDB2?structureId='", "url", "=", "url_root", "+", "pdb_id", "+", "'&chainId='", "+", "chain_id", ...
24.457143
26.228571
def LDA_base(x, labels): """ Base function used for Linear Discriminant Analysis. **Args:** * `x` : input matrix (2d array), every row represents new sample * `labels` : list of labels (iterable), every item should be label for \ sample with corresponding index **Returns:** * ...
[ "def", "LDA_base", "(", "x", ",", "labels", ")", ":", "classes", "=", "np", ".", "array", "(", "tuple", "(", "set", "(", "labels", ")", ")", ")", "cols", "=", "x", ".", "shape", "[", "1", "]", "# mean values for every class", "means", "=", "np", "....
36.073171
17.390244
def _return_comma_list(self, l): """ get a list and return a string with comma separated list values Examples ['to', 'ta'] will return 'to,ta'. """ if isinstance(l, (text_type, int)): return l if not isinstance(l, list): raise TypeError(l, ' should be a l...
[ "def", "_return_comma_list", "(", "self", ",", "l", ")", ":", "if", "isinstance", "(", "l", ",", "(", "text_type", ",", "int", ")", ")", ":", "return", "l", "if", "not", "isinstance", "(", "l", ",", "list", ")", ":", "raise", "TypeError", "(", "l",...
30.142857
16.285714
def cases(arg, case_result_pairs, default=None): """ Create a case expression in one shot. Returns ------- case_expr : SimpleCase """ builder = arg.case() for case, result in case_result_pairs: builder = builder.when(case, result) if default is not None: builder = bu...
[ "def", "cases", "(", "arg", ",", "case_result_pairs", ",", "default", "=", "None", ")", ":", "builder", "=", "arg", ".", "case", "(", ")", "for", "case", ",", "result", "in", "case_result_pairs", ":", "builder", "=", "builder", ".", "when", "(", "case"...
25.142857
12.285714
def _getAuth(self, auth): """Create the authorization/identification portion of a request.""" if type(auth) is dict: return auth else: # auth is string if None != self._clientid: return {"cik": auth, "client_id": self._clientid} eli...
[ "def", "_getAuth", "(", "self", ",", "auth", ")", ":", "if", "type", "(", "auth", ")", "is", "dict", ":", "return", "auth", "else", ":", "# auth is string", "if", "None", "!=", "self", ".", "_clientid", ":", "return", "{", "\"cik\"", ":", "auth", ","...
40
13.363636
def _do_setup_step(self, play): ''' get facts from the remote system ''' host_list = self._list_available_hosts(play.hosts) if play.gather_facts is False: return {} elif play.gather_facts is None: host_list = [h for h in host_list if h not in self.SETUP_CACHE or...
[ "def", "_do_setup_step", "(", "self", ",", "play", ")", ":", "host_list", "=", "self", ".", "_list_available_hosts", "(", "play", ".", "hosts", ")", "if", "play", ".", "gather_facts", "is", "False", ":", "return", "{", "}", "elif", "play", ".", "gather_f...
47.885714
27.028571