text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def dot(*values: Union[float, complex, np.ndarray] ) -> Union[float, complex, np.ndarray]: """Computes the dot/matrix product of a sequence of values. A *args version of np.linalg.multi_dot. Args: *values: The values to combine with the dot/matrix product. Returns: The resulti...
[ "def", "dot", "(", "*", "values", ":", "Union", "[", "float", ",", "complex", ",", "np", ".", "ndarray", "]", ")", "->", "Union", "[", "float", ",", "complex", ",", "np", ".", "ndarray", "]", ":", "if", "len", "(", "values", ")", "==", "1", ":"...
29.705882
15.823529
def process_calibration(self, save=True, calf=20000): """Processes a completed calibration :param save: Wether to save this calibration to file :type save: bool :param calf: Frequency for which to reference attenuation curve from :type calf: int :returns: str -- name of ...
[ "def", "process_calibration", "(", "self", ",", "save", "=", "True", ",", "calf", "=", "20000", ")", ":", "if", "self", ".", "selected_calibration_index", "==", "2", ":", "raise", "Exception", "(", "\"Calibration curve processing not currently supported\"", ")", "...
42.714286
20.785714
def find_atoms_near_atom(self, source_atom, search_radius, atom_hit_cache = set(), atom_names_to_include = set(), atom_names_to_exclude = set(), restrict_to_CA = False): '''It is advisable to set up and use an atom hit cache object. This reduces the number of distance calculations and gives better performance. ...
[ "def", "find_atoms_near_atom", "(", "self", ",", "source_atom", ",", "search_radius", ",", "atom_hit_cache", "=", "set", "(", ")", ",", "atom_names_to_include", "=", "set", "(", ")", ",", "atom_names_to_exclude", "=", "set", "(", ")", ",", "restrict_to_CA", "=...
69.114286
42.257143
def _route_flags(rflags): ''' https://github.com/torvalds/linux/blob/master/include/uapi/linux/route.h https://github.com/torvalds/linux/blob/master/include/uapi/linux/ipv6_route.h ''' flags = '' fmap = { 0x0001: 'U', # RTF_UP, route is up 0x0002: 'G', # RTF_GATEWAY, use gatewa...
[ "def", "_route_flags", "(", "rflags", ")", ":", "flags", "=", "''", "fmap", "=", "{", "0x0001", ":", "'U'", ",", "# RTF_UP, route is up", "0x0002", ":", "'G'", ",", "# RTF_GATEWAY, use gateway", "0x0004", ":", "'H'", ",", "# RTF_HOST, target is a host", "0x0008"...
40.666667
23.238095
def compose(self, bucket_name, source_objects, destination_object): """ Composes a list of existing object into a new object in the same storage bucket_name Currently it only supports up to 32 objects that can be concatenated in a single operation https://cloud.google.com/stora...
[ "def", "compose", "(", "self", ",", "bucket_name", ",", "source_objects", ",", "destination_object", ")", ":", "if", "not", "source_objects", "or", "not", "len", "(", "source_objects", ")", ":", "raise", "ValueError", "(", "'source_objects cannot be empty.'", ")",...
42.472222
25.027778
def remove_qc_reports(portal): """Removes the action Quality Control from Reports """ logger.info("Removing Reports > Quality Control ...") ti = portal.reports.getTypeInfo() actions = map(lambda action: action.id, ti._actions) for index, action in enumerate(actions, start=0): if action =...
[ "def", "remove_qc_reports", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Removing Reports > Quality Control ...\"", ")", "ti", "=", "portal", ".", "reports", ".", "getTypeInfo", "(", ")", "actions", "=", "map", "(", "lambda", "action", ":", "action"...
40.545455
9.727273
def set_current_stim_parameter(self, param, val): """Sets a parameter on the current stimulus :param param: name of the parameter of the stimulus to set :type param: str :param val: new value to set the parameter to """ component = self._stimulus.component(0,1) c...
[ "def", "set_current_stim_parameter", "(", "self", ",", "param", ",", "val", ")", ":", "component", "=", "self", ".", "_stimulus", ".", "component", "(", "0", ",", "1", ")", "component", ".", "set", "(", "param", ",", "val", ")" ]
37.333333
13.333333
def paintEvent(self, event): """Override Qt method.""" painter = QPainter(self) color = QColor(self.color) color.setAlphaF(.5) painter.setPen(color) offset = self.editor.document().documentMargin() + \ self.editor.contentOffset().x() for _, line_numb...
[ "def", "paintEvent", "(", "self", ",", "event", ")", ":", "painter", "=", "QPainter", "(", "self", ")", "color", "=", "QColor", "(", "self", ".", "color", ")", "color", ".", "setAlphaF", "(", ".5", ")", "painter", ".", "setPen", "(", "color", ")", ...
41.102041
20.020408
def next (self): # File-like object. """This is to support iterators over a file-like object. """ result = self.readline() if result == self._empty_buffer: raise StopIteration return result
[ "def", "next", "(", "self", ")", ":", "# File-like object.", "result", "=", "self", ".", "readline", "(", ")", "if", "result", "==", "self", ".", "_empty_buffer", ":", "raise", "StopIteration", "return", "result" ]
26.444444
13
def rewrite_links(self, func): """ Add a callback for rewriting links. The callback should take a single argument, the url, and should return a replacement url. The callback function is called everytime a ``[]()`` or ``<link>`` is processed. You can use this method as ...
[ "def", "rewrite_links", "(", "self", ",", "func", ")", ":", "@", "libmarkdown", ".", "e_url_callback", "def", "_rewrite_links_func", "(", "string", ",", "size", ",", "context", ")", ":", "ret", "=", "func", "(", "string", "[", ":", "size", "]", ")", "i...
36.095238
15.333333
def _createStatsDict(self, headers, rows): """Utility method that returns database stats as a nested dictionary. @param headers: List of columns in query result. @param rows: List of rows in query result. @return: Nested dictionary of values. Fi...
[ "def", "_createStatsDict", "(", "self", ",", "headers", ",", "rows", ")", ":", "dbstats", "=", "{", "}", "for", "row", "in", "rows", ":", "dbstats", "[", "row", "[", "0", "]", "]", "=", "dict", "(", "zip", "(", "headers", "[", "1", ":", "]", ",...
40.571429
16.285714
def load_manual_sequence(self, seq, ident=None, write_fasta_file=False, outdir=None, set_as_representative=False, force_rewrite=False): """Load a manual sequence given as a string and optionally set it as the representative sequence. Also store it in the sequences attribute....
[ "def", "load_manual_sequence", "(", "self", ",", "seq", ",", "ident", "=", "None", ",", "write_fasta_file", "=", "False", ",", "outdir", "=", "None", ",", "set_as_representative", "=", "False", ",", "force_rewrite", "=", "False", ")", ":", "if", "write_fasta...
45.9375
27.145833
def vector_dot(vector1, vector2): """ Computes the dot-product of the input vectors. :param vector1: input vector 1 :type vector1: list, tuple :param vector2: input vector 2 :type vector2: list, tuple :return: result of the dot product :rtype: float """ try: if vector1 is No...
[ "def", "vector_dot", "(", "vector1", ",", "vector2", ")", ":", "try", ":", "if", "vector1", "is", "None", "or", "len", "(", "vector1", ")", "==", "0", "or", "vector2", "is", "None", "or", "len", "(", "vector2", ")", "==", "0", ":", "raise", "ValueE...
29.730769
18.076923
def gc(self): '''Find the frequency of G and C in the current sequence.''' gc = len([base for base in self.seq if base == 'C' or base == 'G']) return float(gc) / len(self)
[ "def", "gc", "(", "self", ")", ":", "gc", "=", "len", "(", "[", "base", "for", "base", "in", "self", ".", "seq", "if", "base", "==", "'C'", "or", "base", "==", "'G'", "]", ")", "return", "float", "(", "gc", ")", "/", "len", "(", "self", ")" ]
48
23.5
def predict(self, trial_history): """predict the value of target position Parameters ---------- trial_history: list The history performance matrix of each trial. Returns ------- float expected final result performance of this hype...
[ "def", "predict", "(", "self", ",", "trial_history", ")", ":", "self", ".", "trial_history", "=", "trial_history", "self", ".", "point_num", "=", "len", "(", "trial_history", ")", "self", ".", "fit_theta", "(", ")", "self", ".", "filter_curve", "(", ")", ...
33.36
18.24
def store_report_link(backend, user, response, *args, **kwargs): ''' Part of the Python Social Auth Pipeline. Stores the result service URL reported by the LMS / LTI tool consumer so that we can use it later. ''' if backend.name is 'lti': assignment_pk = response.get('assignment_pk', None) ...
[ "def", "store_report_link", "(", "backend", ",", "user", ",", "response", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "backend", ".", "name", "is", "'lti'", ":", "assignment_pk", "=", "response", ".", "get", "(", "'assignment_pk'", ",", ...
53.8125
31.3125
async def _get(self, term: str = None, random: bool = False) -> dict: """Helper method to reduce some boilerplate with :module:`aiohttp`. Args: term: The term to search for. Optional if doing a random search. random: Whether the search should return a random word. ...
[ "async", "def", "_get", "(", "self", ",", "term", ":", "str", "=", "None", ",", "random", ":", "bool", "=", "False", ")", "->", "dict", ":", "params", "=", "None", "if", "random", ":", "url", "=", "self", ".", "RANDOM_URL", "else", ":", "params", ...
33.741935
21.419355
def updateorders(self): """ Update the orders """ log.info("Replacing orders") # Canceling orders self.cancelall() # Target target = self.bot.get("target", {}) price = self.getprice() # prices buy_price = price * (1 - target["offsets"]["...
[ "def", "updateorders", "(", "self", ")", ":", "log", ".", "info", "(", "\"Replacing orders\"", ")", "# Canceling orders", "self", ".", "cancelall", "(", ")", "# Target", "target", "=", "self", ".", "bot", ".", "get", "(", "\"target\"", ",", "{", "}", ")"...
33.113636
21.613636
def next(self, timeout=None): """Return the next result value in the sequence. Raise StopIteration at the end. Can raise the exception raised by the Job""" try: apply_result = self._collector._get_result(self._idx, timeout) except IndexError: # Reset for n...
[ "def", "next", "(", "self", ",", "timeout", "=", "None", ")", ":", "try", ":", "apply_result", "=", "self", ".", "_collector", ".", "_get_result", "(", "self", ".", "_idx", ",", "timeout", ")", "except", "IndexError", ":", "# Reset for next time", "self", ...
32.8125
14.8125
def dictionaries_walker(dictionary, path=()): """ Defines a generator used to walk into nested dictionaries. Usage:: >>> nested_dictionary = {"Level 1A":{"Level 2A": { "Level 3A" : "Higher Level"}}, "Level 1B" : "Lower level"} >>> dictionaries_walker(nested_dictionary) <generator o...
[ "def", "dictionaries_walker", "(", "dictionary", ",", "path", "=", "(", ")", ")", ":", "for", "key", "in", "dictionary", ":", "if", "not", "isinstance", "(", "dictionary", "[", "key", "]", ",", "dict", ")", ":", "yield", "path", ",", "key", ",", "dic...
37.548387
24
def _PythonValueToJsonValue(py_value): """Convert the given python value to a JsonValue.""" if py_value is None: return JsonValue(is_null=True) if isinstance(py_value, bool): return JsonValue(boolean_value=py_value) if isinstance(py_value, six.string_types): return JsonValue(stri...
[ "def", "_PythonValueToJsonValue", "(", "py_value", ")", ":", "if", "py_value", "is", "None", ":", "return", "JsonValue", "(", "is_null", "=", "True", ")", "if", "isinstance", "(", "py_value", ",", "bool", ")", ":", "return", "JsonValue", "(", "boolean_value"...
47.578947
10.315789
def list_tags(tags): """Print tags in dict so they allign with listing above.""" tags_sorted = sorted(list(tags.items()), key=operator.itemgetter(0)) tag_sec_spacer = "" c = 1 ignored_keys = ["Name", "aws:ec2spot:fleet-request-id"] pad_col = {1: 38, 2: 49} for k, v in tags_sorted: # ...
[ "def", "list_tags", "(", "tags", ")", ":", "tags_sorted", "=", "sorted", "(", "list", "(", "tags", ".", "items", "(", ")", ")", ",", "key", "=", "operator", ".", "itemgetter", "(", "0", ")", ")", "tag_sec_spacer", "=", "\"\"", "c", "=", "1", "ignor...
38.272727
17.318182
def createTopicPage2(): """ create a topic page directly, set the article threshold, restrict results to set concepts and keywords """ topic = TopicPage(er) topic.addCategory(er.getCategoryUri("renewable"), 50) topic.addKeyword("renewable energy", 30) topic.addConcept(er.getConceptUri("bio...
[ "def", "createTopicPage2", "(", ")", ":", "topic", "=", "TopicPage", "(", "er", ")", "topic", ".", "addCategory", "(", "er", ".", "getCategoryUri", "(", "\"renewable\"", ")", ",", "50", ")", "topic", ".", "addKeyword", "(", "\"renewable energy\"", ",", "30...
40.294118
24.294118
def configureIAMCredentials(self, AWSAccessKeyID, AWSSecretAccessKey, AWSSessionToken=""): """ **Description** Used to configure/update the custom IAM credentials for Websocket SigV4 connection to AWS IoT. Should be called before connect. **Syntax** .. code:: python ...
[ "def", "configureIAMCredentials", "(", "self", ",", "AWSAccessKeyID", ",", "AWSSecretAccessKey", ",", "AWSSessionToken", "=", "\"\"", ")", ":", "iam_credentials_provider", "=", "IAMCredentialsProvider", "(", ")", "iam_credentials_provider", ".", "set_access_key_id", "(", ...
34.833333
33.444444
def playlist_song_move( self, playlist_song, *, after=None, before=None, index=None, position=None ): """Move a song in a playlist. Note: * Provide no optional arguments to move to end. * Provide playlist song dicts for ``after`` and/or ``before``. * Provide a zero-based ``index``. * Pro...
[ "def", "playlist_song_move", "(", "self", ",", "playlist_song", ",", "*", ",", "after", "=", "None", ",", "before", "=", "None", ",", "index", "=", "None", ",", "position", "=", "None", ")", ":", "playlist_songs", "=", "self", ".", "playlist", "(", "pl...
26.169811
23.037736
def network_interfaces_list_all(**kwargs): ''' .. versionadded:: 2019.2.0 List all network interfaces within a subscription. CLI Example: .. code-block:: bash salt-call azurearm_network.network_interfaces_list_all ''' result = {} netconn = __utils__['azurearm.get_client']('n...
[ "def", "network_interfaces_list_all", "(", "*", "*", "kwargs", ")", ":", "result", "=", "{", "}", "netconn", "=", "__utils__", "[", "'azurearm.get_client'", "]", "(", "'network'", ",", "*", "*", "kwargs", ")", "try", ":", "nics", "=", "__utils__", "[", "...
25.88
26.68
def processPrePrepare(self, pre_prepare: PrePrepare, sender: str): """ Validate and process provided PRE-PREPARE, create and broadcast PREPARE for it. :param pre_prepare: message :param sender: name of the node that sent this message """ key = (pre_prepare.viewNo...
[ "def", "processPrePrepare", "(", "self", ",", "pre_prepare", ":", "PrePrepare", ",", "sender", ":", "str", ")", ":", "key", "=", "(", "pre_prepare", ".", "viewNo", ",", "pre_prepare", ".", "ppSeqNo", ")", "self", ".", "logger", ".", "debug", "(", "\"{} r...
53.248062
21.418605
def hybridize(self, active=True, **kwargs): """Activates or deactivates `HybridBlock` s recursively. Has no effect on non-hybrid children. Parameters ---------- active : bool, default True Whether to turn hybrid on or off. **kwargs : string Additi...
[ "def", "hybridize", "(", "self", ",", "active", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_children", "and", "all", "(", "isinstance", "(", "c", ",", "HybridBlock", ")", "for", "c", "in", "self", ".", "_children", ".", "va...
44.875
20.375
def cmd(send, msg, args): """Reports the difference between now and some specified time. Syntax: {command} <time> """ parser = arguments.ArgParser(args['config']) parser.add_argument('date', nargs='*', action=arguments.DateParser) try: cmdargs = parser.parse_args(msg) except argume...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "parser", "=", "arguments", ".", "ArgParser", "(", "args", "[", "'config'", "]", ")", "parser", ".", "add_argument", "(", "'date'", ",", "nargs", "=", "'*'", ",", "action", "=", "arguments...
31.03125
16.5625
def indent(self): """ Indents the document text under cursor. :return: Method success. :rtype: bool """ cursor = self.textCursor() if not cursor.hasSelection(): cursor.insertText(self.__indent_marker) else: block = self.document()...
[ "def", "indent", "(", "self", ")", ":", "cursor", "=", "self", ".", "textCursor", "(", ")", "if", "not", "cursor", ".", "hasSelection", "(", ")", ":", "cursor", ".", "insertText", "(", "self", ".", "__indent_marker", ")", "else", ":", "block", "=", "...
31.904762
16
def get_issuer_keys(self, issuer): """ Get all the keys that belong to an entity. :param issuer: The entity ID :return: A possibly empty list of keys """ res = [] for kbl in self.issuer_keys[issuer]: res.extend(kbl.keys()) return res
[ "def", "get_issuer_keys", "(", "self", ",", "issuer", ")", ":", "res", "=", "[", "]", "for", "kbl", "in", "self", ".", "issuer_keys", "[", "issuer", "]", ":", "res", ".", "extend", "(", "kbl", ".", "keys", "(", ")", ")", "return", "res" ]
27.272727
11.090909
def iterator(plugins, context): """An iterator for plug-in and instance pairs""" test = pyblish.logic.registered_test() state = { "nextOrder": None, "ordersWithError": set() } for plugin in plugins: state["nextOrder"] = plugin.order message = test(**state) i...
[ "def", "iterator", "(", "plugins", ",", "context", ")", ":", "test", "=", "pyblish", ".", "logic", ".", "registered_test", "(", ")", "state", "=", "{", "\"nextOrder\"", ":", "None", ",", "\"ordersWithError\"", ":", "set", "(", ")", "}", "for", "plugin", ...
27.5
17.863636
def to_observations_dataframe(self, sql_ctx, ts_col='timestamp', key_col='key', val_col='value'): """ Returns a DataFrame of observations, each containing a timestamp, a key, and a value. Parameters ---------- sql_ctx : SQLContext ts_col : string The name for...
[ "def", "to_observations_dataframe", "(", "self", ",", "sql_ctx", ",", "ts_col", "=", "'timestamp'", ",", "key_col", "=", "'key'", ",", "val_col", "=", "'value'", ")", ":", "ssql_ctx", "=", "sql_ctx", ".", "_ssql_ctx", "jdf", "=", "self", ".", "_jtsrdd", "....
37.352941
18.529412
def _sign(private_key, data, hash_algorithm): """ Generates an RSA, DSA or ECDSA signature :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1"...
[ "def", "_sign", "(", "private_key", ",", "data", ",", "hash_algorithm", ")", ":", "if", "not", "isinstance", "(", "private_key", ",", "PrivateKey", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n private_key must be an instance of Private...
31.345912
18.578616
def _is_owner_ignored(owner, name, ignored_classes, ignored_modules): """Check if the given owner should be ignored This will verify if the owner's module is in *ignored_modules* or the owner's module fully qualified name is in *ignored_modules* or if the *ignored_modules* contains a pattern which catc...
[ "def", "_is_owner_ignored", "(", "owner", ",", "name", ",", "ignored_classes", ",", "ignored_modules", ")", ":", "ignored_modules", "=", "set", "(", "ignored_modules", ")", "module_name", "=", "owner", ".", "root", "(", ")", ".", "name", "module_qname", "=", ...
36.551724
17.241379
def drop_unused_terms(self): ''' Returns ------- PriorFactory ''' self.term_doc_mat = self.term_doc_mat.remove_terms( set(self.term_doc_mat.get_terms()) - set(self.priors.index) ) self._reindex_priors() return self
[ "def", "drop_unused_terms", "(", "self", ")", ":", "self", ".", "term_doc_mat", "=", "self", ".", "term_doc_mat", ".", "remove_terms", "(", "set", "(", "self", ".", "term_doc_mat", ".", "get_terms", "(", ")", ")", "-", "set", "(", "self", ".", "priors", ...
20.454545
25.909091
def send_es_mapping(self, es_map, **kwargs): """ sends the mapping to elasticsearch args: es_map: dictionary of the index mapping kwargs: reset_idx: WARNING! If True the current referenced es index will be deleted destroying all data...
[ "def", "send_es_mapping", "(", "self", ",", "es_map", ",", "*", "*", "kwargs", ")", ":", "log", ".", "setLevel", "(", "kwargs", ".", "get", "(", "'log_level'", ",", "self", ".", "log_level", ")", ")", "def", "next_es_index_version", "(", "curr_alias", ")...
44.215385
18.923077
def _set_client_id(self, client_id): """ Method for tracer to set client ID of throttler. """ with self.lock: if self.client_id is None: self.client_id = client_id
[ "def", "_set_client_id", "(", "self", ",", "client_id", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "client_id", "is", "None", ":", "self", ".", "client_id", "=", "client_id" ]
31
5.857143
def copy(self,deep=yes): """ Makes a (deep)copy of this object for use by other objects. """ if deep: return copy.deepcopy(self) else: return copy.copy(self)
[ "def", "copy", "(", "self", ",", "deep", "=", "yes", ")", ":", "if", "deep", ":", "return", "copy", ".", "deepcopy", "(", "self", ")", "else", ":", "return", "copy", ".", "copy", "(", "self", ")" ]
29.571429
10.714286
def get_userstable_data(self): """Get users with roles on the project. Roles can be applied directly on the project or through a group. """ project_users = {} project = self.tab_group.kwargs['project'] try: # Get all global roles once to avoid multiple reque...
[ "def", "get_userstable_data", "(", "self", ")", ":", "project_users", "=", "{", "}", "project", "=", "self", ".", "tab_group", ".", "kwargs", "[", "'project'", "]", "try", ":", "# Get all global roles once to avoid multiple requests.", "roles", "=", "api", ".", ...
39.766667
21.766667
def plot_fullcalib(dio_cross,feedtype='l',**kwargs): ''' Generates and shows five plots: Uncalibrated diode, calibrated diode, fold information, phase offsets, and gain offsets for a noise diode measurement. Most useful diagnostic plot to make sure calibration proceeds correctly. ''' plt.figure...
[ "def", "plot_fullcalib", "(", "dio_cross", ",", "feedtype", "=", "'l'", ",", "*", "*", "kwargs", ")", ":", "plt", ".", "figure", "(", "\"Multiple Calibration Plots\"", ",", "figsize", "=", "(", "12", ",", "9", ")", ")", "left", ",", "width", "=", "0.07...
37.469388
24.979592
def replace_pattern(name, pattern, repl, count=0, flags=8, bufsize=1, append_if_not_found=False, prepend_if_not_found=False, not_found_content=None, ...
[ "def", "replace_pattern", "(", "name", ",", "pattern", ",", "repl", ",", "count", "=", "0", ",", "flags", "=", "8", ",", "bufsize", "=", "1", ",", "append_if_not_found", "=", "False", ",", "prepend_if_not_found", "=", "False", ",", "not_found_content", "="...
42.258741
24.832168
def update_cells(self, cell_list, value_input_option='RAW'): """Updates many cells at once. :param cell_list: List of :class:`Cell` objects to update. :param value_input_option: (optional) Determines how input data should be interpreted. See `ValueInputOption...
[ "def", "update_cells", "(", "self", ",", "cell_list", ",", "value_input_option", "=", "'RAW'", ")", ":", "values_rect", "=", "cell_list_to_rect", "(", "cell_list", ")", "start", "=", "rowcol_to_a1", "(", "min", "(", "c", ".", "row", "for", "c", "in", "cell...
30.952381
25.357143
def find_base_images(self): """Finds all mountpoints that are mounted to a directory matching :attr:`orig_re_pattern`.""" for mountpoint, _ in self.mountpoints.items(): if re.match(self.orig_re_pattern, mountpoint): yield mountpoint
[ "def", "find_base_images", "(", "self", ")", ":", "for", "mountpoint", ",", "_", "in", "self", ".", "mountpoints", ".", "items", "(", ")", ":", "if", "re", ".", "match", "(", "self", ".", "orig_re_pattern", ",", "mountpoint", ")", ":", "yield", "mountp...
45.333333
15.5
def _login(self, csrf_token): """Attempt to login session on easyname.""" login_response = self.session.post( self.URLS['login'], data={ 'username': self._get_provider_option('auth_username') or '', 'password': self._get_provider_option('auth_passw...
[ "def", "_login", "(", "self", ",", "csrf_token", ")", ":", "login_response", "=", "self", ".", "session", ".", "post", "(", "self", ".", "URLS", "[", "'login'", "]", ",", "data", "=", "{", "'username'", ":", "self", ".", "_get_provider_option", "(", "'...
43.625
16.8125
def load_learner(path:PathOrStr, file:PathLikeOrBinaryStream='export.pkl', test:ItemList=None, **db_kwargs): "Load a `Learner` object saved with `export_state` in `path/file` with empty data, optionally add `test` and load on `cpu`. `file` can be file-like (file or buffer)" source = Path(path)/file if is_pathli...
[ "def", "load_learner", "(", "path", ":", "PathOrStr", ",", "file", ":", "PathLikeOrBinaryStream", "=", "'export.pkl'", ",", "test", ":", "ItemList", "=", "None", ",", "*", "*", "db_kwargs", ")", ":", "source", "=", "Path", "(", "path", ")", "/", "file", ...
62.785714
30.071429
def revise(self, data): """ Revise attributes value with dictionary data. **中文文档** 将一个字典中的数据更新到本条文档。当且仅当数据值不为None时。 """ if not isinstance(data, dict): raise TypeError("`data` has to be a dict!") for key, value in data.items(): if value i...
[ "def", "revise", "(", "self", ",", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"`data` has to be a dict!\"", ")", "for", "key", ",", "value", "in", "data", ".", "items", "(", ")", ":", ...
26.428571
15
def copy(self): """Copy text to clipboard""" if not self.selectedIndexes(): return (row_min, row_max, col_min, col_max) = get_idx_rect(self.selectedIndexes()) index = header = False df = self.model().df obj = df.iloc[slice(row_min, row_max + 1...
[ "def", "copy", "(", "self", ")", ":", "if", "not", "self", ".", "selectedIndexes", "(", ")", ":", "return", "(", "row_min", ",", "row_max", ",", "col_min", ",", "col_max", ")", "=", "get_idx_rect", "(", "self", ".", "selectedIndexes", "(", ")", ")", ...
36.684211
13.263158
def steps(self, *steps_cfg:StartOptEnd): "Build anneal schedule for all of the parameters." return [Scheduler(step, n_iter, func=func) for (step,(n_iter,func)) in zip(steps_cfg, self.phases)]
[ "def", "steps", "(", "self", ",", "*", "steps_cfg", ":", "StartOptEnd", ")", ":", "return", "[", "Scheduler", "(", "step", ",", "n_iter", ",", "func", "=", "func", ")", "for", "(", "step", ",", "(", "n_iter", ",", "func", ")", ")", "in", "zip", "...
55
15
def generate_confs(tileset, ignore_warnings=True, renderd=False): """ Takes a Tileset object and returns mapproxy and seed config files """ mapproxy_conf_json = """ { "services":{ "wms":{ "on_source_errors":"raise", "image_formats": ["image/png"] } }, ...
[ "def", "generate_confs", "(", "tileset", ",", "ignore_warnings", "=", "True", ",", "renderd", "=", "False", ")", ":", "mapproxy_conf_json", "=", "\"\"\"\n {\n \"services\":{\n \"wms\":{\n \"on_source_errors\":\"raise\",\n \"image_formats\": [\"image/p...
34.917582
25.5
def raise_305(instance, location): """Abort the current request with a 305 (Use Proxy) response code. Sets the Location header correctly. If the location does not start with a slash, the path of the current request is prepended. :param instance: Resource instance (used to access the response) :type...
[ "def", "raise_305", "(", "instance", ",", "location", ")", ":", "_set_location", "(", "instance", ",", "location", ")", "instance", ".", "response", ".", "status", "=", "305", "raise", "ResponseException", "(", "instance", ".", "response", ")" ]
45.916667
14.916667
def generate(env): """Add Builders and construction variables for Borland ilink to an Environment.""" SCons.Tool.createSharedLibBuilder(env) SCons.Tool.createProgBuilder(env) env['LINK'] = '$CC' env['LINKFLAGS'] = SCons.Util.CLVar('') env['LINKCOM'] = '$LINK -q $LINKFLAGS -e$TA...
[ "def", "generate", "(", "env", ")", ":", "SCons", ".", "Tool", ".", "createSharedLibBuilder", "(", "env", ")", "SCons", ".", "Tool", ".", "createProgBuilder", "(", "env", ")", "env", "[", "'LINK'", "]", "=", "'$CC'", "env", "[", "'LINKFLAGS'", "]", "="...
34.461538
12.076923
def unwrap(self, val): """Unpack a Value as some other python type """ if val.getID()!=self.id: self._update(val) return self._unwrap(val)
[ "def", "unwrap", "(", "self", ",", "val", ")", ":", "if", "val", ".", "getID", "(", ")", "!=", "self", ".", "id", ":", "self", ".", "_update", "(", "val", ")", "return", "self", ".", "_unwrap", "(", "val", ")" ]
29.5
7.5
def prepare_additional_parameters(additional_properties, language_hints, web_detection_params): """ Creates additional_properties parameter based on language_hints, web_detection_params and additional_properties parameters specified by the user """ if language_hints is None and web_detection_params ...
[ "def", "prepare_additional_parameters", "(", "additional_properties", ",", "language_hints", ",", "web_detection_params", ")", ":", "if", "language_hints", "is", "None", "and", "web_detection_params", "is", "None", ":", "return", "additional_properties", "if", "additional...
40.958333
25.791667
def check_bot(task_type=SYSTEM_TASK): """ wxpy bot 健康检查任务 """ if glb.wxbot.bot.alive: msg = generate_run_info() message = Message(content=msg, receivers='status') glb.wxbot.send_msg(message) _logger.info( '{0} Send status message {1} at {2:%Y-%m-%d %H:%M:%S}'....
[ "def", "check_bot", "(", "task_type", "=", "SYSTEM_TASK", ")", ":", "if", "glb", ".", "wxbot", ".", "bot", ".", "alive", ":", "msg", "=", "generate_run_info", "(", ")", "message", "=", "Message", "(", "content", "=", "msg", ",", "receivers", "=", "'sta...
30.307692
18.923077
def add_external_parameter(self, parameter): """ Add a parameter that comes from something other than a function, to the model. :param parameter: a Parameter instance :return: none """ assert isinstance(parameter, Parameter), "Variable must be an instance of Independent...
[ "def", "add_external_parameter", "(", "self", ",", "parameter", ")", ":", "assert", "isinstance", "(", "parameter", ",", "Parameter", ")", ",", "\"Variable must be an instance of IndependentVariable\"", "if", "self", ".", "_has_child", "(", "parameter", ".", "name", ...
38.846154
31.230769
def _shutdown(self, manual): """ Shuts down the TLS session and then shuts down the underlying socket :param manual: A boolean if the connection was manually shutdown """ if self._session_context is None: return # Ignore error during close in ca...
[ "def", "_shutdown", "(", "self", ",", "manual", ")", ":", "if", "self", ".", "_session_context", "is", "None", ":", "return", "# Ignore error during close in case other end closed already", "result", "=", "Security", ".", "SSLClose", "(", "self", ".", "_session_cont...
28.5
21.1
def _getLocation(self, coordinate, reference_id, strand, position_types): """ Make an object for the location, which has: {coordinate : integer, reference : reference_id, types = []} where the strand is indicated in the type array :param coordinate: :param reference_id: ...
[ "def", "_getLocation", "(", "self", ",", "coordinate", ",", "reference_id", ",", "strand", ",", "position_types", ")", ":", "loc", "=", "{", "}", "loc", "[", "'coordinate'", "]", "=", "coordinate", "loc", "[", "'reference'", "]", "=", "reference_id", "loc"...
30.185185
16.037037
def get_id_transcripts(self, hgnc_id, build='37'): """Return a set with identifier transcript(s) Choose all refseq transcripts with NM symbols, if none where found choose ONE with NR, if no NR choose ONE with XM. If there are no RefSeq transcripts identifiers choose the longest ensembl...
[ "def", "get_id_transcripts", "(", "self", ",", "hgnc_id", ",", "build", "=", "'37'", ")", ":", "transcripts", "=", "self", ".", "transcripts", "(", "build", "=", "build", ",", "hgnc_id", "=", "hgnc_id", ")", "identifier_transcripts", "=", "set", "(", ")", ...
28.510638
18.553191
def _load_class(class_path, default): """ Loads the class from the class_path string """ if class_path is None: return default component = class_path.rsplit('.', 1) result_processor = getattr( importlib.import_module(component[0]), component[1], default ) if len(comp...
[ "def", "_load_class", "(", "class_path", ",", "default", ")", ":", "if", "class_path", "is", "None", ":", "return", "default", "component", "=", "class_path", ".", "rsplit", "(", "'.'", ",", "1", ")", "result_processor", "=", "getattr", "(", "importlib", "...
27.692308
14.461538
def run(self): """Runs the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance Returns: ``None`` """ target = getattr(self, '_Thread__target', getattr(self, '_target', None)) args = getattr(self, '_Thread__args', getattr(self, '_args', N...
[ "def", "run", "(", "self", ")", ":", "target", "=", "getattr", "(", "self", ",", "'_Thread__target'", ",", "getattr", "(", "self", ",", "'_target'", ",", "None", ")", ")", "args", "=", "getattr", "(", "self", ",", "'_Thread__args'", ",", "getattr", "("...
30.9375
24.8125
def epanechnikov(xx, idx=None): """ The Epanechnikov kernel estimated for xx values at indices idx (zero elsewhere) Parameters ---------- xx: float array Values of the function on which the kernel is computed. Typically, these are Euclidean distances from some point x0 (see do_...
[ "def", "epanechnikov", "(", "xx", ",", "idx", "=", "None", ")", ":", "ans", "=", "np", ".", "zeros", "(", "xx", ".", "shape", ")", "ans", "[", "idx", "]", "=", "0.75", "*", "(", "1", "-", "xx", "[", "idx", "]", "**", "2", ")", "return", "an...
27.913043
24.608696
def recv_all(self, timeout='default'): """ Return all data recieved until connection closes. Aliases: read_all, readall, recvall """ self._print_recv_header('======== Receiving until close{timeout_text} ========', timeout) return self._recv_predicate(lambda s: 0, timeo...
[ "def", "recv_all", "(", "self", ",", "timeout", "=", "'default'", ")", ":", "self", ".", "_print_recv_header", "(", "'======== Receiving until close{timeout_text} ========'", ",", "timeout", ")", "return", "self", ".", "_recv_predicate", "(", "lambda", "s", ":", "...
33.1
23.3
def build_callback_url(request, urlname, message): """ Build Twilio callback url for confirming message delivery status :type message: OutgoingSMS """ location = reverse(urlname, kwargs={"pk": message.pk}) callback_domain = getattr(settings, "TWILIO_CALLBACK_DOMAIN", None) if callback_doma...
[ "def", "build_callback_url", "(", "request", ",", "urlname", ",", "message", ")", ":", "location", "=", "reverse", "(", "urlname", ",", "kwargs", "=", "{", "\"pk\"", ":", "message", ".", "pk", "}", ")", "callback_domain", "=", "getattr", "(", "settings", ...
31.625
21.958333
def notify(cls, user_or_email_, object_id=None, **filters): """Start notifying the given user or email address when this event occurs and meets the criteria given in ``filters``. Return the created (or the existing matching) Watch so you can call :meth:`~tidings.models.Watch.activate()`...
[ "def", "notify", "(", "cls", ",", "user_or_email_", ",", "object_id", "=", "None", ",", "*", "*", "filters", ")", ":", "# A test-for-existence-then-create race condition exists here, but it", "# doesn't matter: de-duplication on fire() and deletion of all matches", "# on stop_not...
46.140625
18.46875
def reset(self): """Reset the input buffer and associated state.""" super(IPythonInputSplitter, self).reset() self._buffer_raw[:] = [] self.source_raw = '' self.cell_magic_parts = [] self.processing_cell_magic = False
[ "def", "reset", "(", "self", ")", ":", "super", "(", "IPythonInputSplitter", ",", "self", ")", ".", "reset", "(", ")", "self", ".", "_buffer_raw", "[", ":", "]", "=", "[", "]", "self", ".", "source_raw", "=", "''", "self", ".", "cell_magic_parts", "=...
37
8.714286
def config_wdl(args): """ Retrieve the WDL for a method config in a workspace, send stdout """ r = fapi.get_workspace_config(args.project, args.workspace, args.namespace, args.config) fapi._check_response_code(r, 200) method = r.json()["methodRepoMethod"] args....
[ "def", "config_wdl", "(", "args", ")", ":", "r", "=", "fapi", ".", "get_workspace_config", "(", "args", ".", "project", ",", "args", ".", "workspace", ",", "args", ".", "namespace", ",", "args", ".", "config", ")", "fapi", ".", "_check_response_code", "(...
39.166667
14.333333
def do(self, arg): ".example - This is an example plugin for the command line debugger" print "This is an example command." print "%s.do(%r, %r):" % (__name__, self, arg) print " last event", self.lastEvent print " prefix", self.cmdprefix print " arguments", self.split_tokens(arg)
[ "def", "do", "(", "self", ",", "arg", ")", ":", "print", "\"This is an example command.\"", "print", "\"%s.do(%r, %r):\"", "%", "(", "__name__", ",", "self", ",", "arg", ")", "print", "\" last event\"", ",", "self", ".", "lastEvent", "print", "\" prefix\"", ...
43.142857
10.857143
def project_role(self, project, id): """Get a role Resource. :param project: ID or key of the project to get the role from :param id: ID of the role to get """ if isinstance(id, Number): id = "%s" % id return self._find_for_resource(Role, (project, id))
[ "def", "project_role", "(", "self", ",", "project", ",", "id", ")", ":", "if", "isinstance", "(", "id", ",", "Number", ")", ":", "id", "=", "\"%s\"", "%", "id", "return", "self", ".", "_find_for_resource", "(", "Role", ",", "(", "project", ",", "id",...
34
12.444444
def reverse(self): """ In place reverses the list. Very expensive on large data sets. The reversed list will be persisted to the redis :prop:_client as well. """ tmp_list = RedisList( randint(0, 100000000), prefix=self.key_prefix, client=self._clie...
[ "def", "reverse", "(", "self", ")", ":", "tmp_list", "=", "RedisList", "(", "randint", "(", "0", ",", "100000000", ")", ",", "prefix", "=", "self", ".", "key_prefix", ",", "client", "=", "self", ".", "_client", ",", "serializer", "=", "self", ".", "s...
36.863636
16.909091
async def stop(self): """ Stops the player, if playing. """ await self._lavalink.ws.send(op='stop', guildId=self.guild_id) self.current = None
[ "async", "def", "stop", "(", "self", ")", ":", "await", "self", ".", "_lavalink", ".", "ws", ".", "send", "(", "op", "=", "'stop'", ",", "guildId", "=", "self", ".", "guild_id", ")", "self", ".", "current", "=", "None" ]
41.5
15.5
def get_intercept_only_candidate_models(data, weights_col): """ Return a list of a single candidate intercept-only model. Parameters ---------- data : :any:`pandas.DataFrame` A DataFrame containing at least the column ``meter_value``. DataFrames of this form can be made using the ...
[ "def", "get_intercept_only_candidate_models", "(", "data", ",", "weights_col", ")", ":", "model_type", "=", "\"intercept_only\"", "formula", "=", "\"meter_value ~ 1\"", "if", "weights_col", "is", "None", ":", "weights", "=", "1", "else", ":", "weights", "=", "data...
28.655738
21.639344
def pci_lookup_name4( access: (IN, ctypes.POINTER(pci_access)), buf: (IN, ctypes.c_char_p), size: (IN, ctypes.c_int), flags: (IN, ctypes.c_int), arg1: (IN, ctypes.c_int), arg2: (IN, ctypes.c_int), arg3: (IN, ctypes.c_int), arg4: (IN, ctypes.c_int), ) -> ctypes.c_char_p: """ Conve...
[ "def", "pci_lookup_name4", "(", "access", ":", "(", "IN", ",", "ctypes", ".", "POINTER", "(", "pci_access", ")", ")", ",", "buf", ":", "(", "IN", ",", "ctypes", ".", "c_char_p", ")", ",", "size", ":", "(", "IN", ",", "ctypes", ".", "c_int", ")", ...
30.285714
18.571429
def blogurl(parser, token): """ Compatibility tag to allow django-fluent-blogs to operate stand-alone. Either the app can be hooked in the URLconf directly, or it can be added as a pagetype of django-fluent-pages. For the former, URL resolving works via the normal '{% url "viewname" arg1 arg2 %}' syntax...
[ "def", "blogurl", "(", "parser", ",", "token", ")", ":", "if", "HAS_APP_URLS", ":", "from", "fluent_pages", ".", "templatetags", ".", "appurl_tags", "import", "appurl", "return", "appurl", "(", "parser", ",", "token", ")", "else", ":", "from", "django", "....
48.307692
24.923077
def add_command(self, cmd_name, *args): """Add command to action.""" self.__commands.append(Command(cmd_name, args))
[ "def", "add_command", "(", "self", ",", "cmd_name", ",", "*", "args", ")", ":", "self", ".", "__commands", ".", "append", "(", "Command", "(", "cmd_name", ",", "args", ")", ")" ]
43.333333
5.333333
def get_instance(self, payload): """ Build an instance of MessageInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.message.MessageInstance :rtype: twilio.rest.api.v2010.account.message.MessageInstance """ return ...
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "MessageInstance", "(", "self", ".", "_version", ",", "payload", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", ")" ]
39.5
22.9
def from_file(cls, filepath): """Alternative constructor to get Torrent object from file. :param str filepath: :rtype: Torrent """ torrent = cls(Bencode.read_file(filepath)) torrent._filepath = filepath return torrent
[ "def", "from_file", "(", "cls", ",", "filepath", ")", ":", "torrent", "=", "cls", "(", "Bencode", ".", "read_file", "(", "filepath", ")", ")", "torrent", ".", "_filepath", "=", "filepath", "return", "torrent" ]
29.555556
12.444444
def get_url(self, request, *, date=None, size_x=None, size_y=None, geometry=None): """ Returns url to Sentinel Hub's OGC service for the product specified by the OgcRequest and date. :param request: OGC-type request with specified bounding box, cloud coverage for specific product. :type request...
[ "def", "get_url", "(", "self", ",", "request", ",", "*", ",", "date", "=", "None", ",", "size_x", "=", "None", ",", "size_y", "=", "None", ",", "geometry", "=", "None", ")", ":", "url", "=", "self", ".", "get_base_url", "(", "request", ")", "author...
53.366667
22.566667
def download(url, file_name, headers=None, show_progress=True): '''stream to a temporary file, rename on successful completion Parameters ========== file_name: the file name to stream to url: the url to stream from headers: additional headers to add ''' fd, tmp_file...
[ "def", "download", "(", "url", ",", "file_name", ",", "headers", "=", "None", ",", "show_progress", "=", "True", ")", ":", "fd", ",", "tmp_file", "=", "tempfile", ".", "mkstemp", "(", "prefix", "=", "(", "\"%s.tmp.\"", "%", "file_name", ")", ")", "os",...
32
22.3
def _random_token(self, bits=128): """ Generates a random token, using the url-safe base64 alphabet. The "bits" argument specifies the bits of randomness to use. """ alphabet = string.ascii_letters + string.digits + '-_' # alphabet length is 64, so each letter provides lg...
[ "def", "_random_token", "(", "self", ",", "bits", "=", "128", ")", ":", "alphabet", "=", "string", ".", "ascii_letters", "+", "string", ".", "digits", "+", "'-_'", "# alphabet length is 64, so each letter provides lg(64) = 6 bits", "num_letters", "=", "int", "(", ...
50
17.777778
def _set_traffic_state(self, v, load=False): """ Setter method for traffic_state, mapped from YANG variable /traffic_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_traffic_state is considered as a private method. Backends looking to populate this v...
[ "def", "_set_traffic_state", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "...
73.333333
34.625
def on_change_checkout(self): ''' When you change checkin_date or checkout_date it will checked it and update the qty of hotel service line ----------------------------------------------------------------- @param self: object pointer ''' if not self.ser_checkin_da...
[ "def", "on_change_checkout", "(", "self", ")", ":", "if", "not", "self", ".", "ser_checkin_date", ":", "time_a", "=", "time", ".", "strftime", "(", "DEFAULT_SERVER_DATETIME_FORMAT", ")", "self", ".", "ser_checkin_date", "=", "time_a", "if", "not", "self", ".",...
49.909091
17.727273
def ObjectModifiedEventHandler(instance, event): """ Various types need automation on edit. """ if not hasattr(instance, 'portal_type'): return if instance.portal_type == 'Pricelist': """ Create price list line items """ # Remove existing line items instance.pric...
[ "def", "ObjectModifiedEventHandler", "(", "instance", ",", "event", ")", ":", "if", "not", "hasattr", "(", "instance", ",", "'portal_type'", ")", ":", "return", "if", "instance", ".", "portal_type", "==", "'Pricelist'", ":", "\"\"\" Create price list line items\n ...
40.461538
12.538462
def wait_ssh_open(server, port, keep_waiting=None, timeout=None): """ Wait for network service to appear @param server: host to connect to (str) @param port: port (int) @param timeout: in seconds, if None or 0 wait forever @return: True of False, if timeout is None may return only Tr...
[ "def", "wait_ssh_open", "(", "server", ",", "port", ",", "keep_waiting", "=", "None", ",", "timeout", "=", "None", ")", ":", "import", "socket", "import", "errno", "import", "time", "log", "=", "logging", ".", "getLogger", "(", "'wait_ssh_open'", ")", "sle...
33.850746
17.447761
def full_name(decl, with_defaults=True): """ Returns declaration full qualified name. If `decl` belongs to anonymous namespace or class, the function will return C++ illegal qualified name. Args: decl (declaration_t): declaration for which the full qualified name ...
[ "def", "full_name", "(", "decl", ",", "with_defaults", "=", "True", ")", ":", "if", "None", "is", "decl", ":", "raise", "RuntimeError", "(", "\"Unable to generate full name for None object!\"", ")", "if", "with_defaults", ":", "if", "not", "decl", ".", "cache", ...
37.102564
20.179487
def get_model(self, model_ref, retry=DEFAULT_RETRY): """[Beta] Fetch the model referenced by ``model_ref``. Args: model_ref (Union[ \ :class:`~google.cloud.bigquery.model.ModelReference`, \ str, \ ]): A reference to the model to f...
[ "def", "get_model", "(", "self", ",", "model_ref", ",", "retry", "=", "DEFAULT_RETRY", ")", ":", "if", "isinstance", "(", "model_ref", ",", "str", ")", ":", "model_ref", "=", "ModelReference", ".", "from_string", "(", "model_ref", ",", "default_project", "="...
40.115385
19.846154
def walk_target_deps_topological_order(self, target: Target): """Generate all dependencies of `target` by topological sort order.""" all_deps = get_descendants(self.target_graph, target.name) for dep_name in topological_sort(self.target_graph): if dep_name in all_deps: ...
[ "def", "walk_target_deps_topological_order", "(", "self", ",", "target", ":", "Target", ")", ":", "all_deps", "=", "get_descendants", "(", "self", ".", "target_graph", ",", "target", ".", "name", ")", "for", "dep_name", "in", "topological_sort", "(", "self", "...
57.5
12.5
def get_unspents(self): """Fetches all available unspent transaction outputs. :rtype: ``list`` of :class:`~bitcash.network.meta.Unspent` """ self.unspents[:] = NetworkAPI.get_unspent(self.address) self.balance = sum(unspent.amount for unspent in self.unspents) return sel...
[ "def", "get_unspents", "(", "self", ")", ":", "self", ".", "unspents", "[", ":", "]", "=", "NetworkAPI", ".", "get_unspent", "(", "self", ".", "address", ")", "self", ".", "balance", "=", "sum", "(", "unspent", ".", "amount", "for", "unspent", "in", ...
40.375
18.625
def simple_md2html(text, urls): ''' Convert a text from md to html ''' retval = special_links_replace(text, urls) # Create a par break for double newlines retval = re.sub(r'\n\n', r'</p><p>', retval) # Create a visual br for every new line retval = re.sub(r'\n', r'<br />\n', retval) # Do we ...
[ "def", "simple_md2html", "(", "text", ",", "urls", ")", ":", "retval", "=", "special_links_replace", "(", "text", ",", "urls", ")", "# Create a par break for double newlines", "retval", "=", "re", ".", "sub", "(", "r'\\n\\n'", ",", "r'</p><p>'", ",", "retval", ...
43
8.636364
def _get_dtype_maps(): """ Get dictionaries to map numpy data types to ITK types and the other way around. """ # Define pairs tmp = [ (np.float32, 'MET_FLOAT'), (np.float64, 'MET_DOUBLE'), (np.uint8, 'MET_UCHAR'), (np.int8, 'MET_CHAR'), (np.uint16, 'MET_USHORT'), (...
[ "def", "_get_dtype_maps", "(", ")", ":", "# Define pairs", "tmp", "=", "[", "(", "np", ".", "float32", ",", "'MET_FLOAT'", ")", ",", "(", "np", ".", "float64", ",", "'MET_DOUBLE'", ")", ",", "(", "np", ".", "uint8", ",", "'MET_UCHAR'", ")", ",", "(",...
33.15
18.8
def pipe_createrss(context=None, _INPUT=None, conf=None, **kwargs): """An operator that converts a source into an RSS stream. Not loopable. """ conf = DotDict(conf) for item in _INPUT: item = DotDict(item) yield { value: item.get(conf.get(key, **kwargs)) for ke...
[ "def", "pipe_createrss", "(", "context", "=", "None", ",", "_INPUT", "=", "None", ",", "conf", "=", "None", ",", "*", "*", "kwargs", ")", ":", "conf", "=", "DotDict", "(", "conf", ")", "for", "item", "in", "_INPUT", ":", "item", "=", "DotDict", "("...
28.333333
19.833333
def get_field_label_css_class(self, bound_field): """ Returns the optional label CSS class to use when rendering a field template. By default, returns the Form class property `field_label_css_class`. If the field has errors and the Form class property `field_label_invalid_css_class` ...
[ "def", "get_field_label_css_class", "(", "self", ",", "bound_field", ")", ":", "class_name", "=", "self", ".", "field_label_css_class", "if", "bound_field", ".", "errors", "and", "self", ".", "field_label_invalid_css_class", ":", "class_name", "=", "join_css_class", ...
41.777778
23.555556
def smooth(data, fw): """Smooth data with a moving average.""" if fw == 0: fdata = data else: fdata = lfilter(np.ones(fw)/fw, 1, data) return fdata
[ "def", "smooth", "(", "data", ",", "fw", ")", ":", "if", "fw", "==", "0", ":", "fdata", "=", "data", "else", ":", "fdata", "=", "lfilter", "(", "np", ".", "ones", "(", "fw", ")", "/", "fw", ",", "1", ",", "data", ")", "return", "fdata" ]
25.571429
17.714286
def execute_ssh_command(client, cmd): """ Execute given command using paramiko. Returns: String output of cmd execution. Raises: IpaSSHException: If stderr returns a non-empty string. """ try: stdin, stdout, stderr = client.exec_command(cmd) err = stderr.read() ...
[ "def", "execute_ssh_command", "(", "client", ",", "cmd", ")", ":", "try", ":", "stdin", ",", "stdout", ",", "stderr", "=", "client", ".", "exec_command", "(", "cmd", ")", "err", "=", "stderr", ".", "read", "(", ")", "out", "=", "stdout", ".", "read",...
26.222222
16.888889
def get_password(from_stdin_only=False): """ Get a password either from STDIN or by prompting the user. :return: the password. """ if not sys.stdin.isatty(): password = sys.stdin.readline().strip() elif not from_stdin_only: password = getpass.getpass('Enter the password: ') ...
[ "def", "get_password", "(", "from_stdin_only", "=", "False", ")", ":", "if", "not", "sys", ".", "stdin", ".", "isatty", "(", ")", ":", "password", "=", "sys", ".", "stdin", ".", "readline", "(", ")", ".", "strip", "(", ")", "elif", "not", "from_stdin...
25.5
16.5
def exists(device=''): ''' Check to see if the partition exists CLI Example: .. code-block:: bash salt '*' partition.exists /dev/sdb1 ''' if os.path.exists(device): dev = os.stat(device).st_mode if stat.S_ISBLK(dev): return True return False
[ "def", "exists", "(", "device", "=", "''", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "device", ")", ":", "dev", "=", "os", ".", "stat", "(", "device", ")", ".", "st_mode", "if", "stat", ".", "S_ISBLK", "(", "dev", ")", ":", "return...
17.294118
23.058824
def write_script(self): """ Write the workflow to a script (.sh instead of .dag). Assuming that parents were added to the DAG before their children, dependencies should be handled correctly. """ if not self.__dag_file_path: raise CondorDAGError, "No path for DAG file" try: dfp =...
[ "def", "write_script", "(", "self", ")", ":", "if", "not", "self", ".", "__dag_file_path", ":", "raise", "CondorDAGError", ",", "\"No path for DAG file\"", "try", ":", "dfp", "=", "self", ".", "__dag_file_path", "outfilename", "=", "\".\"", ".", "join", "(", ...
35.148148
18.333333
def create_portable_topology(topol, struct, **kwargs): """Create a processed topology. The processed (or portable) topology file does not contain any ``#include`` statements and hence can be easily copied around. It also makes it possible to re-grompp without having any special itp files available....
[ "def", "create_portable_topology", "(", "topol", ",", "struct", ",", "*", "*", "kwargs", ")", ":", "_topoldir", ",", "_topol", "=", "os", ".", "path", ".", "split", "(", "topol", ")", "processed", "=", "kwargs", ".", "pop", "(", "'processed'", ",", "os...
36.181818
19.545455
def dict_stack(dict_list, key_prefix=''): r""" stacks values from two dicts into a new dict where the values are list of the input values. the keys are the same. DEPRICATE in favor of dict_stack2 Args: dict_list (list): list of dicts with similar keys Returns: dict dict_stacke...
[ "def", "dict_stack", "(", "dict_list", ",", "key_prefix", "=", "''", ")", ":", "dict_stacked_", "=", "defaultdict", "(", "list", ")", "for", "dict_", "in", "dict_list", ":", "for", "key", ",", "val", "in", "six", ".", "iteritems", "(", "dict_", ")", ":...
34.104167
16.75
def validate_confirm_form(self): """ Third and final step of ExpressCheckout. Request has pressed the confirmation but and we can send the final confirmation to PayPal using the data from the POST'ed form. """ wpp = PayPalWPP(self.request) pp_data = dict(token=self.reques...
[ "def", "validate_confirm_form", "(", "self", ")", ":", "wpp", "=", "PayPalWPP", "(", "self", ".", "request", ")", "pp_data", "=", "dict", "(", "token", "=", "self", ".", "request", ".", "POST", "[", "'token'", "]", ",", "payerid", "=", "self", ".", "...
42.090909
20.090909