text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def mnl_estimate(data, chosen, numalts, GPU=False, coeffrange=(-3, 3), weights=None, lcgrad=False, beta=None): """ Calculate coefficients of the MNL model. Parameters ---------- data : 2D array The data are expected to be in "long" form where each row is for one alt...
[ "def", "mnl_estimate", "(", "data", ",", "chosen", ",", "numalts", ",", "GPU", "=", "False", ",", "coeffrange", "=", "(", "-", "3", ",", "3", ")", ",", "weights", "=", "None", ",", "lcgrad", "=", "False", ",", "beta", "=", "None", ")", ":", "logg...
34.806122
0.000285
def l_system(axiom, transformations, iterations=1, angle=45, resolution=1): """Generates a texture by running transformations on a turtle program. First, the given transformations are applied to the axiom. This is repeated `iterations` times. Then, the output is run as a turtle program to get a texture...
[ "def", "l_system", "(", "axiom", ",", "transformations", ",", "iterations", "=", "1", ",", "angle", "=", "45", ",", "resolution", "=", "1", ")", ":", "turtle_program", "=", "transform_multiple", "(", "axiom", ",", "transformations", ",", "iterations", ")", ...
46.652174
0.001826
def lessThan(self, value): """ Sets the operator type to Query.Op.LessThan and sets the value to the inputted value. :param value <variant> :return <Query> :sa lessThan :usage |>>> from orb import Que...
[ "def", "lessThan", "(", "self", ",", "value", ")", ":", "newq", "=", "self", ".", "copy", "(", ")", "newq", ".", "setOp", "(", "Query", ".", "Op", ".", "LessThan", ")", "newq", ".", "setValue", "(", "value", ")", "return", "newq" ]
28.2
0.010292
def ensure_tuple(length, tuples): """Yield `length`-sized tuples from the given collection. Will truncate longer tuples to the desired length, and pad using the leading element if shorter. """ for elem in tuples: # Handle non-tuples and non-lists as a single repeated element. if not isinstance(elem, (tuple,...
[ "def", "ensure_tuple", "(", "length", ",", "tuples", ")", ":", "for", "elem", "in", "tuples", ":", "# Handle non-tuples and non-lists as a single repeated element.", "if", "not", "isinstance", "(", "elem", ",", "(", "tuple", ",", "list", ")", ")", ":", "yield", ...
26.48
0.049563
def document_agents(p): """ Document agents in AIKIF (purpose and intent) """ p.comment('agent.py', 'base agent class') p.comment('run_agents.py', 'Top level function to run the agents') p.comment('agent_image_metadata.py', 'agent to collect file picture metadata') p.comment('agent_lear...
[ "def", "document_agents", "(", "p", ")", ":", "p", ".", "comment", "(", "'agent.py'", ",", "'base agent class'", ")", "p", ".", "comment", "(", "'run_agents.py'", ",", "'Top level function to run the agents'", ")", "p", ".", "comment", "(", "'agent_image_metadata....
66
0.008299
def memoize(func, cache, num_args): """ Wrap a function so that results for any argument tuple are stored in 'cache'. Note that the args to the function must be usable as dictionary keys. Only the first num_args are considered when creating the key. """ @wraps(func) def wrapper(*args): ...
[ "def", "memoize", "(", "func", ",", "cache", ",", "num_args", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ")", ":", "mem_args", "=", "args", "[", ":", "num_args", "]", "if", "mem_args", "in", "cache", ":", "return"...
28.111111
0.001912
def find_event_with_outgoing_edges(self, event_name, desired_relations): """Gets a list of event nodes with the specified event_name and outgoing edges annotated with each of the specified relations. Parameters ---------- event_name : str Look for event nodes with th...
[ "def", "find_event_with_outgoing_edges", "(", "self", ",", "event_name", ",", "desired_relations", ")", ":", "G", "=", "self", ".", "G", "desired_relations", "=", "set", "(", "desired_relations", ")", "desired_event_nodes", "=", "[", "]", "for", "node", "in", ...
37.181818
0.001589
def oaiserver(sets, records): """Initialize OAI-PMH server.""" from invenio_db import db from invenio_oaiserver.models import OAISet from invenio_records.api import Record # create a OAI Set with db.session.begin_nested(): for i in range(sets): db.session.add(OAISet( ...
[ "def", "oaiserver", "(", "sets", ",", "records", ")", ":", "from", "invenio_db", "import", "db", "from", "invenio_oaiserver", ".", "models", "import", "OAISet", "from", "invenio_records", ".", "api", "import", "Record", "# create a OAI Set", "with", "db", ".", ...
30.276596
0.000681
def sequence(self, fasta, use_strand=True): """ Retrieves the sequence of this feature as a string. Uses the pyfaidx package. Parameters ---------- fasta : str If str, then it's a FASTA-format filename; otherwise assume it's a pyfaidx.Fasta obje...
[ "def", "sequence", "(", "self", ",", "fasta", ",", "use_strand", "=", "True", ")", ":", "if", "isinstance", "(", "fasta", ",", "six", ".", "string_types", ")", ":", "fasta", "=", "Fasta", "(", "fasta", ",", "as_raw", "=", "False", ")", "# recall GTF/GF...
29.666667
0.002176
def modulo_distribution(modulo=3, wait=30, non_zero_wait=False): """ Modulo distribution This helper uses the unit number, a modulo value and a constant wait time to produce a calculated wait time distribution. This is useful in large scale deployments to distribute load during an expensive operation s...
[ "def", "modulo_distribution", "(", "modulo", "=", "3", ",", "wait", "=", "30", ",", "non_zero_wait", "=", "False", ")", ":", "unit_number", "=", "int", "(", "local_unit", "(", ")", ".", "split", "(", "'/'", ")", "[", "1", "]", ")", "calculated_wait_tim...
39.818182
0.000743
def _add_parent_cnt(self, hdr, goobj, c2ps): """Add the parent count to the GO term box for if not all parents are plotted.""" if goobj.id in c2ps: parents = c2ps[goobj.id] if 'prt_pcnt' in self.present or parents and len(goobj.parents) != len(parents): assert len...
[ "def", "_add_parent_cnt", "(", "self", ",", "hdr", ",", "goobj", ",", "c2ps", ")", ":", "if", "goobj", ".", "id", "in", "c2ps", ":", "parents", "=", "c2ps", "[", "goobj", ".", "id", "]", "if", "'prt_pcnt'", "in", "self", ".", "present", "or", "pare...
60.714286
0.009281
def serialize(self): """Convert this recorded RPC into a string.""" return "{},{: <26},{:2d},{:#06x},{:#04x},{:5.0f},{: <40},{: <40},{}".\ format(self.connection, self.start_stamp.isoformat(), self.address, self.rpc_id, self.status, self.runtime * 1000, self.call, self.re...
[ "def", "serialize", "(", "self", ")", ":", "return", "\"{},{: <26},{:2d},{:#06x},{:#04x},{:5.0f},{: <40},{: <40},{}\"", ".", "format", "(", "self", ".", "connection", ",", "self", ".", "start_stamp", ".", "isoformat", "(", ")", ",", "self", ".", "address", ",", ...
55.666667
0.011799
def parse_response(self, resp): """ Parse the xmlrpc response. """ p, u = self.getparser() p.feed(resp.content) p.close() return u.close()
[ "def", "parse_response", "(", "self", ",", "resp", ")", ":", "p", ",", "u", "=", "self", ".", "getparser", "(", ")", "p", ".", "feed", "(", "resp", ".", "content", ")", "p", ".", "close", "(", ")", "return", "u", ".", "close", "(", ")" ]
23.375
0.010309
def execDetails(self, reqId, contract, execution): """execDetails(EWrapper self, int reqId, Contract contract, Execution execution)""" return _swigibpy.EWrapper_execDetails(self, reqId, contract, execution)
[ "def", "execDetails", "(", "self", ",", "reqId", ",", "contract", ",", "execution", ")", ":", "return", "_swigibpy", ".", "EWrapper_execDetails", "(", "self", ",", "reqId", ",", "contract", ",", "execution", ")" ]
73.333333
0.013514
def get_sections_by_delegate_and_term(person, term, future_terms=0, include_secondaries=True, transcriptable_course='yes', delete_...
[ "def", "get_sections_by_delegate_and_term", "(", "person", ",", "term", ",", "future_terms", "=", "0", ",", "include_secondaries", "=", "True", ",", "transcriptable_course", "=", "'yes'", ",", "delete_flag", "=", "[", "'active'", "]", ")", ":", "data", "=", "_...
50.238095
0.00093
def __neighbor_indexes_points(self, index_point): """! @brief Return neighbors of the specified object in case of sequence of points. @param[in] index_point (uint): Index point whose neighbors are should be found. @return (list) List of indexes of neighbors in line the connectivi...
[ "def", "__neighbor_indexes_points", "(", "self", ",", "index_point", ")", ":", "kdnodes", "=", "self", ".", "__kdtree", ".", "find_nearest_dist_nodes", "(", "self", ".", "__pointer_data", "[", "index_point", "]", ",", "self", ".", "__eps", ")", "return", "[", ...
49.454545
0.012635
def rotate_polygon(lon, lat, lon0, lat0): """ Given a polygon with vertices defined by (lon, lat), rotate the polygon such that the North pole of the spherical coordinates is now at (lon0, lat0). Therefore, to end up with a polygon centered on (lon0, lat0), the polygon should initially be drawn arou...
[ "def", "rotate_polygon", "(", "lon", ",", "lat", ",", "lon0", ",", "lat0", ")", ":", "# Create a representation object", "polygon", "=", "UnitSphericalRepresentation", "(", "lon", "=", "lon", ",", "lat", "=", "lat", ")", "# Determine rotation matrix to make it so th...
38.913043
0.001091
def graph(network, branch_components=None, weight=None, inf_weight=False): """ Build NetworkX graph. Arguments --------- network : Network|SubNetwork branch_components : [str] Components to use as branches. The default are passive_branch_components in the case of a SubNetwork a...
[ "def", "graph", "(", "network", ",", "branch_components", "=", "None", ",", "weight", "=", "None", ",", "inf_weight", "=", "False", ")", ":", "from", ".", "import", "components", "if", "isinstance", "(", "network", ",", "components", ".", "Network", ")", ...
32.753846
0.001368
def _best_response_selection(x, g, indptr=None): """ Selection of the best response correspondence of `g` that selects the best response action with the smallest index when there are ties, where the input and output are flattened action profiles. Parameters ---------- x : array_like(float, ...
[ "def", "_best_response_selection", "(", "x", ",", "g", ",", "indptr", "=", "None", ")", ":", "N", "=", "g", ".", "N", "if", "indptr", "is", "None", ":", "indptr", "=", "np", ".", "empty", "(", "N", "+", "1", ",", "dtype", "=", "int", ")", "indp...
32.54
0.00179
def set_title(self,table=None,title=None,verbose=None): """ Changes the visible identifier of a single table. :param table (string, optional): Specifies a table by table name. If the pr efix SUID: is used, the table corresponding the SUID will be returne d. :para...
[ "def", "set_title", "(", "self", ",", "table", "=", "None", ",", "title", "=", "None", ",", "verbose", "=", "None", ")", ":", "PARAMS", "=", "set_param", "(", "[", "'table'", ",", "'title'", "]", ",", "[", "table", ",", "title", "]", ")", "response...
45.230769
0.023333
def getFilterNames(header, filternames=None): """ Returns a comma-separated string of filter names extracted from the input header (PyFITS header object). This function has been hard-coded to support the following instruments: ACS, WFPC2, STIS This function relies on the 'INSTRUME' keywor...
[ "def", "getFilterNames", "(", "header", ",", "filternames", "=", "None", ")", ":", "# Define the keyword names for each instrument", "_keydict", "=", "{", "'ACS'", ":", "[", "'FILTER1'", ",", "'FILTER2'", "]", ",", "'WFPC2'", ":", "[", "'FILTNAM1'", ",", "'FILTN...
34.769231
0.000538
async def play_now(self, requester: int, track: dict): """ Add track and play it. """ self.add_next(requester, track) await self.play(ignore_shuffle=True)
[ "async", "def", "play_now", "(", "self", ",", "requester", ":", "int", ",", "track", ":", "dict", ")", ":", "self", ".", "add_next", "(", "requester", ",", "track", ")", "await", "self", ".", "play", "(", "ignore_shuffle", "=", "True", ")" ]
44.5
0.01105
async def register(self, service): """Registers a new local service. Returns: bool: ``True`` on success The register endpoint is used to add a new service, with an optional health check, to the local agent. The request body must look like:: { ...
[ "async", "def", "register", "(", "self", ",", "service", ")", ":", "response", "=", "await", "self", ".", "_api", ".", "put", "(", "\"/v1/agent/service/register\"", ",", "data", "=", "service", ")", "return", "response", ".", "status", "==", "200" ]
50.372093
0.000453
def probe(*devices): ''' Ask the kernel to update its local partition data. When no args are specified all block devices are tried. Caution: Generally only works on devices with no mounted partitions and may take a long time to return if specified devices are in use. CLI Examples: .. code...
[ "def", "probe", "(", "*", "devices", ")", ":", "for", "device", "in", "devices", ":", "_validate_device", "(", "device", ")", "cmd", "=", "'partprobe -- {0}'", ".", "format", "(", "\" \"", ".", "join", "(", "devices", ")", ")", "out", "=", "__salt__", ...
28.454545
0.001546
def do_numberrep(self, line): """numberrep <number of replicas> Set preferred number of replicas for new objects If the preferred number of replicas is set to zero, replication is also disallowed.""" n_replicas = self._split_args(line, 1, 0)[0] self._command_processor.get_session...
[ "def", "do_numberrep", "(", "self", ",", "line", ")", ":", "n_replicas", "=", "self", ".", "_split_args", "(", "line", ",", "1", ",", "0", ")", "[", "0", "]", "self", ".", "_command_processor", ".", "get_session", "(", ")", ".", "get_replication_policy",...
53.666667
0.01222
def download(self, url, post=False, parameters=None, timeout=None): # type: (str, bool, Optional[Dict], Optional[float]) -> requests.Response """Download url Args: url (str): URL to download post (bool): Whether to use POST instead of GET. Defaults to False. ...
[ "def", "download", "(", "self", ",", "url", ",", "post", "=", "False", ",", "parameters", "=", "None", ",", "timeout", "=", "None", ")", ":", "# type: (str, bool, Optional[Dict], Optional[float]) -> requests.Response", "return", "self", ".", "setup", "(", "url", ...
42.666667
0.009174
def tvdb_refresh_token(token): """ Refreshes JWT token Online docs: api.thetvdb.com/swagger#!/Authentication/get_refresh_token= """ url = "https://api.thetvdb.com/refresh_token" headers = {"Authorization": "Bearer %s" % token} status, content = _request_json(url, headers=headers, cache=False) ...
[ "def", "tvdb_refresh_token", "(", "token", ")", ":", "url", "=", "\"https://api.thetvdb.com/refresh_token\"", "headers", "=", "{", "\"Authorization\"", ":", "\"Bearer %s\"", "%", "token", "}", "status", ",", "content", "=", "_request_json", "(", "url", ",", "heade...
40.384615
0.001862
def _create_latent_variables(self): """ Creates model latent variables Returns ---------- None (changes model attributes) """ self.latent_variables.add_z('Vol Constant', fam.Normal(0,3,transform=None), fam.Normal(0,3)) for p_term in range(self.p): s...
[ "def", "_create_latent_variables", "(", "self", ")", ":", "self", ".", "latent_variables", ".", "add_z", "(", "'Vol Constant'", ",", "fam", ".", "Normal", "(", "0", ",", "3", ",", "transform", "=", "None", ")", ",", "fam", ".", "Normal", "(", "0", ",",...
42.466667
0.020721
def find_signature_parameters(callable_, candidates, excluded=('self', 'cls')): """Find on a set of candidates the parameters needed to execute a callable. Returns a dictionary with the `candidates` found on `callable_`. When any of the required parameters of a callable is not...
[ "def", "find_signature_parameters", "(", "callable_", ",", "candidates", ",", "excluded", "=", "(", "'self'", ",", "'cls'", ")", ")", ":", "signature_params", "=", "inspect_signature_parameters", "(", "callable_", ",", "excluded", "=", "excluded", ")", "exec_param...
35.365854
0.000671
def get_dag_configs(self) -> Dict[str, Dict[str, Any]]: """ Returns configuration for each the DAG in factory :returns: dict with configuration for dags """ return {dag: self.config[dag] for dag in self.config.keys() if dag != "default"}
[ "def", "get_dag_configs", "(", "self", ")", "->", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Any", "]", "]", ":", "return", "{", "dag", ":", "self", ".", "config", "[", "dag", "]", "for", "dag", "in", "self", ".", "config", ".", "keys", ...
38.857143
0.010791
def main(): """ Install a package from the local folder :return: """ common.setup_main() config = common.ConfigData() dist_folder = 'dist' if os.path.isdir(dist_folder): shutil.rmtree(dist_folder) args = [ '{}'.format(config.python), 'setup.py', 'sdis...
[ "def", "main", "(", ")", ":", "common", ".", "setup_main", "(", ")", "config", "=", "common", ".", "ConfigData", "(", ")", "dist_folder", "=", "'dist'", "if", "os", ".", "path", ".", "isdir", "(", "dist_folder", ")", ":", "shutil", ".", "rmtree", "("...
22.282609
0.000935
def _read_munparsed(self, lines): """ Read text fragments from an munparsed format text file. :param list lines: the lines of the unparsed text file """ from bs4 import BeautifulSoup def nodes_at_level(root, level): """ Return a dict with the bs4 filter para...
[ "def", "_read_munparsed", "(", "self", ",", "lines", ")", ":", "from", "bs4", "import", "BeautifulSoup", "def", "nodes_at_level", "(", "root", ",", "level", ")", ":", "\"\"\" Return a dict with the bs4 filter parameters \"\"\"", "LEVEL_TO_REGEX_MAP", "=", "[", "None",...
45.386364
0.00147
def current_git_hash(): """Retrieve the current git hash number of the git repo (first 6 digit). :returns: 6 digit of hash number. :rtype: str """ repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) git_show = subprocess.Popen( 'git rev-parse --short=6 HEAD', ...
[ "def", "current_git_hash", "(", ")", ":", "repo_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", ")", "git_show", "=", "subprocess", ".", "Popen",...
30.5
0.001767
def add_checkpoint(html_note, counter): """Recursively adds checkpoints to html tree. """ if html_note.text: html_note.text = (html_note.text + CHECKPOINT_PREFIX + str(counter) + CHECKPOINT_SUFFIX) else: html_note.text = (CHECKPOINT_PREFIX + str(counter) + ...
[ "def", "add_checkpoint", "(", "html_note", ",", "counter", ")", ":", "if", "html_note", ".", "text", ":", "html_note", ".", "text", "=", "(", "html_note", ".", "text", "+", "CHECKPOINT_PREFIX", "+", "str", "(", "counter", ")", "+", "CHECKPOINT_SUFFIX", ")"...
32.478261
0.0013
def transmit_ack_bpdu(self): """ Send Topology Change Ack BPDU. """ ack_flags = 0b10000001 bpdu_data = self._generate_config_bpdu(ack_flags) self.ofctl.send_packet_out(self.ofport.port_no, bpdu_data)
[ "def", "transmit_ack_bpdu", "(", "self", ")", ":", "ack_flags", "=", "0b10000001", "bpdu_data", "=", "self", ".", "_generate_config_bpdu", "(", "ack_flags", ")", "self", ".", "ofctl", ".", "send_packet_out", "(", "self", ".", "ofport", ".", "port_no", ",", "...
45.4
0.008658
def create(self, searched_resource, uri_parameters=None, request_body_dict=None, query_parameters_dict=None, additional_headers=None): """ This method is used to create a resource using the POST HTTP Method :param searched_resource: A valid display name in the RAML file matching t...
[ "def", "create", "(", "self", ",", "searched_resource", ",", "uri_parameters", "=", "None", ",", "request_body_dict", "=", "None", ",", "query_parameters_dict", "=", "None", ",", "additional_headers", "=", "None", ")", ":", "return", "self", ".", "_request", "...
76.75
0.010459
def set(self, key, value): """ Set a key's value regardless of whether a change is seen.""" return self.__setitem__(key, value, force=True)
[ "def", "set", "(", "self", ",", "key", ",", "value", ")", ":", "return", "self", ".", "__setitem__", "(", "key", ",", "value", ",", "force", "=", "True", ")" ]
51
0.012903
def create(container, portal_type, *args, **kwargs): """Creates an object in Bika LIMS This code uses most of the parts from the TypesTool see: `Products.CMFCore.TypesTool._constructInstance` :param container: container :type container: ATContentType/DexterityContentType/CatalogBrain :param po...
[ "def", "create", "(", "container", ",", "portal_type", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "bika", ".", "lims", ".", "utils", "import", "tmpID", "if", "kwargs", ".", "get", "(", "\"title\"", ")", "is", "None", ":", "kwargs", ...
32.54902
0.000585
def matchmaker_request(url, token, method, content_type=None, accept=None, data=None): """Send a request to MatchMaker and return its response Args: url(str): url to send request to token(str): MME server authorization token method(str): 'GET', 'POST' or 'DELETE' content_type(st...
[ "def", "matchmaker_request", "(", "url", ",", "token", ",", "method", ",", "content_type", "=", "None", ",", "accept", "=", "None", ",", "data", "=", "None", ")", ":", "headers", "=", "Headers", "(", ")", "headers", "=", "{", "'X-Auth-Token'", ":", "to...
34.632653
0.010315
def _merge(self, key, value): """ Internal merge logic implementation to allow merging of values when setting attributes/items. :param key: Attribute name or item key :type key: str :param value: Value to set attribute/item as. :type value: object :rtype:...
[ "def", "_merge", "(", "self", ",", "key", ",", "value", ")", ":", "method", "=", "self", ".", "_merge_method", "(", "key", ")", "if", "method", "is", "not", "None", ":", "# strings are special, update methods like set.update looks for", "# iterables", "if", "met...
35.75
0.001946
def get_field(hologram, sideband=+1, filter_name="disk", filter_size=1 / 3, subtract_mean=True, zero_pad=True, copy=True): """Compute the complex field from a hologram using Fourier analysis Parameters ---------- hologram: real-valued 2d ndarray hologram data sideband: +1, -1,...
[ "def", "get_field", "(", "hologram", ",", "sideband", "=", "+", "1", ",", "filter_name", "=", "\"disk\"", ",", "filter_size", "=", "1", "/", "3", ",", "subtract_mean", "=", "True", ",", "zero_pad", "=", "True", ",", "copy", "=", "True", ")", ":", "if...
39.037594
0.000188
def get_maintainer(self): # type: () -> hdx.data.user.User """Get the dataset's maintainer. Returns: User: Dataset's maintainer """ return hdx.data.user.User.read_from_hdx(self.data['maintainer'], configuration=self.configuration)
[ "def", "get_maintainer", "(", "self", ")", ":", "# type: () -> hdx.data.user.User", "return", "hdx", ".", "data", ".", "user", ".", "User", ".", "read_from_hdx", "(", "self", ".", "data", "[", "'maintainer'", "]", ",", "configuration", "=", "self", ".", "con...
34.75
0.014035
def all_record_sets(self): """Generator to loop through current record set. Call next page if it exists. """ is_truncated = True start_record_name = None start_record_type = None kwargs = self.get_base_kwargs() while is_truncated: if start_rec...
[ "def", "all_record_sets", "(", "self", ")", ":", "is_truncated", "=", "True", "start_record_name", "=", "None", "start_record_type", "=", "None", "kwargs", "=", "self", ".", "get_base_kwargs", "(", ")", "while", "is_truncated", ":", "if", "start_record_name", "i...
36.26087
0.002336
def model_argmax(sess, x, predictions, samples, feed=None): """ Helper function that computes the current class prediction :param sess: TF session :param x: the input placeholder :param predictions: the model's symbolic output :param samples: numpy array with input samples (dims must match x) :param feed:...
[ "def", "model_argmax", "(", "sess", ",", "x", ",", "predictions", ",", "samples", ",", "feed", "=", "None", ")", ":", "feed_dict", "=", "{", "x", ":", "samples", "}", "if", "feed", "is", "not", "None", ":", "feed_dict", ".", "update", "(", "feed", ...
38.666667
0.008413
def listPrimaryDatasets(self, primary_ds_name="", primary_ds_type=""): """ Returns all primary dataset if primary_ds_name or primary_ds_type are not passed. """ conn = self.dbi.connection() try: result = self.primdslist.execute(conn, primary_ds_name, primary_ds_type) ...
[ "def", "listPrimaryDatasets", "(", "self", ",", "primary_ds_name", "=", "\"\"", ",", "primary_ds_type", "=", "\"\"", ")", ":", "conn", "=", "self", ".", "dbi", ".", "connection", "(", ")", "try", ":", "result", "=", "self", ".", "primdslist", ".", "execu...
36.25
0.011211
def export_dmg_by_event(ekey, dstore): """ :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object """ damage_dt = build_damage_dt(dstore, mean_std=False) dt_list = [('event_id', numpy.uint64), ('rlzi', numpy.uint16)] + [ (f, damage_dt.fields[f][0]) for ...
[ "def", "export_dmg_by_event", "(", "ekey", ",", "dstore", ")", ":", "damage_dt", "=", "build_damage_dt", "(", "dstore", ",", "mean_std", "=", "False", ")", "dt_list", "=", "[", "(", "'event_id'", ",", "numpy", ".", "uint64", ")", ",", "(", "'rlzi'", ",",...
45.875
0.00089
def _search_body(self, search_type, search_term, start, max_items): """Return the search XML body. :param search_type: The search type :type search_type: str :param search_term: The search term e.g. 'Jon Bon Jovi' :type search_term: str :param start: The start index of t...
[ "def", "_search_body", "(", "self", ",", "search_type", ",", "search_term", ",", "start", ",", "max_items", ")", ":", "xml", "=", "self", ".", "_base_body", "(", ")", "# Add the Body part", "XML", ".", "SubElement", "(", "xml", ",", "'s:Body'", ")", "item_...
34.4
0.001413
def _on_startup(self, *args): """ Called when the HTTP server start """ yield from Controller.instance().start() # Because with a large image collection # without md5sum already computed we start the # computing with server start asyncio.async(Qemu.instanc...
[ "def", "_on_startup", "(", "self", ",", "*", "args", ")", ":", "yield", "from", "Controller", ".", "instance", "(", ")", ".", "start", "(", ")", "# Because with a large image collection", "# without md5sum already computed we start the", "# computing with server start", ...
36.666667
0.008876
def downloaded(name, version=None, pkgs=None, fromrepo=None, ignore_epoch=None, **kwargs): ''' .. versionadded:: 2017.7.0 Ensure that the package is downloaded, and that it is the correct version (if specified). Currently s...
[ "def", "downloaded", "(", "name", ",", "version", "=", "None", ",", "pkgs", "=", "None", ",", "fromrepo", "=", "None", ",", "ignore_epoch", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":...
34.897436
0.000714
def _copy_cell_text(self): """ Copies the description of the selected message to the clipboard """ txt = self.currentItem().text() QtWidgets.QApplication.clipboard().setText(txt)
[ "def", "_copy_cell_text", "(", "self", ")", ":", "txt", "=", "self", ".", "currentItem", "(", ")", ".", "text", "(", ")", "QtWidgets", ".", "QApplication", ".", "clipboard", "(", ")", ".", "setText", "(", "txt", ")" ]
35.5
0.009174
def find(self, text): """ Return a list of genres found in text. """ genres = [] text = text.lower() category_counter = Counter() counter = Counter() for genre in self.db.genres: found = self.contains_entity(genre, text) if found...
[ "def", "find", "(", "self", ",", "text", ")", ":", "genres", "=", "[", "]", "text", "=", "text", ".", "lower", "(", ")", "category_counter", "=", "Counter", "(", ")", "counter", "=", "Counter", "(", ")", "for", "genre", "in", "self", ".", "db", "...
27.596491
0.001228
def ticket_form_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/ticket_forms#show-ticket-form" api_path = "/api/v2/ticket_forms/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
[ "def", "ticket_form_show", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/ticket_forms/{id}.json\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "self", ".", "call", "(", "api_pat...
53
0.011152
def template_remove(tr, template, cc_thresh, windowlength, interp_len, debug=0): """ Looks for instances of template in the trace and removes the matches. :type tr: obspy.core.trace.Trace :param tr: Trace to remove spikes from. :type template: osbpy.core.trace.Trace :param t...
[ "def", "template_remove", "(", "tr", ",", "template", ",", "cc_thresh", ",", "windowlength", ",", "interp_len", ",", "debug", "=", "0", ")", ":", "data_in", "=", "tr", ".", "copy", "(", ")", "_interp_len", "=", "int", "(", "tr", ".", "stats", ".", "s...
40.12
0.000487
def link(self, rel): """Look for link with specified rel, return else None.""" for link in self.ln: if ('rel' in link and link['rel'] == rel): return(link) return(None)
[ "def", "link", "(", "self", ",", "rel", ")", ":", "for", "link", "in", "self", ".", "ln", ":", "if", "(", "'rel'", "in", "link", "and", "link", "[", "'rel'", "]", "==", "rel", ")", ":", "return", "(", "link", ")", "return", "(", "None", ")" ]
33.428571
0.008333
def get_or_add_image(self, image_descriptor): """Return (rId, image) pair for image identified by *image_descriptor*. *rId* is the str key (often like "rId7") for the relationship between this story part and the image part, reused if already present, newly created if not. *image* is an ...
[ "def", "get_or_add_image", "(", "self", ",", "image_descriptor", ")", ":", "image_part", "=", "self", ".", "_package", ".", "get_or_add_image_part", "(", "image_descriptor", ")", "rId", "=", "self", ".", "relate_to", "(", "image_part", ",", "RT", ".", "IMAGE",...
53.909091
0.008292
def index_last(ol,value): ''' from elist.elist import * ol = [1,'a',3,'a',4,'a',5] index_last(ol,'a') ####lastIndexOf is the same as index_last lastIndexOf(ol,'a') ''' length = ol.__len__() for i in range(length-1,-1,-1): if(value == ol[i]): re...
[ "def", "index_last", "(", "ol", ",", "value", ")", ":", "length", "=", "ol", ".", "__len__", "(", ")", "for", "i", "in", "range", "(", "length", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "if", "(", "value", "==", "ol", "[", "i", "]"...
24.066667
0.010667
async def get_status_info(self) -> Tuple[str, str, int]: """Returns (NewConnectionStatus, NewLastConnectionError, NewUptime)""" return await self.gateway.commands.GetStatusInfo()
[ "async", "def", "get_status_info", "(", "self", ")", "->", "Tuple", "[", "str", ",", "str", ",", "int", "]", ":", "return", "await", "self", ".", "gateway", ".", "commands", ".", "GetStatusInfo", "(", ")" ]
64
0.010309
def stream_events(self, filter: Callable[[Event], bool] = None, *, max_queue_size: int = 0): """Shortcut for calling :func:`stream_events` with this signal in the first argument.""" return stream_events([self], filter, max_queue_size=max_queue_size)
[ "def", "stream_events", "(", "self", ",", "filter", ":", "Callable", "[", "[", "Event", "]", ",", "bool", "]", "=", "None", ",", "*", ",", "max_queue_size", ":", "int", "=", "0", ")", ":", "return", "stream_events", "(", "[", "self", "]", ",", "fil...
87.666667
0.015094
def get_compiler(self, using=None, connection=None): """ Overrides the Query method get_compiler in order to return an instance of the above custom compiler. """ # Copy the body of this method from Django except the final # return statement. We will ignore code coverage for t...
[ "def", "get_compiler", "(", "self", ",", "using", "=", "None", ",", "connection", "=", "None", ")", ":", "# Copy the body of this method from Django except the final", "# return statement. We will ignore code coverage for this.", "if", "using", "is", "None", "and", "connect...
52.1
0.001885
def parse_failed_targets(test_registry, junit_xml_path, error_handler): """Parses junit xml reports and maps targets to the set of individual tests that failed. Targets with no failed tests are omitted from the returned mapping and failed tests with no identifiable owning target are keyed under `None`. :param...
[ "def", "parse_failed_targets", "(", "test_registry", ",", "junit_xml_path", ",", "error_handler", ")", ":", "failed_targets", "=", "defaultdict", "(", "set", ")", "def", "parse_junit_xml_file", "(", "path", ")", ":", "try", ":", "xml", "=", "XmlParser", ".", "...
48.953488
0.010713
def policy_definition_delete(name, **kwargs): ''' .. versionadded:: 2019.2.0 Delete a policy definition. :param name: The name of the policy definition to delete. CLI Example: .. code-block:: bash salt-call azurearm_resource.policy_definition_delete testpolicy ''' result = ...
[ "def", "policy_definition_delete", "(", "name", ",", "*", "*", "kwargs", ")", ":", "result", "=", "False", "polconn", "=", "__utils__", "[", "'azurearm.get_client'", "]", "(", "'policy'", ",", "*", "*", "kwargs", ")", "try", ":", "# pylint: disable=unused-vari...
24.740741
0.001441
def get_cameras_rules(self): """Return the camera rules.""" resource = "rules" rules_event = self.publish_and_get_event(resource) if rules_event: return rules_event.get('properties') return None
[ "def", "get_cameras_rules", "(", "self", ")", ":", "resource", "=", "\"rules\"", "rules_event", "=", "self", ".", "publish_and_get_event", "(", "resource", ")", "if", "rules_event", ":", "return", "rules_event", ".", "get", "(", "'properties'", ")", "return", ...
30
0.008097
def get_stockprices(chart_range='1y'): ''' This is a proxy to the main fetch function to cache the result based on the chart range parameter. ''' all_symbols = list_symbols() @daily_cache(filename='iex_chart_{}'.format(chart_range)) def get_stockprices_cached(all_symbols): return _...
[ "def", "get_stockprices", "(", "chart_range", "=", "'1y'", ")", ":", "all_symbols", "=", "list_symbols", "(", ")", "@", "daily_cache", "(", "filename", "=", "'iex_chart_{}'", ".", "format", "(", "chart_range", ")", ")", "def", "get_stockprices_cached", "(", "a...
30.538462
0.002445
def get_multi_address(addresses, filter=None, limit=None, offset=None, api_code=None): """Get aggregate summary for multiple addresses including overall balance, per address balance and list of relevant transactions. :param tuple addresses: addresses(xpub or base58) to look up :param FilterType filter...
[ "def", "get_multi_address", "(", "addresses", ",", "filter", "=", "None", ",", "limit", "=", "None", ",", "offset", "=", "None", ",", "api_code", "=", "None", ")", ":", "if", "isinstance", "(", "addresses", ",", "basestring", ")", ":", "resource", "=", ...
43.866667
0.00223
def pop_one(self): """ NON-BLOCKING POP IN QUEUE, IF ANY """ with self.lock: if self.closed: return [THREAD_STOP] elif not self.queue: return None else: v =self.queue.pop() if v is THREAD_...
[ "def", "pop_one", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "closed", ":", "return", "[", "THREAD_STOP", "]", "elif", "not", "self", ".", "queue", ":", "return", "None", "else", ":", "v", "=", "self", ".", "queue",...
30.357143
0.009132
def start_manager(self): """ **Purpose**: Method to start the tmgr process. The tmgr function is not to be accessed directly. The function is started in a separate thread using this method. """ if not self._tmgr_process: try: self._prof.prof...
[ "def", "start_manager", "(", "self", ")", ":", "if", "not", "self", ".", "_tmgr_process", ":", "try", ":", "self", ".", "_prof", ".", "prof", "(", "'creating tmgr process'", ",", "uid", "=", "self", ".", "_uid", ")", "self", ".", "_tmgr_terminate", "=", ...
38.219512
0.001867
def get_samples(self, sample_count): """ Fetch a number of samples from self.wave_cache Args: sample_count (int): Number of samples to fetch Returns: ndarray """ if self.amplitude.value <= 0: return None # Build samples by rolling the per...
[ "def", "get_samples", "(", "self", ",", "sample_count", ")", ":", "if", "self", ".", "amplitude", ".", "value", "<=", "0", ":", "return", "None", "# Build samples by rolling the period cache through the buffer", "rolled_array", "=", "numpy", ".", "roll", "(", "sel...
44.48
0.001761
def _validate_geometry(self, geometry): """Validates geometry, raising error if invalid.""" if geometry is not None and geometry not in self.valid_geometries: raise InvalidParameterError("{} is not a valid geometry".format(geometry)) return geometry
[ "def", "_validate_geometry", "(", "self", ",", "geometry", ")", ":", "if", "geometry", "is", "not", "None", "and", "geometry", "not", "in", "self", ".", "valid_geometries", ":", "raise", "InvalidParameterError", "(", "\"{} is not a valid geometry\"", ".", "format"...
40.142857
0.010453
def ensemble_simulations( t, y0=None, volume=1.0, model=None, solver='ode', is_netfree=False, species_list=None, without_reset=False, return_type='matplotlib', opt_args=(), opt_kwargs=None, structures=None, rndseed=None, n=1, nproc=None, method=None, errorbar=True, **kwargs): """ Run sim...
[ "def", "ensemble_simulations", "(", "t", ",", "y0", "=", "None", ",", "volume", "=", "1.0", ",", "model", "=", "None", ",", "solver", "=", "'ode'", ",", "is_netfree", "=", "False", ",", "species_list", "=", "None", ",", "without_reset", "=", "False", "...
37.586592
0.002317
def extract_links_from_peer_assignment(self, element_id): """ Return a dictionary with links to supplement files (pdf, csv, zip, ipynb, html and so on) extracted from peer assignment. @param element_id: Element ID to extract files from. @type element_id: str @return: @s...
[ "def", "extract_links_from_peer_assignment", "(", "self", ",", "element_id", ")", ":", "logging", ".", "debug", "(", "'Gathering supplement URLs for element_id <%s>.'", ",", "element_id", ")", "try", ":", "# Assignment text (instructions) contains asset tags which describe", "#...
42.878788
0.001382
def InstallDriver(kext_path): """Calls into the IOKit to load a kext by file-system path. Apple kext API doco here: http://developer.apple.com/library/mac/#documentation/IOKit/Reference/ KextManager_header_reference/Reference/reference.html Args: kext_path: Absolute or relative POSIX path to the k...
[ "def", "InstallDriver", "(", "kext_path", ")", ":", "km", "=", "objc", ".", "KextManager", "(", ")", "cf_kext_path", "=", "km", ".", "PyStringToCFString", "(", "kext_path", ")", "kext_url", "=", "km", ".", "dll", ".", "CFURLCreateWithFileSystemPath", "(", "o...
33.541667
0.01087
def get_object(self, mpath, path=None, accept="*/*"): """GetObject https://apidocs.joyent.com/manta/api.html#GetObject @param mpath {str} Required. A manta path, e.g. '/trent/stor/myobj'. @param path {str} Optional. If given, the retrieved object will be written to the given...
[ "def", "get_object", "(", "self", ",", "mpath", ",", "path", "=", "None", ",", "accept", "=", "\"*/*\"", ")", ":", "res", ",", "content", "=", "self", ".", "get_object2", "(", "mpath", ",", "path", "=", "path", ",", "accept", "=", "accept", ")", "t...
41.714286
0.002232
def get_dependency_walker(): """ Checks if `depends.exe` is in the system PATH. If not, it will be downloaded and extracted to a temporary directory. Note that the file will not be deleted afterwards. Returns the path to the Dependency Walker executable. """ for dirname in os.getenv('PATH', '').split(os...
[ "def", "get_dependency_walker", "(", ")", ":", "for", "dirname", "in", "os", ".", "getenv", "(", "'PATH'", ",", "''", ")", ".", "split", "(", "os", ".", "pathsep", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "'de...
35.685714
0.011691
def copy(self, graph): """ Returns a copy of the layout for the given graph. """ l = self.__class__(graph, self.n) l.i = 0 return l
[ "def", "copy", "(", "self", ",", "graph", ")", ":", "l", "=", "self", ".", "__class__", "(", "graph", ",", "self", ".", "n", ")", "l", ".", "i", "=", "0", "return", "l" ]
22.75
0.026455
def UnlockEncryptedVolume( self, source_scanner_object, scan_context, locked_scan_node, credentials): """Unlocks an encrypted volume. This method can be used to prompt the user to provide encrypted volume credentials. Args: source_scanner_object (SourceScanner): source scanner. scan_...
[ "def", "UnlockEncryptedVolume", "(", "self", ",", "source_scanner_object", ",", "scan_context", ",", "locked_scan_node", ",", "credentials", ")", ":", "# TODO: print volume description.", "if", "locked_scan_node", ".", "type_indicator", "==", "(", "definitions", ".", "T...
35.035294
0.009471
def nslookup(host): ''' Query DNS for information about a domain or ip address CLI Example: .. code-block:: bash salt '*' network.nslookup archlinux.org ''' ret = [] addresses = [] cmd = ['nslookup', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, ...
[ "def", "nslookup", "(", "host", ")", ":", "ret", "=", "[", "]", "addresses", "=", "[", "]", "cmd", "=", "[", "'nslookup'", ",", "salt", ".", "utils", ".", "network", ".", "sanitize_host", "(", "host", ")", "]", "lines", "=", "__salt__", "[", "'cmd....
28.967742
0.001078
def assert_is_instance(obj, cls, msg_fmt="{msg}"): """Fail if an object is not an instance of a class or tuple of classes. >>> assert_is_instance(5, int) >>> assert_is_instance('foo', (str, bytes)) >>> assert_is_instance(5, str) Traceback (most recent call last): ... AssertionError: 5 i...
[ "def", "assert_is_instance", "(", "obj", ",", "cls", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "cls", ")", ":", "msg", "=", "\"{!r} is an instance of {!r}, expected {!r}\"", ".", "format", "(", "obj", ",", "obj",...
37.47619
0.001239
def ekgd(selidx, row, element): """ Return an element of an entry in a column of double precision type in a specified row. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekgd_c.html :param selidx: Index of parent column in SELECT clause. :type selidx: int :param row: Row to fetch ...
[ "def", "ekgd", "(", "selidx", ",", "row", ",", "element", ")", ":", "selidx", "=", "ctypes", ".", "c_int", "(", "selidx", ")", "row", "=", "ctypes", ".", "c_int", "(", "row", ")", "element", "=", "ctypes", ".", "c_int", "(", "element", ")", "ddata"...
34.111111
0.001056
def encryptMessage(self, message, ad = None): """ Encrypt a message using this double ratchet session. :param message: A bytes-like object encoding the message to encrypt. :param ad: A bytes-like object encoding the associated data to use for message authentication. Pass Non...
[ "def", "encryptMessage", "(", "self", ",", "message", ",", "ad", "=", "None", ")", ":", "if", "ad", "==", "None", ":", "ad", "=", "self", ".", "__ad", "# Prepare the header for this message", "header", "=", "Header", "(", "self", ".", "pub", ",", "self",...
37.121951
0.009603
def execute(self, conn, primary_ds_name="", primary_ds_type="", transaction=False): """ Lists all primary datasets if pattern is not provided. """ sql = self.sql binds = {} #import pdb #pdb.set_trace() if primary_ds_name and primary_ds_type in ('', None, ...
[ "def", "execute", "(", "self", ",", "conn", ",", "primary_ds_name", "=", "\"\"", ",", "primary_ds_type", "=", "\"\"", ",", "transaction", "=", "False", ")", ":", "sql", "=", "self", ".", "sql", "binds", "=", "{", "}", "#import pdb", "#pdb.set_trace()", "...
46.133333
0.008493
def append_string(t, string): """Append a string to a node, as text or tail of last child.""" node = t.tree if string: if len(node) == 0: if node.text is not None: node.text += string else: node.text = string else: # Get last child ...
[ "def", "append_string", "(", "t", ",", "string", ")", ":", "node", "=", "t", ".", "tree", "if", "string", ":", "if", "len", "(", "node", ")", "==", "0", ":", "if", "node", ".", "text", "is", "not", "None", ":", "node", ".", "text", "+=", "strin...
31.133333
0.002079
def find_field_by_label(browser, field_type, label): """ Locate the control input that has a label pointing to it. :param browser: ``world.browser`` :param string field_type: a field type (i.e. `button`) :param string label: label text This will first locate the label element that has a label ...
[ "def", "find_field_by_label", "(", "browser", ",", "field_type", ",", "label", ")", ":", "return", "ElementSelector", "(", "browser", ",", "xpath", "=", "field_xpath", "(", "field_type", ",", "'id'", ")", "%", "'//label[contains(., {0})]/@for'", ".", "format", "...
31.045455
0.00142
def time_zones_for_geographical_number(numobj): """Returns a list of time zones to which a phone number belongs. This method assumes the validity of the number passed in has already been checked, and that the number is geo-localizable. We consider fixed-line and mobile numbers possible candidates for g...
[ "def", "time_zones_for_geographical_number", "(", "numobj", ")", ":", "e164_num", "=", "format_number", "(", "numobj", ",", "PhoneNumberFormat", ".", "E164", ")", "if", "not", "e164_num", ".", "startswith", "(", "U_PLUS", ")", ":", "# pragma no cover", "# Can only...
48.913043
0.000872
def convert_world_to_phenotype(world): """ Converts sets indicating the resources present in a single cell to binary strings (bit order is based on the order of resources in world.resources). TODO: Figure out how to handle relationship between resources and tasks Inputs: world - an EnvironmentFile...
[ "def", "convert_world_to_phenotype", "(", "world", ")", ":", "if", "set", "(", "world", ".", "resources", ")", "!=", "set", "(", "world", ".", "tasks", ")", ":", "print", "(", "\"Warning: world phenotypes don't correspond to phenotypes\"", ")", "if", "set", "(",...
42.6
0.001148
def __get_button_events(self, state, timeval=None): """Get the button events from xinput.""" changed_buttons = self.__detect_button_events(state) events = self.__emulate_buttons(changed_buttons, timeval) return events
[ "def", "__get_button_events", "(", "self", ",", "state", ",", "timeval", "=", "None", ")", ":", "changed_buttons", "=", "self", ".", "__detect_button_events", "(", "state", ")", "events", "=", "self", ".", "__emulate_buttons", "(", "changed_buttons", ",", "tim...
49
0.008032
def _range(self, memory, addr, **kwargs): """ Gets the (min, max) range of solutions for an address. """ return (self._min(memory, addr, **kwargs), self._max(memory, addr, **kwargs))
[ "def", "_range", "(", "self", ",", "memory", ",", "addr", ",", "*", "*", "kwargs", ")", ":", "return", "(", "self", ".", "_min", "(", "memory", ",", "addr", ",", "*", "*", "kwargs", ")", ",", "self", ".", "_max", "(", "memory", ",", "addr", ","...
42
0.014019
def group_records_by_domain(self): """Return the records grouped by the domain they came from. The return value is a dict, a key in this dict is a domain and the value is a list of all the records with this domain. """ key_function = lambda record: record...
[ "def", "group_records_by_domain", "(", "self", ")", ":", "key_function", "=", "lambda", "record", ":", "record", ".", "source", ".", "domain", "return", "self", ".", "group_records", "(", "key_function", ")" ]
41.666667
0.013055
def namespace_to_taxon() -> Dict[str, Node]: """ namespace to taxon mapping """ human_taxon = Node( id='NCBITaxon:9606', label='Homo sapiens' ) return { 'MGI': Node( id='NCBITaxon:10090', label='Mus musculus' ), 'MONDO': human_tax...
[ "def", "namespace_to_taxon", "(", ")", "->", "Dict", "[", "str", ",", "Node", "]", ":", "human_taxon", "=", "Node", "(", "id", "=", "'NCBITaxon:9606'", ",", "label", "=", "'Homo sapiens'", ")", "return", "{", "'MGI'", ":", "Node", "(", "id", "=", "'NCB...
23.966667
0.001337
def r_edges(step): """Cell border. Args: step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData instance. Returns: tuple of :class:`numpy.array`: the position of the bottom and top walls of the cells. The two elements of the tuple are identical. """ rbo...
[ "def", "r_edges", "(", "step", ")", ":", "rbot", ",", "rtop", "=", "misc", ".", "get_rbounds", "(", "step", ")", "centers", "=", "step", ".", "rprof", ".", "loc", "[", ":", ",", "'r'", "]", ".", "values", "+", "rbot", "# assume walls are mid-way betwee...
34.555556
0.001565
def _evaluate_f(self, n, xdata, p=None): """ Evaluates a single function n for arbitrary xdata and p tuple. p=None means use the fit results """ # by default, use the fit values, otherwise, use the guess values. if p is None and self.results is not None: p = self.resul...
[ "def", "_evaluate_f", "(", "self", ",", "n", ",", "xdata", ",", "p", "=", "None", ")", ":", "# by default, use the fit values, otherwise, use the guess values.", "if", "p", "is", "None", "and", "self", ".", "results", "is", "not", "None", ":", "p", "=", "sel...
35.6
0.009124
def compare_bpdu_info(my_priority, my_times, rcv_priority, rcv_times): """ Check received BPDU is superior to currently held BPDU by the following comparison. - root bridge ID value - root path cost - designated bridge ID value - designated port I...
[ "def", "compare_bpdu_info", "(", "my_priority", ",", "my_times", ",", "rcv_priority", ",", "rcv_times", ")", ":", "if", "my_priority", "is", "None", ":", "result", "=", "SUPERIOR", "else", ":", "result", "=", "Stp", ".", "_cmp_value", "(", "rcv_priority", "....
46.176471
0.001248
def uninstall(pkg, dir=None, runas=None, env=None): ''' Uninstall an NPM package. If no directory is specified, the package will be uninstalled globally. pkg A package name in any format accepted by NPM dir The target directory from which to uninstall the package, or None for ...
[ "def", "uninstall", "(", "pkg", ",", "dir", "=", "None", ",", "runas", "=", "None", ",", "env", "=", "None", ")", ":", "# Protect against injection", "if", "pkg", ":", "pkg", "=", "_cmd_quote", "(", "pkg", ")", "env", "=", "env", "or", "{", "}", "i...
22.735849
0.001591
def write(name, values, tags={}, timestamp=None, database=None): """ Method to be called via threading module. """ point = { 'measurement': name, 'tags': tags, 'fields': values } if isinstance(timestamp, datetime): timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%SZ') ...
[ "def", "write", "(", "name", ",", "values", ",", "tags", "=", "{", "}", ",", "timestamp", "=", "None", ",", "database", "=", "None", ")", ":", "point", "=", "{", "'measurement'", ":", "name", ",", "'tags'", ":", "tags", ",", "'fields'", ":", "value...
31.210526
0.001637
def do_metric_create(mc, args): '''Create metric.''' fields = {} fields['name'] = args.name if args.dimensions: fields['dimensions'] = utils.format_parameters(args.dimensions) fields['timestamp'] = args.time fields['value'] = args.value if args.value_meta: fields['value_meta'...
[ "def", "do_metric_create", "(", "mc", ",", "args", ")", ":", "fields", "=", "{", "}", "fields", "[", "'name'", "]", "=", "args", ".", "name", "if", "args", ".", "dimensions", ":", "fields", "[", "'dimensions'", "]", "=", "utils", ".", "format_parameter...
36.111111
0.001499
def supports_currency_type(self, currency_type=None): """Tests if the given currency type is supported. arg: currency_type (osid.type.Type): a currency Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syntax is not...
[ "def", "supports_currency_type", "(", "self", ",", "currency_type", "=", "None", ")", ":", "# Implemented from template for osid.Metadata.supports_coordinate_type", "from", ".", "osid_errors", "import", "IllegalState", ",", "NullArgument", "if", "not", "currency_type", ":",...
48.166667
0.002262
def comma_list(cls, string): '''Convert a comma separated string to list.''' items = string.split(',') items = list([item.strip() for item in items]) return items
[ "def", "comma_list", "(", "cls", ",", "string", ")", ":", "items", "=", "string", ".", "split", "(", "','", ")", "items", "=", "list", "(", "[", "item", ".", "strip", "(", ")", "for", "item", "in", "items", "]", ")", "return", "items" ]
38
0.010309
def _trim_css_to_bounds(css, image_shape): """ Make sure a tuple in (top, right, bottom, left) order is within the bounds of the image. :param css: plain tuple representation of the rect in (top, right, bottom, left) order :param image_shape: numpy shape of the image array :return: a trimmed plain...
[ "def", "_trim_css_to_bounds", "(", "css", ",", "image_shape", ")", ":", "return", "max", "(", "css", "[", "0", "]", ",", "0", ")", ",", "min", "(", "css", "[", "1", "]", ",", "image_shape", "[", "1", "]", ")", ",", "min", "(", "css", "[", "2", ...
54.333333
0.01006
def ensure_local_space(hs, cls=LocalSpace): """Ensure that the given `hs` is an instance of :class:`LocalSpace`. If `hs` an instance of :class:`str` or :class:`int`, it will be converted to a `cls` (if possible). If it already is an instace of `cls`, `hs` will be returned unchanged. Args: ...
[ "def", "ensure_local_space", "(", "hs", ",", "cls", "=", "LocalSpace", ")", ":", "if", "isinstance", "(", "hs", ",", "(", "str", ",", "int", ")", ")", ":", "try", ":", "hs", "=", "cls", "(", "hs", ")", "except", "TypeError", "as", "exc_info", ":", ...
36.434783
0.000581
def ding0_exemplary_plots(stats, base_path=BASEPATH): """ Analyze multiple grid district data generated with Ding0. Parameters ---------- stats : pandas.DataFrame Statistics of each MV grid districts base_path : str Root directory of Ding0 data structure, i.e. '~/.ding0' (which ...
[ "def", "ding0_exemplary_plots", "(", "stats", ",", "base_path", "=", "BASEPATH", ")", ":", "# make some plot", "plotpath", "=", "os", ".", "path", ".", "join", "(", "base_path", ",", "'plots'", ")", "results", ".", "plot_cable_length", "(", "stats", ",", "pl...
26.6
0.001815
def newton_secant(func, x0, args=(), tol=1.48e-8, maxiter=50, disp=True): """ Find a zero from the secant method using the jitted version of Scipy's secant method. Note that `func` must be jitted via Numba. Parameters ---------- func : callable and jitted The func...
[ "def", "newton_secant", "(", "func", ",", "x0", ",", "args", "=", "(", ")", ",", "tol", "=", "1.48e-8", ",", "maxiter", "=", "50", ",", "disp", "=", "True", ")", ":", "if", "tol", "<=", "0", ":", "raise", "ValueError", "(", "\"tol is too small <= 0\"...
29.858974
0.000416