text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def quote_split(sep,string): """ Splits the strings into pieces divided by sep, when sep in not inside quotes. """ if len(sep) != 1: raise Exception("Separation string must be one character long") retlist = [] squote = False dquote = False left = 0 i = 0 while i < len(string): ...
[ "def", "quote_split", "(", "sep", ",", "string", ")", ":", "if", "len", "(", "sep", ")", "!=", "1", ":", "raise", "Exception", "(", "\"Separation string must be one character long\"", ")", "retlist", "=", "[", "]", "squote", "=", "False", "dquote", "=", "F...
31.16129
16.903226
def bold(s, *, escape=True): r"""Make a string appear bold in LaTeX formatting. bold() wraps a given string in the LaTeX command \textbf{}. Args ---- s : str The string to be formatted. escape: bool If true the bold text will be escaped Returns ------- NoEscape ...
[ "def", "bold", "(", "s", ",", "*", ",", "escape", "=", "True", ")", ":", "if", "escape", ":", "s", "=", "escape_latex", "(", "s", ")", "return", "NoEscape", "(", "r'\\textbf{'", "+", "s", "+", "'}'", ")" ]
18.37931
23.034483
def _mkpda(self, nonterms, productions, productions_struct, terminals, splitstring=1): """ This function generates a PDA from a CNF grammar as described in: - http://www.oit.edu/faculty/sherry.yang/CST229/Lectures/7_pda.pdf - http://www.eng.utah.edu/~cs3100/lectures/l18/pda-notes.p...
[ "def", "_mkpda", "(", "self", ",", "nonterms", ",", "productions", ",", "productions_struct", ",", "terminals", ",", "splitstring", "=", "1", ")", ":", "pda", "=", "PDA", "(", "self", ".", "alphabet", ")", "pda", ".", "nonterminals", "=", "nonterms", "pd...
41.097902
19.307692
def selection_val(traj_exp,adj_mat): ''' Function returns an ndarray of ratios calculated by dividing the summed neighborhood variances by the global variance :param traj_exp: ndarray representing gene expression :param adj_mat: ndarray representing the calculated adjacency matrix :return val: ndarr...
[ "def", "selection_val", "(", "traj_exp", ",", "adj_mat", ")", ":", "r", "=", "traj_exp", ".", "shape", "[", "0", "]", "#keep track of the rows", "c", "=", "traj_exp", ".", "shape", "[", "1", "]", "#keep track of the columns", "k", "=", "np", ".", "sum", ...
66.62069
35.103448
def tags(self, name=None) -> List['Tag']: """Return all tags with the given name.""" lststr = self._lststr type_to_spans = self._type_to_spans if name: if name in _tag_extensions: string = lststr[0] return [ Tag(lststr, type...
[ "def", "tags", "(", "self", ",", "name", "=", "None", ")", "->", "List", "[", "'Tag'", "]", ":", "lststr", "=", "self", ".", "_lststr", "type_to_spans", "=", "self", ".", "_type_to_spans", "if", "name", ":", "if", "name", "in", "_tag_extensions", ":", ...
43.666667
14.304348
def exec_command(self, cmd, tmp_path, sudo_user,sudoable=False, executable='/bin/sh'): ''' run a command on the remote host ''' ssh_cmd = self._password_cmd() ssh_cmd += ["ssh", "-tt", "-q"] + self.common_args + [self.host] if not self.runner.sudo or not sudoable: if execut...
[ "def", "exec_command", "(", "self", ",", "cmd", ",", "tmp_path", ",", "sudo_user", ",", "sudoable", "=", "False", ",", "executable", "=", "'/bin/sh'", ")", ":", "ssh_cmd", "=", "self", ".", "_password_cmd", "(", ")", "ssh_cmd", "+=", "[", "\"ssh\"", ",",...
44.931507
24.986301
def handle_trial_end(self, data): """ data: it has three keys: trial_job_id, event, hyper_params - trial_job_id: the id generated by training service - event: the job's state - hyper_params: the hyperparameters generated and returned by tuner """ tr...
[ "def", "handle_trial_end", "(", "self", ",", "data", ")", ":", "trial_job_id", "=", "data", "[", "'trial_job_id'", "]", "_ended_trials", ".", "add", "(", "trial_job_id", ")", "if", "trial_job_id", "in", "_trial_history", ":", "_trial_history", ".", "pop", "(",...
49.866667
16
def _get_local_folder(self, root=None): """Return local NApp root folder. Search for kytos.json in _./_ folder and _./user/napp_. Args: root (pathlib.Path): Where to begin searching. Return: pathlib.Path: NApp root folder. Raises: FileNotFo...
[ "def", "_get_local_folder", "(", "self", ",", "root", "=", "None", ")", ":", "if", "root", "is", "None", ":", "root", "=", "Path", "(", ")", "for", "folders", "in", "[", "'.'", "]", ",", "[", "self", ".", "user", ",", "self", ".", "napp", "]", ...
37.214286
20.642857
def agents(status, all): ''' List and manage agents. (admin privilege required) ''' fields = [ ('ID', 'id'), ('Status', 'status'), ('Region', 'region'), ('First Contact', 'first_contact'), ('CPU Usage (%)', 'cpu_cur_pct'), ('Used Memory (MiB)', 'mem_cu...
[ "def", "agents", "(", "status", ",", "all", ")", ":", "fields", "=", "[", "(", "'ID'", ",", "'id'", ")", ",", "(", "'Status'", ",", "'status'", ")", ",", "(", "'Region'", ",", "'region'", ")", ",", "(", "'First Contact'", ",", "'first_contact'", ")",...
34.78481
17.924051
def get_data_frame_transform(self, transform_id=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/get-data-frame-transform.html>`_ :arg transform_id: The id or comma delimited list of id expressions of the transforms to get, '_all' or '*' impl...
[ "def", "get_data_frame_transform", "(", "self", ",", "transform_id", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "\"_data_frame\"", ",", "\"transforms\"", ...
53.25
29.916667
def respond_via_request(self, task): """ Handle response after 55 second. :param task: :return: """ warn(f"Detected slow response into webhook. " f"(Greater than {RESPONSE_TIMEOUT} seconds)\n" f"Recommended to use 'async_task' decorator from Dis...
[ "def", "respond_via_request", "(", "self", ",", "task", ")", ":", "warn", "(", "f\"Detected slow response into webhook. \"", "f\"(Greater than {RESPONSE_TIMEOUT} seconds)\\n\"", "f\"Recommended to use 'async_task' decorator from Dispatcher for handler with long timeouts.\"", ",", "Timeou...
35
20.333333
def join(self, join_streamlet, window_config, join_function): """Return a new Streamlet by joining join_streamlet with this streamlet """ from heronpy.streamlet.impl.joinbolt import JoinStreamlet, JoinBolt join_streamlet_result = JoinStreamlet(JoinBolt.INNER, window_config, ...
[ "def", "join", "(", "self", ",", "join_streamlet", ",", "window_config", ",", "join_function", ")", ":", "from", "heronpy", ".", "streamlet", ".", "impl", ".", "joinbolt", "import", "JoinStreamlet", ",", "JoinBolt", "join_streamlet_result", "=", "JoinStreamlet", ...
54.444444
16
def subsample(self, factor): """ Downsample images by an integer factor. Parameters ---------- factor : positive int or tuple of positive ints Stride to use in subsampling. If a single int is passed, each dimension of the image will be downsampled by this...
[ "def", "subsample", "(", "self", ",", "factor", ")", ":", "value_shape", "=", "self", ".", "value_shape", "ndims", "=", "len", "(", "value_shape", ")", "if", "not", "hasattr", "(", "factor", ",", "'__len__'", ")", ":", "factor", "=", "[", "factor", "]"...
38.703704
22.185185
def featurizer(topfile): r""" Featurizer to select features from MD data. Parameters ---------- topfile : str or mdtraj.Topology instance path to topology file (e.g pdb file) or a mdtraj.Topology object Returns ------- feat : :class:`Featurizer <pyemma.coordinates.data.featurizatio...
[ "def", "featurizer", "(", "topfile", ")", ":", "from", "pyemma", ".", "coordinates", ".", "data", ".", "featurization", ".", "featurizer", "import", "MDFeaturizer", "return", "MDFeaturizer", "(", "topfile", ")" ]
32.340909
29.636364
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
25.692308
def get_model_file(name, root=os.path.join(base.data_dir(), 'models')): r"""Return location for the pretrained on local file system. This function will download from online model zoo when model cannot be found or has mismatch. The root directory will be created if it doesn't exist. Parameters ----...
[ "def", "get_model_file", "(", "name", ",", "root", "=", "os", ".", "path", ".", "join", "(", "base", ".", "data_dir", "(", ")", ",", "'models'", ")", ")", ":", "file_name", "=", "'{name}-{short_hash}'", ".", "format", "(", "name", "=", "name", ",", "...
35.145833
21.791667
def get_num_gpu(): """ Returns: int: #available GPUs in CUDA_VISIBLE_DEVICES, or in the system. """ def warn_return(ret, message): try: import tensorflow as tf except ImportError: return ret built_with_cuda = tf.test.is_built_with_cuda() ...
[ "def", "get_num_gpu", "(", ")", ":", "def", "warn_return", "(", "ret", ",", "message", ")", ":", "try", ":", "import", "tensorflow", "as", "tf", "except", "ImportError", ":", "return", "ret", "built_with_cuda", "=", "tf", ".", "test", ".", "is_built_with_c...
38.697674
22.976744
def _write(self, text): """Write text by respecting the current indentlevel""" spaces = ' ' * (self.indent * self.indentlevel) t = spaces + text.strip() + '\n' if hasattr(t, 'encode'): t = t.encode(self.encoding, 'xmlcharrefreplace') self.stream.write(t)
[ "def", "_write", "(", "self", ",", "text", ")", ":", "spaces", "=", "' '", "*", "(", "self", ".", "indent", "*", "self", ".", "indentlevel", ")", "t", "=", "spaces", "+", "text", ".", "strip", "(", ")", "+", "'\\n'", "if", "hasattr", "(", "t", ...
42.857143
10.285714
def logical_raid_levels(self): """Gets the raid level for each logical volume :returns the set of list of raid levels configured """ lg_raid_lvls = set() for member in self.get_members(): lg_raid_lvls.update(member.logical_drives.logical_raid_levels) return l...
[ "def", "logical_raid_levels", "(", "self", ")", ":", "lg_raid_lvls", "=", "set", "(", ")", "for", "member", "in", "self", ".", "get_members", "(", ")", ":", "lg_raid_lvls", ".", "update", "(", "member", ".", "logical_drives", ".", "logical_raid_levels", ")",...
35.888889
14.222222
def delete(key, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the cache service ''' key, profile = _parse_key(key, profile) cache = salt.cache.Cache(__opts__) try: cache.flush(profile['bank'], key=key) return True except Exception: return ...
[ "def", "delete", "(", "key", ",", "service", "=", "None", ",", "profile", "=", "None", ")", ":", "# pylint: disable=W0613", "key", ",", "profile", "=", "_parse_key", "(", "key", ",", "profile", ")", "cache", "=", "salt", ".", "cache", ".", "Cache", "("...
28.636364
18.090909
def do_request(self, request, proxies, timeout, **_): """Dispatch the actual request and return the result.""" print('{0} {1}'.format(request.method, request.url)) response = self.http.send(request, proxies=proxies, timeout=timeout, allow_redirects=False) ...
[ "def", "do_request", "(", "self", ",", "request", ",", "proxies", ",", "timeout", ",", "*", "*", "_", ")", ":", "print", "(", "'{0} {1}'", ".", "format", "(", "request", ".", "method", ",", "request", ".", "url", ")", ")", "response", "=", "self", ...
54
15.428571
def discard(self, interval): """ Removes an interval from the tree, if present. If not, does nothing. Completes in O(log n) time. """ if interval not in self: return self.all_intervals.discard(interval) self.top_node = self.top_node.discard(in...
[ "def", "discard", "(", "self", ",", "interval", ")", ":", "if", "interval", "not", "in", "self", ":", "return", "self", ".", "all_intervals", ".", "discard", "(", "interval", ")", "self", ".", "top_node", "=", "self", ".", "top_node", ".", "discard", "...
29.833333
13.166667
def import_project_sitetree_modules(): """Imports sitetrees modules from packages (apps). Returns a list of submodules. :rtype: list """ from django.conf import settings as django_settings submodules = [] for app in django_settings.INSTALLED_APPS: module = import_app_sitetree_module...
[ "def", "import_project_sitetree_modules", "(", ")", ":", "from", "django", ".", "conf", "import", "settings", "as", "django_settings", "submodules", "=", "[", "]", "for", "app", "in", "django_settings", ".", "INSTALLED_APPS", ":", "module", "=", "import_app_sitetr...
31.076923
11.923077
async def hmset(self, name, mapping): """ Set key to value within hash ``name`` for each corresponding key and value from the ``mapping`` dict. """ if not mapping: raise DataError("'hmset' with 'mapping' of length 0") items = [] for pair in iteritems(m...
[ "async", "def", "hmset", "(", "self", ",", "name", ",", "mapping", ")", ":", "if", "not", "mapping", ":", "raise", "DataError", "(", "\"'hmset' with 'mapping' of length 0\"", ")", "items", "=", "[", "]", "for", "pair", "in", "iteritems", "(", "mapping", ")...
37.636364
12.545455
def create_additional_charge(self, *, subscription_id, description, plan_value, plan_tax, plan_tax_return_base, currency): """ Adds extra charges to the respective invoice for the current period. Args: subscription_id: Identification of the subscript...
[ "def", "create_additional_charge", "(", "self", ",", "*", ",", "subscription_id", ",", "description", ",", "plan_value", ",", "plan_tax", ",", "plan_tax_return_base", ",", "currency", ")", ":", "payload", "=", "{", "\"description\"", ":", "description", ",", "\"...
32.289474
18.815789
def handle(self, data, source = None): """Given OSC data, tries to call the callback with the right address.""" decoded = decodeOSC(data) self.dispatch(decoded, source)
[ "def", "handle", "(", "self", ",", "data", ",", "source", "=", "None", ")", ":", "decoded", "=", "decodeOSC", "(", "data", ")", "self", ".", "dispatch", "(", "decoded", ",", "source", ")" ]
39.2
2.2
def __print_namespace_help(self, session, namespace, cmd_name=None): """ Prints the documentation of all the commands in the given name space, or only of the given command :param session: Session Handler :param namespace: Name space of the command :param cmd_name: Name o...
[ "def", "__print_namespace_help", "(", "self", ",", "session", ",", "namespace", ",", "cmd_name", "=", "None", ")", ":", "session", ".", "write_line", "(", "\"=== Name space '{0}' ===\"", ",", "namespace", ")", "# Get all commands in this name space", "if", "cmd_name",...
34.5
18.423077
def link_set(self, rel, href, allow_duplicates=False, **atts): """Set/create link with specified rel, set href and any other attributes. Any link element must have both rel and href values, the specification also defines the type attributes and others are permitted also. See description...
[ "def", "link_set", "(", "self", ",", "rel", ",", "href", ",", "allow_duplicates", "=", "False", ",", "*", "*", "atts", ")", ":", "if", "(", "self", ".", "ln", "is", "None", ")", ":", "# automagically create a self.ln list", "self", ".", "ln", "=", "[",...
36.962963
17.62963
def call(__self, __context, __obj, *args, **kwargs): """Call an object from sandboxed code.""" fmt = inspect_format_method(__obj) if fmt is not None: return __self.format_string(fmt, args, kwargs) # the double prefixes are to avoid double keyword argument # errors wh...
[ "def", "call", "(", "__self", ",", "__context", ",", "__obj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "fmt", "=", "inspect_format_method", "(", "__obj", ")", "if", "fmt", "is", "not", "None", ":", "return", "__self", ".", "format_string", ...
45.818182
14.636364
def starmap(source, func, ordered=True, task_limit=None): """Apply a given function to the unpacked elements of an asynchronous sequence. Each element is unpacked before applying the function. The given function can either be synchronous or asynchronous. The results can either be returned in or ou...
[ "def", "starmap", "(", "source", ",", "func", ",", "ordered", "=", "True", ",", "task_limit", "=", "None", ")", ":", "if", "asyncio", ".", "iscoroutinefunction", "(", "func", ")", ":", "async", "def", "starfunc", "(", "args", ")", ":", "return", "await...
41.26087
20.826087
def scan_timestamp(self, tbuf): '''scan forward looking in a tlog for a timestamp in a reasonable range''' while True: (tusec,) = struct.unpack('>Q', tbuf) t = tusec * 1.0e-6 if abs(t - self._last_timestamp) <= 3*24*60*60: break c = self.f....
[ "def", "scan_timestamp", "(", "self", ",", "tbuf", ")", ":", "while", "True", ":", "(", "tusec", ",", ")", "=", "struct", ".", "unpack", "(", "'>Q'", ",", "tbuf", ")", "t", "=", "tusec", "*", "1.0e-6", "if", "abs", "(", "t", "-", "self", ".", "...
34.583333
16.916667
def attrlist(self): 'Transform the KEY_MAP paramiter into an attrlist for ldap filters' keymap = self.config.get('KEY_MAP') if keymap: # https://github.com/ContinuumIO/flask-ldap-login/issues/11 # https://continuumsupport.zendesk.com/agent/tickets/393 return [...
[ "def", "attrlist", "(", "self", ")", ":", "keymap", "=", "self", ".", "config", ".", "get", "(", "'KEY_MAP'", ")", "if", "keymap", ":", "# https://github.com/ContinuumIO/flask-ldap-login/issues/11", "# https://continuumsupport.zendesk.com/agent/tickets/393", "return", "["...
43.666667
23
def retyped(self, new_type): """Returns a new node with the same contents as self, but with a new node_type.""" return ParseNode(new_type, children=list(self.children), consumed=self.consumed, position=self.position, ignored...
[ "def", "retyped", "(", "self", ",", "new_type", ")", ":", "return", "ParseNode", "(", "new_type", ",", "children", "=", "list", "(", "self", ".", "children", ")", ",", "consumed", "=", "self", ".", "consumed", ",", "position", "=", "self", ".", "positi...
46.857143
6.571429
def index(self, sub_category): """ The offset of *sub_category* in the overall sequence of leaf categories. """ index = self._parent.index(self) for this_sub_category in self._sub_categories: if sub_category is this_sub_category: return index ...
[ "def", "index", "(", "self", ",", "sub_category", ")", ":", "index", "=", "self", ".", "_parent", ".", "index", "(", "self", ")", "for", "this_sub_category", "in", "self", ".", "_sub_categories", ":", "if", "sub_category", "is", "this_sub_category", ":", "...
38.181818
11.272727
def summary(args): """ %prog summary gffile fastafile Print summary stats, including: - Gene/Exon/Intron - Number - Average size (bp) - Median size (bp) - Total length (Mb) - % of genome - % GC """ p = OptionParser(summary.__doc__) opts, args = p.parse_args(args) ...
[ "def", "summary", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "summary", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "2", ":", "sys", ".", "exit", "(", ...
34.52
17.96
def from_array(array): """ Deserialize a new ChatActionMessage from a given dictionary. :return: new ChatActionMessage instance. :rtype: ChatActionMessage """ if array is None or not array: return None # end if assert_type_or_raise(array, dict...
[ "def", "from_array", "(", "array", ")", ":", "if", "array", "is", "None", "or", "not", "array", ":", "return", "None", "# end if", "assert_type_or_raise", "(", "array", ",", "dict", ",", "parameter_name", "=", "\"array\"", ")", "data", "=", "{", "}", "da...
36.423077
16.115385
def pre_save(self, model_instance, add): """Generate ID if required.""" value = super(AleaIdField, self).pre_save(model_instance, add) if (not value) and self.default in (meteor_random_id, NOT_PROVIDED): value = self.get_seeded_value(model_instance) setattr(model_instance...
[ "def", "pre_save", "(", "self", ",", "model_instance", ",", "add", ")", ":", "value", "=", "super", "(", "AleaIdField", ",", "self", ")", ".", "pre_save", "(", "model_instance", ",", "add", ")", "if", "(", "not", "value", ")", "and", "self", ".", "de...
51
17
def add(self, paths, **params): """ Add a path (or list of paths) to the list of paths being watched. The 'missing' setting for a file can also be changed by re-adding the file. """ log = self._getparam('log', self._discard, **params) missing = self._getparam('missin...
[ "def", "add", "(", "self", ",", "paths", ",", "*", "*", "params", ")", ":", "log", "=", "self", ".", "_getparam", "(", "'log'", ",", "self", ".", "_discard", ",", "*", "*", "params", ")", "missing", "=", "self", ".", "_getparam", "(", "'missing'", ...
38.785714
16.357143
def _calculate_expires(self): """Calculates the session expiry using the timeout""" self._backend_client.expires = None now = datetime.utcnow() self._backend_client.expires = now + timedelta(seconds=self._config.timeout)
[ "def", "_calculate_expires", "(", "self", ")", ":", "self", ".", "_backend_client", ".", "expires", "=", "None", "now", "=", "datetime", ".", "utcnow", "(", ")", "self", ".", "_backend_client", ".", "expires", "=", "now", "+", "timedelta", "(", "seconds", ...
41.333333
17.833333
def location(self): """ The location for this engine. May be None if no specific location has been assigned. :param value: location to assign engine. Can be name, str href, or Location element. If name, it will be automatically created if a Location with the same...
[ "def", "location", "(", "self", ")", ":", "location", "=", "Element", ".", "from_href", "(", "self", ".", "location_ref", ")", "if", "location", "and", "location", ".", "name", "==", "'Default'", ":", "return", "None", "return", "location" ]
39.933333
17.133333
def get_eci_assignment_number(encoding): """\ Returns the ECI number for the provided encoding. :param str encoding: A encoding name :return str: The ECI number. """ try: return consts.ECI_ASSIGNMENT_NUM[codecs.lookup(encoding).name] except KeyError: raise QRCodeError('Unkno...
[ "def", "get_eci_assignment_number", "(", "encoding", ")", ":", "try", ":", "return", "consts", ".", "ECI_ASSIGNMENT_NUM", "[", "codecs", ".", "lookup", "(", "encoding", ")", ".", "name", "]", "except", "KeyError", ":", "raise", "QRCodeError", "(", "'Unknown EC...
33.25
15.333333
def delete_record_translations(cr, module, xml_ids): """Cleanup translations of specific records in a module. :param module: module name :param xml_ids: a tuple or list of xml record IDs """ if not isinstance(xml_ids, (list, tuple)): do_raise("XML IDs %s must be a tuple or list!" % (xml_ids...
[ "def", "delete_record_translations", "(", "cr", ",", "module", ",", "xml_ids", ")", ":", "if", "not", "isinstance", "(", "xml_ids", ",", "(", "list", ",", "tuple", ")", ")", ":", "do_raise", "(", "\"XML IDs %s must be a tuple or list!\"", "%", "(", "xml_ids", ...
34.45
11.75
def find_single_file_project(self): # type: () -> List[str] """ Take first non-setup.py python file. What a mess. :return: """ # TODO: use package_dirs packaged_dirs = "" try: # Right now only returns 1st. packaged_dirs = self.extract_pack...
[ "def", "find_single_file_project", "(", "self", ")", ":", "# type: () -> List[str]", "# TODO: use package_dirs", "packaged_dirs", "=", "\"\"", "try", ":", "# Right now only returns 1st.", "packaged_dirs", "=", "self", ".", "extract_package_dir", "(", ")", "except", ":", ...
35.588235
14.941176
def _pystmark_call(self, method, *args, **kwargs): ''' Wraps a call to the pystmark Simple API, adding configured settings ''' kwargs = self._apply_config(**kwargs) return method(*args, **kwargs)
[ "def", "_pystmark_call", "(", "self", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "self", ".", "_apply_config", "(", "*", "*", "kwargs", ")", "return", "method", "(", "*", "args", ",", "*", "*", "kwargs", ")" ...
38.333333
16.666667
def to_dict(self): """Return the resource as a dictionary. :rtype: dict """ result_dict = {} for column in self.__table__.columns.keys(): # pylint: disable=no-member value = result_dict[column] = getattr(self, column, None) if isinstance(value, Decimal):...
[ "def", "to_dict", "(", "self", ")", ":", "result_dict", "=", "{", "}", "for", "column", "in", "self", ".", "__table__", ".", "columns", ".", "keys", "(", ")", ":", "# pylint: disable=no-member", "value", "=", "result_dict", "[", "column", "]", "=", "geta...
39.307692
18.230769
def get_idxs(exprs): """ Finds sympy.tensor.indexed.Idx instances and returns them. """ idxs = set() for expr in (exprs): for i in expr.find(sympy.Idx): idxs.add(i) return sorted(idxs, key=str)
[ "def", "get_idxs", "(", "exprs", ")", ":", "idxs", "=", "set", "(", ")", "for", "expr", "in", "(", "exprs", ")", ":", "for", "i", "in", "expr", ".", "find", "(", "sympy", ".", "Idx", ")", ":", "idxs", ".", "add", "(", "i", ")", "return", "sor...
25.444444
12.111111
def _fetch_access_token(self, url, data): """ The real fetch access token """ logger.info('Fetching component access token') res = self._http.post( url=url, data=data ) try: res.raise_for_status() except requests.RequestException as req...
[ "def", "_fetch_access_token", "(", "self", ",", "url", ",", "data", ")", ":", "logger", ".", "info", "(", "'Fetching component access token'", ")", "res", "=", "self", ".", "_http", ".", "post", "(", "url", "=", "url", ",", "data", "=", "data", ")", "t...
30.837838
12.864865
def send_wpa_enc(self, data, iv, seqnum, dest, mic_key, key_idx=0, additionnal_flag=["from-DS"], encrypt_key=None): """Send an encrypted packet with content @data, using IV @iv, sequence number @seqnum, MIC key @mic_key """ if encrypt_key is Non...
[ "def", "send_wpa_enc", "(", "self", ",", "data", ",", "iv", ",", "seqnum", ",", "dest", ",", "mic_key", ",", "key_idx", "=", "0", ",", "additionnal_flag", "=", "[", "\"from-DS\"", "]", ",", "encrypt_key", "=", "None", ")", ":", "if", "encrypt_key", "is...
31.225806
20.193548
def set_consumer_offsets( kafka_client, group, new_offsets, raise_on_error=True, ): """Set consumer offsets to the specified offsets. This method does not validate the specified offsets, it is up to the caller to specify valid offsets within a topic partition. If any partition leader i...
[ "def", "set_consumer_offsets", "(", "kafka_client", ",", "group", ",", "new_offsets", ",", "raise_on_error", "=", "True", ",", ")", ":", "valid_new_offsets", "=", "_verify_commit_offsets_requests", "(", "kafka_client", ",", "new_offsets", ",", "raise_on_error", ")", ...
31.125
23.03125
def options(self): """ Engine options discover HTTP entry point """ #configure engine with an empty dict to ensure default selection/options self.engine.configure({}) conf = self.engine.as_dict() conf["returns"] = [oname for oname in six.iterkeys(self._outputs)] #...
[ "def", "options", "(", "self", ")", ":", "#configure engine with an empty dict to ensure default selection/options", "self", ".", "engine", ".", "configure", "(", "{", "}", ")", "conf", "=", "self", ".", "engine", ".", "as_dict", "(", ")", "conf", "[", "\"return...
48.6
19.3
def infer_slice(node, context=None): """Understand `slice` calls.""" args = node.args if not 0 < len(args) <= 3: raise UseInferenceDefault infer_func = partial(helpers.safe_infer, context=context) args = [infer_func(arg) for arg in args] for arg in args: if not arg or arg is uti...
[ "def", "infer_slice", "(", "node", ",", "context", "=", "None", ")", ":", "args", "=", "node", ".", "args", "if", "not", "0", "<", "len", "(", "args", ")", "<=", "3", ":", "raise", "UseInferenceDefault", "infer_func", "=", "partial", "(", "helpers", ...
32.04
14.96
def share(self, base=None, keys=None, by=None, **kwargs): """ Share the formatoptions of one plotter with all the others This method shares specified formatoptions from `base` with all the plotters in this instance. Parameters ---------- base: None, Plotter, xar...
[ "def", "share", "(", "self", ",", "base", "=", "None", ",", "keys", "=", "None", ",", "by", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "by", "is", "not", "None", ":", "if", "base", "is", "not", "None", ":", "if", "hasattr", "(", "b...
43.732143
18.75
def main(self): ''' Responsible for calling self.init, initializing self.config.display, and calling self.run. Returns the value returned from self.run. ''' self.status = self.parent.status self.modules = self.parent.executed_modules # A special exception for th...
[ "def", "main", "(", "self", ")", ":", "self", ".", "status", "=", "self", ".", "parent", ".", "status", "self", ".", "modules", "=", "self", ".", "parent", ".", "executed_modules", "# A special exception for the extractor module, which should be allowed to", "# over...
29.52
23.12
def get_documented_add(self, record_descriptors): """ this hack is used to document add function a methods __doc__ attribute is read-only (or must use metaclasses, what I certainly don't want to do...) we therefore create a function (who's __doc__ attribute is read/write), and will bind it to Table in _...
[ "def", "get_documented_add", "(", "self", ",", "record_descriptors", ")", ":", "def", "add", "(", "data", "=", "None", ",", "*", "*", "or_data", ")", ":", "\"\"\"\n Parameters\n ----------\n data: dictionary containing field lowercase names or index as ke...
38.333333
26.75
def createSuperimposedSensorySDRs(sequenceSensations, objectSensations): """ Given two lists of sensations, create a new list where the sensory SDRs are union of the individual sensory SDRs. Keep the location SDRs from the object. A list of sensations has the following format: [ { 0: (set([1, 5, 10...
[ "def", "createSuperimposedSensorySDRs", "(", "sequenceSensations", ",", "objectSensations", ")", ":", "assert", "len", "(", "sequenceSensations", ")", "==", "len", "(", "objectSensations", ")", "superimposedSensations", "=", "[", "]", "for", "i", ",", "objectSensati...
30.95122
24.804878
def get_ops_hashes(cls, impl, working_dir, start_block_height=None, end_block_height=None): """ Read all consensus hashes into memory. They're write-once read-many, so no need to worry about cache-coherency. """ if (start_block_height is None and end_block_height is not None) or...
[ "def", "get_ops_hashes", "(", "cls", ",", "impl", ",", "working_dir", ",", "start_block_height", "=", "None", ",", "end_block_height", "=", "None", ")", ":", "if", "(", "start_block_height", "is", "None", "and", "end_block_height", "is", "not", "None", ")", ...
37.886364
26.568182
def tune_mount_configuration(self, path, default_lease_ttl=None, max_lease_ttl=None, description=None, audit_non_hmac_request_keys=None, audit_non_hmac_response_keys=None, listing_visibility=None, passthrough_request_headers=None, options=None): ...
[ "def", "tune_mount_configuration", "(", "self", ",", "path", ",", "default_lease_ttl", "=", "None", ",", "max_lease_ttl", "=", "None", ",", "description", "=", "None", ",", "audit_non_hmac_request_keys", "=", "None", ",", "audit_non_hmac_response_keys", "=", "None",...
52.57377
27.327869
def set_ttl(self, key, ttl): """ Sets time to live for @key to @ttl seconds -> #bool True if the timeout was set """ return self._client.expire(self.get_key(key), ttl)
[ "def", "set_ttl", "(", "self", ",", "key", ",", "ttl", ")", ":", "return", "self", ".", "_client", ".", "expire", "(", "self", ".", "get_key", "(", "key", ")", ",", "ttl", ")" ]
39.8
7.6
def _Tb(P, S): """Procedure to calculate the boiling temperature of seawater Parameters ---------- P : float Pressure, [MPa] S : float Salinity, [kg/kg] Returns ------- Tb : float Boiling temperature, [K] References ---------- IAPWS, Advisory Note ...
[ "def", "_Tb", "(", "P", ",", "S", ")", ":", "def", "f", "(", "T", ")", ":", "pw", "=", "_Region1", "(", "T", ",", "P", ")", "gw", "=", "pw", "[", "\"h\"", "]", "-", "T", "*", "pw", "[", "\"s\"", "]", "pv", "=", "_Region2", "(", "T", ","...
21.25
23
def selected(self): """Action to be executed when a valid item has been selected""" self.selected_text = self.currentText() self.valid.emit(True, True) self.open_dir.emit(self.selected_text)
[ "def", "selected", "(", "self", ")", ":", "self", ".", "selected_text", "=", "self", ".", "currentText", "(", ")", "self", ".", "valid", ".", "emit", "(", "True", ",", "True", ")", "self", ".", "open_dir", ".", "emit", "(", "self", ".", "selected_tex...
44.4
7.6
def set_priority(self, p_priority): """ Sets the priority of the todo. Must be a single capital letter [A-Z], or None to unset the priority. Priority remains unchanged when an invalid priority is given, or when the task was completed. """ if not self.is_completed(...
[ "def", "set_priority", "(", "self", ",", "p_priority", ")", ":", "if", "not", "self", ".", "is_completed", "(", ")", "and", "(", "p_priority", "is", "None", "or", "is_valid_priority", "(", "p_priority", ")", ")", ":", "self", ".", "fields", "[", "'priori...
47.076923
20.153846
def resume(self, start_date=None, end_date=None, timespan='DAY', check= False): ''' This method may help if the original run was interrupted for some reason. It will only work under the following conditions * You have a date field that you can facet on * Indexing was stopped for the ...
[ "def", "resume", "(", "self", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "timespan", "=", "'DAY'", ",", "check", "=", "False", ")", ":", "if", "type", "(", "self", ".", "_source", ")", "is", "not", "SolrClient", "or", "type", ...
71.658537
48.243902
def multiplied(*values): """ Returns the product of all supplied values. One or more *values* can be specified. For example, to light a :class:`~gpiozero.PWMLED` as the product (i.e. multiplication) of several potentiometers connected to an :class:`~gpiozero.MCP3008` ADC:: from gpiozero...
[ "def", "multiplied", "(", "*", "values", ")", ":", "values", "=", "[", "_normalize", "(", "v", ")", "for", "v", "in", "values", "]", "def", "_product", "(", "it", ")", ":", "p", "=", "1", "for", "n", "in", "it", ":", "p", "*=", "n", "return", ...
27.172414
19.034483
def receive(self): """ :rtype: bytes """ try: return self.socket.recv(self.__recv_bytes) except socket.error: _, e, _ = sys.exc_info() if get_errno(e) in (errno.EAGAIN, errno.EINTR): log.debug("socket read interrupted, restartin...
[ "def", "receive", "(", "self", ")", ":", "try", ":", "return", "self", ".", "socket", ".", "recv", "(", "self", ".", "__recv_bytes", ")", "except", "socket", ".", "error", ":", "_", ",", "e", ",", "_", "=", "sys", ".", "exc_info", "(", ")", "if",...
32.615385
13.846154
def any_embedded_linux(self): """Check whether the current board is any embedded Linux device.""" return self.any_raspberry_pi or self.any_beaglebone or \ self.any_orange_pi or self.any_giant_board or self.any_jetson_board
[ "def", "any_embedded_linux", "(", "self", ")", ":", "return", "self", ".", "any_raspberry_pi", "or", "self", ".", "any_beaglebone", "or", "self", ".", "any_orange_pi", "or", "self", ".", "any_giant_board", "or", "self", ".", "any_jetson_board" ]
61
17.75
def render_url(self): """ Render the final URL based on available variables """ url = self.url.format(**self.replacements) if self.params: return url + '?' + urlencode(self.params) return url
[ "def", "render_url", "(", "self", ")", ":", "url", "=", "self", ".", "url", ".", "format", "(", "*", "*", "self", ".", "replacements", ")", "if", "self", ".", "params", ":", "return", "url", "+", "'?'", "+", "urlencode", "(", "self", ".", "params",...
30.5
12.25
def show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_src_port(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_fabric_trunk_info = ET.Element("show_fabric_trunk_info") config = show_fabric_trunk_info ...
[ "def", "show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_src_port", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "show_fabric_trunk_info", "=", "ET", ".", "Element"...
55.933333
25.6
def create_object_if_not_exists(self, alias, name=None, *args, **kwargs): """Constructs the type with the given alias using the given args and kwargs. NB: aliases may be the alias' object type itself if that type is known. :API: public :param alias: Either the type alias or the type itself. :type...
[ "def", "create_object_if_not_exists", "(", "self", ",", "alias", ",", "name", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "name", "is", "None", ":", "raise", "ValueError", "(", "\"Method requires an object `name`.\"", ")", "obj_cr...
44.285714
20.714286
def _init_date_range(self, start_date=None, end_date=None): """Set date range defaults if no dates are passed""" self.end_date = end_date self.start_date = start_date if self.end_date is None: today = now_utc().date() end_date = self.event.end_dt.date() ...
[ "def", "_init_date_range", "(", "self", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ")", ":", "self", ".", "end_date", "=", "end_date", "self", ".", "start_date", "=", "start_date", "if", "self", ".", "end_date", "is", "None", ":", "tod...
50.1
13.7
def step_HMC(exe, exe_params, exe_grads, label_key, noise_precision, prior_precision, L=10, eps=1E-6): """Generate the implementation of step HMC""" init_params = {k: v.copyto(v.context) for k, v in exe_params.items()} end_params = {k: v.copyto(v.context) for k, v in exe_params.items()} init_momentums =...
[ "def", "step_HMC", "(", "exe", ",", "exe_params", ",", "exe_grads", ",", "label_key", ",", "noise_precision", ",", "prior_precision", ",", "L", "=", "10", ",", "eps", "=", "1E-6", ")", ":", "init_params", "=", "{", "k", ":", "v", ".", "copyto", "(", ...
50.040816
21.285714
def generate(env): """ Add Builders and construction variables for C compilers to an Environment. """ static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in CSuffixes: static_obj.add_action(suffix, SCons.Defaults.CAction) shared_obj.add_action(suffix, SCons.Default...
[ "def", "generate", "(", "env", ")", ":", "static_obj", ",", "shared_obj", "=", "SCons", ".", "Tool", ".", "createObjBuilders", "(", "env", ")", "for", "suffix", "in", "CSuffixes", ":", "static_obj", ".", "add_action", "(", "suffix", ",", "SCons", ".", "D...
36.566667
21.3
def consensus_scan(self, fa): """Scan FASTA with the motif as a consensus sequence. Parameters ---------- fa : Fasta object Fasta object to scan Returns ------- matches : dict Dictionaru with matches. """ regexp = ...
[ "def", "consensus_scan", "(", "self", ",", "fa", ")", ":", "regexp", "=", "\"\"", ".", "join", "(", "[", "\"[\"", "+", "\"\"", ".", "join", "(", "self", ".", "iupac", "[", "x", ".", "upper", "(", ")", "]", ")", "+", "\"]\"", "for", "x", "in", ...
30.818182
17
async def login(self, token, *, bot=True): """|coro| Logs in the client with the specified credentials. This function can be used in two different ways. .. warning:: Logging on with a user token is against the Discord `Terms of Service <https://support.discord...
[ "async", "def", "login", "(", "self", ",", "token", ",", "*", ",", "bot", "=", "True", ")", ":", "log", ".", "info", "(", "'logging in using static token'", ")", "await", "self", ".", "http", ".", "static_login", "(", "token", ",", "bot", "=", "bot", ...
33.027778
21.638889
def parse_args(self, args): """Parses positional arguments and returns ``(values, args, order)`` for the parsed options and arguments as well as the leftover arguments if there are any. The order is a list of objects as they appear on the command line. If arguments appear multiple time...
[ "def", "parse_args", "(", "self", ",", "args", ")", ":", "state", "=", "ParsingState", "(", "args", ")", "try", ":", "self", ".", "_process_args_for_options", "(", "state", ")", "self", ".", "_process_args_for_args", "(", "state", ")", "except", "UsageError"...
45.8
16
def get_feature_penalty(self): """Get the feature penalty of the Dataset. Returns ------- feature_penalty : numpy array or None Feature penalty for each feature in the Dataset. """ if self.feature_penalty is None: self.feature_penalty = self.get_f...
[ "def", "get_feature_penalty", "(", "self", ")", ":", "if", "self", ".", "feature_penalty", "is", "None", ":", "self", ".", "feature_penalty", "=", "self", ".", "get_field", "(", "'feature_penalty'", ")", "return", "self", ".", "feature_penalty" ]
33.545455
14.363636
def a_neg(self): ''' Negative antipodal point on the major axis, Point class. ''' na = Point(self.center) if self.xAxisIsMajor: na.x -= self.majorRadius else: na.y -= self.majorRadius return na
[ "def", "a_neg", "(", "self", ")", ":", "na", "=", "Point", "(", "self", ".", "center", ")", "if", "self", ".", "xAxisIsMajor", ":", "na", ".", "x", "-=", "self", ".", "majorRadius", "else", ":", "na", ".", "y", "-=", "self", ".", "majorRadius", "...
22
22
def _kl_divergence(params, P, degrees_of_freedom, n_samples, n_components, skip_num_points=0): """t-SNE objective function: gradient of the KL divergence of p_ijs and q_ijs and the absolute error. Parameters ---------- params : array, shape (n_params,) Unraveled embedding...
[ "def", "_kl_divergence", "(", "params", ",", "P", ",", "degrees_of_freedom", ",", "n_samples", ",", "n_components", ",", "skip_num_points", "=", "0", ")", ":", "X_embedded", "=", "params", ".", "reshape", "(", "n_samples", ",", "n_components", ")", "# Q is a h...
33.809524
21.31746
def generate(self, file, validatedata = None, inputdata=None, user = None): """Convert the template into instantiated metadata, validating the data in the process and returning errors otherwise. inputdata is a dictionary-compatible structure, such as the relevant postdata. Return (success, metadata, parameters...
[ "def", "generate", "(", "self", ",", "file", ",", "validatedata", "=", "None", ",", "inputdata", "=", "None", ",", "user", "=", "None", ")", ":", "metadata", "=", "{", "}", "if", "not", "validatedata", ":", "assert", "inputdata", "errors", ",", "parame...
45.931034
23.068966
def relations_to(self, target, include_object=False): ''' list all relations pointing at an object ''' relations = self._get_item_node(target).incoming if include_object: for k in relations: for v in relations[k]: if hasattr(v, 'obj'): # filter dea...
[ "def", "relations_to", "(", "self", ",", "target", ",", "include_object", "=", "False", ")", ":", "relations", "=", "self", ".", "_get_item_node", "(", "target", ")", ".", "incoming", "if", "include_object", ":", "for", "k", "in", "relations", ":", "for", ...
40.4
12.8
def load_data(self): """ Loads data files and stores the output in the data attribute. """ data = [] valid_dates = [] mrms_files = np.array(sorted(os.listdir(self.path + self.variable + "/"))) mrms_file_dates = np.array([m_file.split("_")[-2].split("-")[0] ...
[ "def", "load_data", "(", "self", ")", ":", "data", "=", "[", "]", "valid_dates", "=", "[", "]", "mrms_files", "=", "np", ".", "array", "(", "sorted", "(", "os", ".", "listdir", "(", "self", ".", "path", "+", "self", ".", "variable", "+", "\"/\"", ...
47.102564
17.820513
def getDepartmentInfo(self): """ Returns a dict with the department infomration {'uid':'xxxx','id':'xxxx','title':'xxx','url':'xxx'} """ pc = getToolByName(api.portal.get(), 'portal_catalog') contentFilter = {'portal_type': 'Department', 'UID': se...
[ "def", "getDepartmentInfo", "(", "self", ")", ":", "pc", "=", "getToolByName", "(", "api", ".", "portal", ".", "get", "(", ")", ",", "'portal_catalog'", ")", "contentFilter", "=", "{", "'portal_type'", ":", "'Department'", ",", "'UID'", ":", "self", ".", ...
41.043478
11.826087
def to_array(self): """ Serializes this VenueMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(VenueMessage, self).to_array() array['latitude'] = float(self.latitude) # type float array['longitude'...
[ "def", "to_array", "(", "self", ")", ":", "array", "=", "super", "(", "VenueMessage", ",", "self", ")", ".", "to_array", "(", ")", "array", "[", "'latitude'", "]", "=", "float", "(", "self", ".", "latitude", ")", "# type float", "array", "[", "'longitu...
52.192308
31.384615
async def listreactions(self, ctx): """Lists all the reactions for the server""" data = self.config.get(ctx.message.server.id, {}) if not data: await self.bot.responses.failure(message="There are no reactions on this server.") return try: pager = Pages...
[ "async", "def", "listreactions", "(", "self", ",", "ctx", ")", ":", "data", "=", "self", ".", "config", ".", "get", "(", "ctx", ".", "message", ".", "server", ".", "id", ",", "{", "}", ")", "if", "not", "data", ":", "await", "self", ".", "bot", ...
45.5
24.357143
def fasta_file_to_dict(fasta_file, id=True, header=False, seq=False): """Returns a dict from a fasta file and the number of sequences as the second return value. fasta_file can be a string path or a file object. The key of fasta_dict can be set using the keyword arguments and results in a combination of...
[ "def", "fasta_file_to_dict", "(", "fasta_file", ",", "id", "=", "True", ",", "header", "=", "False", ",", "seq", "=", "False", ")", ":", "fasta_file_f", "=", "fasta_file", "if", "isinstance", "(", "fasta_file", ",", "str", ")", ":", "fasta_file_f", "=", ...
43.409091
22.136364
def numberOfProximalSynapses(self, cells=None): """ Returns the number of proximal synapses with permanence>0 on these cells. Parameters: ---------------------------- @param cells (iterable) Indices of the cells. If None return count for all cells. """ if cells is None: c...
[ "def", "numberOfProximalSynapses", "(", "self", ",", "cells", "=", "None", ")", ":", "if", "cells", "is", "None", ":", "cells", "=", "xrange", "(", "self", ".", "numberOfCells", "(", ")", ")", "n", "=", "0", "for", "cell", "in", "cells", ":", "n", ...
27.75
19.5
def recursive_iter(enumerables): ''' Walks nested list-like elements as though they were sequentially available recursive_iter([[1,2], 3]) # => 1, 2, 3 ''' if not is_collection(enumerables) or isinstance(enumerables, (basestring, dict)): yield enumerables else: for...
[ "def", "recursive_iter", "(", "enumerables", ")", ":", "if", "not", "is_collection", "(", "enumerables", ")", "or", "isinstance", "(", "enumerables", ",", "(", "basestring", ",", "dict", ")", ")", ":", "yield", "enumerables", "else", ":", "for", "elem", "i...
31.692308
22.923077
def range(self) -> str: """Get the range of this fragment.""" if FRAGMENT_MISSING in self: return '?' return '{}_{}'.format(self[FRAGMENT_START], self[FRAGMENT_STOP])
[ "def", "range", "(", "self", ")", "->", "str", ":", "if", "FRAGMENT_MISSING", "in", "self", ":", "return", "'?'", "return", "'{}_{}'", ".", "format", "(", "self", "[", "FRAGMENT_START", "]", ",", "self", "[", "FRAGMENT_STOP", "]", ")" ]
33
18.5
def normalise(v, dimN=2): r"""Normalise vectors, corresponding to slices along specified number of initial spatial dimensions of an array, to have unit :math:`\ell_2` norm. The remaining axes enumerate the distinct vectors to be normalised. Parameters ---------- v : array_like Array w...
[ "def", "normalise", "(", "v", ",", "dimN", "=", "2", ")", ":", "axisN", "=", "tuple", "(", "range", "(", "0", ",", "dimN", ")", ")", "vn", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "v", "**", "2", ",", "axisN", ",", "keepdims", "=...
28.956522
19.217391
def pack_args(self): """ Pack the parameters into the form necessary for the integration routines above. For example, packs for calculate_linescan_psf """ mapper = { 'psf-kfki': 'kfki', 'psf-alpha': 'alpha', 'psf-n2n1': 'n2n1', 'ps...
[ "def", "pack_args", "(", "self", ")", ":", "mapper", "=", "{", "'psf-kfki'", ":", "'kfki'", ",", "'psf-alpha'", ":", "'alpha'", ",", "'psf-n2n1'", ":", "'n2n1'", ",", "'psf-sigkf'", ":", "'sigkf'", ",", "'psf-sph6-ab'", ":", "'sph6_ab'", ",", "'psf-laser-wav...
29.166667
15.222222
def read_skel(self, fid): """Loads an acclaim skeleton format from a file stream.""" lin = self.read_line(fid) while lin: if lin[0]==':': if lin[1:]== 'name': lin = self.read_line(fid) self.name = lin elif lin[1:...
[ "def", "read_skel", "(", "self", ",", "fid", ")", ":", "lin", "=", "self", ".", "read_line", "(", "fid", ")", "while", "lin", ":", "if", "lin", "[", "0", "]", "==", "':'", ":", "if", "lin", "[", "1", ":", "]", "==", "'name'", ":", "lin", "=",...
38.551724
8.482759
def _set_ip(self): """Resolve FQDN to IP address""" self._ip = socket.gethostbyname(self._fqdn) log.debug('IP: %s' % self._ip)
[ "def", "_set_ip", "(", "self", ")", ":", "self", ".", "_ip", "=", "socket", ".", "gethostbyname", "(", "self", ".", "_fqdn", ")", "log", ".", "debug", "(", "'IP: %s'", "%", "self", ".", "_ip", ")" ]
36.75
8.75
def _media(self): """ The medias needed to enhance the admin page. """ def static_url(url): return staticfiles_storage.url('zinnia_markitup/%s' % url) media = super(EntryAdminMarkItUpMixin, self).media media += Media( js=(static_url('js/jquery.mi...
[ "def", "_media", "(", "self", ")", ":", "def", "static_url", "(", "url", ")", ":", "return", "staticfiles_storage", ".", "url", "(", "'zinnia_markitup/%s'", "%", "url", ")", "media", "=", "super", "(", "EntryAdminMarkItUpMixin", ",", "self", ")", ".", "med...
36.619048
18.238095
def search(searchList, matchStr, numSyllables=None, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok', multiword='ok', pos=None): ''' Searches for matching words in the dictionary with regular expressions wordInitial, wordFinal, spanSyllable, stressSyllabl...
[ "def", "search", "(", "searchList", ",", "matchStr", ",", "numSyllables", "=", "None", ",", "wordInitial", "=", "'ok'", ",", "wordFinal", "=", "'ok'", ",", "spanSyllable", "=", "'ok'", ",", "stressedSyllable", "=", "'ok'", ",", "multiword", "=", "'ok'", ",...
37.506173
17.975309
def dumps(obj, big_endian=True): """ Dump a GeoJSON-like `dict` to a WKB string. .. note:: The dimensions of the generated WKB will be inferred from the first vertex in the GeoJSON `coordinates`. It will be assumed that all vertices are uniform. There are 4 types: - 2D (X, ...
[ "def", "dumps", "(", "obj", ",", "big_endian", "=", "True", ")", ":", "geom_type", "=", "obj", "[", "'type'", "]", "meta", "=", "obj", ".", "get", "(", "'meta'", ",", "{", "}", ")", "exporter", "=", "_dumps_registry", ".", "get", "(", "geom_type", ...
41.528571
23.871429
def get_models(args): """ Parse a list of ModelName, appname or appname.ModelName list, and return the list of model classes in the IndexRegistry. If the list if falsy, return all the models in the registry. """ if args: models = [] for arg in args: match_found = Fals...
[ "def", "get_models", "(", "args", ")", ":", "if", "args", ":", "models", "=", "[", "]", "for", "arg", "in", "args", ":", "match_found", "=", "False", "for", "model", "in", "registry", ".", "get_models", "(", ")", ":", "if", "model", ".", "_meta", "...
33.958333
16.458333
def color_hex(self): """Node color as Hex Triplet https://en.wikipedia.org/wiki/Web_colors#Hex_triplet""" def clamp(x): return max(0, min(int(x), 255)) r, g, b = np.trunc(self.color_rgb * 255) return "#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b))
[ "def", "color_hex", "(", "self", ")", ":", "def", "clamp", "(", "x", ")", ":", "return", "max", "(", "0", ",", "min", "(", "int", "(", "x", ")", ",", "255", ")", ")", "r", ",", "g", ",", "b", "=", "np", ".", "trunc", "(", "self", ".", "co...
42.857143
18
def process_post_media_attachments(self, bulk_mode, api_post, post_media_attachments): """ Create or update Media objects related to a post. :param bulk_mode: If True, minimize db operations by bulk creating post objects :param api_post: the API data for the Post :param post_med...
[ "def", "process_post_media_attachments", "(", "self", ",", "bulk_mode", ",", "api_post", ",", "post_media_attachments", ")", ":", "post_media_attachments", "[", "api_post", "[", "\"ID\"", "]", "]", "=", "[", "]", "for", "api_attachment", "in", "six", ".", "iterv...
47.4
26.333333
def get_parser(): """Argument specifier. """ parser = argparse.ArgumentParser(prog='pyradigm') parser.add_argument('path_list', nargs='*', action='store', default=None, help='List of paths to display info about.') parser.add_argument('-m', '--meta', action='store_true', d...
[ "def", "get_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "'pyradigm'", ")", "parser", ".", "add_argument", "(", "'path_list'", ",", "nargs", "=", "'*'", ",", "action", "=", "'store'", ",", "default", "=", "N...
42.935484
28.322581
def _from_dict(cls, _dict): """Initialize a PdfHeadingDetection object from a json dictionary.""" args = {} if 'fonts' in _dict: args['fonts'] = [ FontSetting._from_dict(x) for x in (_dict.get('fonts')) ] return cls(**args)
[ "def", "_from_dict", "(", "cls", ",", "_dict", ")", ":", "args", "=", "{", "}", "if", "'fonts'", "in", "_dict", ":", "args", "[", "'fonts'", "]", "=", "[", "FontSetting", ".", "_from_dict", "(", "x", ")", "for", "x", "in", "(", "_dict", ".", "get...
36
16.375
def get_recipe_env(self, arch, with_flags_in_cc=True): """ Add libgeos headers to path """ env = super(ShapelyRecipe, self).get_recipe_env(arch, with_flags_in_cc) libgeos_dir = Recipe.get_recipe('libgeos', self.ctx).get_build_dir(arch.arch) env['CFLAGS'] += " -I{}/dist/include".format(li...
[ "def", "get_recipe_env", "(", "self", ",", "arch", ",", "with_flags_in_cc", "=", "True", ")", ":", "env", "=", "super", "(", "ShapelyRecipe", ",", "self", ")", ".", "get_recipe_env", "(", "arch", ",", "with_flags_in_cc", ")", "libgeos_dir", "=", "Recipe", ...
57.333333
24.166667