text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def replace(self, ): """Replace the current reftrack :returns: None :rtype: None :raises: None """ tfi = self.get_taskfileinfo_selection() if tfi: self.reftrack.replace(tfi)
[ "def", "replace", "(", "self", ",", ")", ":", "tfi", "=", "self", ".", "get_taskfileinfo_selection", "(", ")", "if", "tfi", ":", "self", ".", "reftrack", ".", "replace", "(", "tfi", ")" ]
23.3
15.1
def extract_message_to_dict(filename): """ Read in a text file that java messages to be ignored and generate a dictionary structure out of it with key and value pairs. The keys are test names and the values are lists of java message strings associated with that test name where we are either going to ad...
[ "def", "extract_message_to_dict", "(", "filename", ")", ":", "message_dict", "=", "{", "}", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "# open file to read in new exclude messages if it exists", "with", "open", "(", "filename", ",", "'r'", ...
37.432836
27.462687
def clock_plot(self, add_internal=False, ax=None, regression=None, confidence=True, n_sigma = 2, fs=14): """Plot root-to-tip distance vs time as a basic time-tree diagnostic Parameters ---------- add_internal : bool, optional add internal nodes. this will ...
[ "def", "clock_plot", "(", "self", ",", "add_internal", "=", "False", ",", "ax", "=", "None", ",", "regression", "=", "None", ",", "confidence", "=", "True", ",", "n_sigma", "=", "2", ",", "fs", "=", "14", ")", ":", "import", "matplotlib", ".", "pyplo...
45.851064
25.159574
def find_category(**kwargs): """Return a list with matching Category arguments. :param kwargs: PYBOSSA Category members :rtype: list :returns: A list of project that match the kwargs """ try: res = _pybossa_req('get', 'category', params=kwargs) if type(res).__name__ == 'list': ...
[ "def", "find_category", "(", "*", "*", "kwargs", ")", ":", "try", ":", "res", "=", "_pybossa_req", "(", "'get'", ",", "'category'", ",", "params", "=", "kwargs", ")", "if", "type", "(", "res", ")", ".", "__name__", "==", "'list'", ":", "return", "[",...
27.9375
17.75
def open(self, connection=None): """Open the client. The client can create a new Connection or an existing Connection can be passed in. This existing Connection may have an existing CBS authentication Session, which will be used for this client as well. Otherwise a new Session will be ...
[ "def", "open", "(", "self", ",", "connection", "=", "None", ")", ":", "# pylint: disable=protected-access", "if", "self", ".", "_session", ":", "return", "# already open.", "_logger", ".", "debug", "(", "\"Opening client connection.\"", ")", "if", "connection", ":...
45.096154
13.5
def get_template(self, template_id, version=None, timeout=None): """ API call to get a specific template """ if (version): return self._api_request( self.TEMPLATES_VERSION_ENDPOINT % (template_id, version), self.HTTP_GET, timeout=timeout ...
[ "def", "get_template", "(", "self", ",", "template_id", ",", "version", "=", "None", ",", "timeout", "=", "None", ")", ":", "if", "(", "version", ")", ":", "return", "self", ".", "_api_request", "(", "self", ".", "TEMPLATES_VERSION_ENDPOINT", "%", "(", "...
36.214286
16
def a2s_rules(server_addr, timeout=2, challenge=0): """Get rules from server :param server_addr: (ip, port) for the server :type server_addr: tuple :param timeout: (optional) timeout in seconds :type timeout: float :param challenge: (optional) challenge number :type challenge: int :r...
[ "def", "a2s_rules", "(", "server_addr", ",", "timeout", "=", "2", ",", "challenge", "=", "0", ")", ":", "ss", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", "ss", ".", "connect", "(", "server_addr", ...
26.625
20.107143
def plot_fit(self,intervals=False,**kwargs): """ Plots the fit of the model Parameters ---------- intervals : Boolean Whether to plot 95% confidence interval of states Returns ---------- None (plots data and the fit) """ import matplo...
[ "def", "plot_fit", "(", "self", ",", "intervals", "=", "False", ",", "*", "*", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "import", "seaborn", "as", "sns", "figsize", "=", "kwargs", ".", "get", "(", "'figsize'", ",", "(", ...
40.269841
23.142857
def save_csv(self, csv_location): # type: (str) -> None """ Save the csv to a file """ with open(csv_location, 'w') as csv_handle: writer = csv.writer(csv_handle) for row in self.csv_data: writer.writerow(row)
[ "def", "save_csv", "(", "self", ",", "csv_location", ")", ":", "# type: (str) -> None", "with", "open", "(", "csv_location", ",", "'w'", ")", "as", "csv_handle", ":", "writer", "=", "csv", ".", "writer", "(", "csv_handle", ")", "for", "row", "in", "self", ...
43.5
6.166667
def _CheckAttribute(self, attribute, value): """Check that the value is of the expected type. Args: attribute: An instance of Attribute(). value: An instance of RDFValue. Raises: ValueError: when the value is not of the expected type. AttributeError: When the attribute is not o...
[ "def", "_CheckAttribute", "(", "self", ",", "attribute", ",", "value", ")", ":", "if", "not", "isinstance", "(", "attribute", ",", "Attribute", ")", ":", "raise", "AttributeError", "(", "\"Attribute %s must be of type aff4.Attribute()\"", "%", "attribute", ")", "i...
38.277778
20
def log_call( wrapped_function=None, action_type=None, include_args=None, include_result=True ): """Decorator/decorator factory that logs inputs and the return result. If used with inputs (i.e. as a decorator factory), it accepts the following parameters: @param action_type: The action...
[ "def", "log_call", "(", "wrapped_function", "=", "None", ",", "action_type", "=", "None", ",", "include_args", "=", "None", ",", "include_result", "=", "True", ")", ":", "if", "wrapped_function", "is", "None", ":", "return", "partial", "(", "log_call", ",", ...
36.584906
21.849057
def Buscar(self, nro_doc, tipo_doc=80): "Devuelve True si fue encontrado y establece atributos con datos" # cuit: codigo único de identificación tributaria del contribuyente # (sin guiones) self.cursor.execute("SELECT * FROM padron WHERE " " tipo_doc=? A...
[ "def", "Buscar", "(", "self", ",", "nro_doc", ",", "tipo_doc", "=", "80", ")", ":", "# cuit: codigo único de identificación tributaria del contribuyente", "# (sin guiones)", "self", ".", "cursor", ".", "execute", "(", "\"SELECT * FROM padron WHERE \"", "\" tipo_doc=? ...
36.6
12.085714
def make_open_functions(): """From the current state of ``registry``, create open_* functions""" # Create shortcut open methods if hasattr(str, 'isidentifier'): def isidentifier(x): return x.isidentifier() else: IDENTIFIER_REGEX = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*$') ...
[ "def", "make_open_functions", "(", ")", ":", "# Create shortcut open methods", "if", "hasattr", "(", "str", ",", "'isidentifier'", ")", ":", "def", "isidentifier", "(", "x", ")", ":", "return", "x", ".", "isidentifier", "(", ")", "else", ":", "IDENTIFIER_REGEX...
40.842105
10.368421
def setup_data_split(X, y, tokenizer, proc_data_dir, **kwargs): """Setup data while splitting into a training, validation, and test set. Args: X: text data, y: data labels, tokenizer: A Tokenizer instance proc_data_dir: Directory for the split and processed d...
[ "def", "setup_data_split", "(", "X", ",", "y", ",", "tokenizer", ",", "proc_data_dir", ",", "*", "*", "kwargs", ")", ":", "X_train", ",", "X_val", ",", "X_test", ",", "y_train", ",", "y_val", ",", "y_test", "=", "split_data", "(", "X", ",", "y", ")",...
38.95
16.9
def _update_panic_status(self, status=None): """ Updates the panic status of the alarm panel. :param status: status to use to update :type status: boolean :returns: boolean indicating the new status """ if status is None: return if status !=...
[ "def", "_update_panic_status", "(", "self", ",", "status", "=", "None", ")", ":", "if", "status", "is", "None", ":", "return", "if", "status", "!=", "self", ".", "_panic_status", ":", "self", ".", "_panic_status", ",", "old_status", "=", "status", ",", "...
27.684211
17.684211
def _get_item(self, question_id): """we need a middle-man method to convert the unique "assessment-session" authority question_ids into "real" itemIds BUT this also has to return the "magic" item, so we can't rely on question = self.get_question(question_id) ...
[ "def", "_get_item", "(", "self", ",", "question_id", ")", ":", "question_map", "=", "self", ".", "_get_question_map", "(", "question_id", ")", "# Throws NotFound()", "real_question_id", "=", "Id", "(", "question_map", "[", "'questionId'", "]", ")", "return", "se...
53.75
18.916667
def zoning_enabled_configuration_default_zone_access(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") zoning = ET.SubElement(config, "zoning", xmlns="urn:brocade.com:mgmt:brocade-zone") enabled_configuration = ET.SubElement(zoning, "enabled-configuration"...
[ "def", "zoning_enabled_configuration_default_zone_access", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "zoning", "=", "ET", ".", "SubElement", "(", "config", ",", "\"zoning\"", ",", "xmlns", "=...
51
24
def add_compare_chains_parser(subparsers, parent_parser): """Creates the arg parsers needed for the compare command. """ parser = subparsers.add_parser( 'compare-chains', help='Compare chains from different nodes.', description=( 'Compute and display information about how...
[ "def", "add_compare_chains_parser", "(", "subparsers", ",", "parent_parser", ")", ":", "parser", "=", "subparsers", ".", "add_parser", "(", "'compare-chains'", ",", "help", "=", "'Compare chains from different nodes.'", ",", "description", "=", "(", "'Compute and displa...
29.839286
24.785714
def _fixup_ins_del_tags(doc): """fixup_ins_del_tags that works on an lxml document in-place """ for tag in ['ins', 'del']: for el in doc.xpath('descendant-or-self::%s' % tag): if not _contains_block_level_tag(el): continue _move_el_inside_block(el, tag=tag) ...
[ "def", "_fixup_ins_del_tags", "(", "doc", ")", ":", "for", "tag", "in", "[", "'ins'", ",", "'del'", "]", ":", "for", "el", "in", "doc", ".", "xpath", "(", "'descendant-or-self::%s'", "%", "tag", ")", ":", "if", "not", "_contains_block_level_tag", "(", "e...
37.222222
9.666667
def get_conversations(self, **kwargs): """ Return list of conversations for the current user, most resent ones first. :calls: `GET /api/v1/conversations \ <https://canvas.instructure.com/doc/api/conversations.html#method.conversations.index>`_ :rtype: :class:`canvasapi.paginate...
[ "def", "get_conversations", "(", "self", ",", "*", "*", "kwargs", ")", ":", "from", "canvasapi", ".", "conversation", "import", "Conversation", "return", "PaginatedList", "(", "Conversation", ",", "self", ".", "__requester", ",", "'GET'", ",", "'conversations'",...
33.631579
20.263158
def __insert_frond_LF(d_w, d_u, dfs_data): """Encapsulates the process of inserting a frond uw into the left side frond group.""" # --Add the frond to the left side dfs_data['LF'].append( (d_w, d_u) ) dfs_data['FG']['l'] += 1 dfs_data['last_inserted_side'] = 'LF'
[ "def", "__insert_frond_LF", "(", "d_w", ",", "d_u", ",", "dfs_data", ")", ":", "# --Add the frond to the left side", "dfs_data", "[", "'LF'", "]", ".", "append", "(", "(", "d_w", ",", "d_u", ")", ")", "dfs_data", "[", "'FG'", "]", "[", "'l'", "]", "+=", ...
39.714286
8.285714
def to_pypsa(network, mode, timesteps): """ Translate graph based grid representation to PyPSA Network For details from a user perspective see API documentation of :meth:`~.grid.network.EDisGo.analyze` of the API class :class:`~.grid.network.EDisGo`. Translating eDisGo's grid topology to PyPSA...
[ "def", "to_pypsa", "(", "network", ",", "mode", ",", "timesteps", ")", ":", "# check if timesteps is array-like, otherwise convert to list (necessary", "# to obtain a dataframe when using .loc in time series functions)", "if", "not", "hasattr", "(", "timesteps", ",", "\"__len__\"...
44
25.205882
def expireat(key, timestamp, host=None, port=None, db=None, password=None): ''' Set a keys expire at given UNIX time CLI Example: .. code-block:: bash salt '*' redis.expireat foo 1400000000 ''' server = _connect(host, port, db, password) return server.expireat(key, timestamp)
[ "def", "expireat", "(", "key", ",", "timestamp", ",", "host", "=", "None", ",", "port", "=", "None", ",", "db", "=", "None", ",", "password", "=", "None", ")", ":", "server", "=", "_connect", "(", "host", ",", "port", ",", "db", ",", "password", ...
25.333333
23
def prox_gradf_lim(xy, step, boundary=None): """Forward-backward step: gradient, followed by projection""" return prox_lim(prox_gradf(xy,step), step, boundary=boundary)
[ "def", "prox_gradf_lim", "(", "xy", ",", "step", ",", "boundary", "=", "None", ")", ":", "return", "prox_lim", "(", "prox_gradf", "(", "xy", ",", "step", ")", ",", "step", ",", "boundary", "=", "boundary", ")" ]
58
9.666667
def main(*argv): """ main driver of program """ try: # Inputs # adminUsername = argv[0] adminPassword = argv[1] siteURL = argv[2] username = argv[3] subFolders = argv[4].lower() == "true" # Logic # sh = arcrest.AGOLTokenSecurity...
[ "def", "main", "(", "*", "argv", ")", ":", "try", ":", "# Inputs", "#", "adminUsername", "=", "argv", "[", "0", "]", "adminPassword", "=", "argv", "[", "1", "]", "siteURL", "=", "argv", "[", "2", "]", "username", "=", "argv", "[", "3", "]", "su...
43.785714
20.428571
def get_log_level(args): # type: (typing.Dict[str, typing.Any]) -> int """Get the log level from the CLI arguments. Removes logging arguments from sys.argv. Args: args: The parsed docopt arguments to be used to determine the logging level. Returns: The correct log leve...
[ "def", "get_log_level", "(", "args", ")", ":", "# type: (typing.Dict[str, typing.Any]) -> int", "index", "=", "-", "1", "log_level", "=", "None", "if", "'<command>'", "in", "args", "and", "args", "[", "'<command>'", "]", ":", "index", "=", "sys", ".", "argv", ...
36.35
18.275
def __convert_enum(node): """Converts an EnumProperty node to JSON format.""" name = __get_attribute(node, 'Name') logging.debug('Found EnumProperty named %s', name) converted_values = [] for value in node.getElementsByTagName('EnumValue'): converted = __convert_node(value) conver...
[ "def", "__convert_enum", "(", "node", ")", ":", "name", "=", "__get_attribute", "(", "node", ",", "'Name'", ")", "logging", ".", "debug", "(", "'Found EnumProperty named %s'", ",", "name", ")", "converted_values", "=", "[", "]", "for", "value", "in", "node",...
28.315789
18.157895
def get_all_monomials(variables, extramonomials, substitutions, degree, removesubstitutions=True): """Return the monomials of a certain degree. """ monomials = get_monomials(variables, degree) if extramonomials is not None: monomials.extend(extramonomials) if removesubs...
[ "def", "get_all_monomials", "(", "variables", ",", "extramonomials", ",", "substitutions", ",", "degree", ",", "removesubstitutions", "=", "True", ")", ":", "monomials", "=", "get_monomials", "(", "variables", ",", "degree", ")", "if", "extramonomials", "is", "n...
47.333333
13.666667
def parse_value_reference(parser, event, node): #pylint: disable=unused-argument """Parse CIM/XML VALUE.REFERENCE element and call function for the child ELEMENT. Return the result of that element parser call. """ (next_event, next_node) = six.next(parser) # TODO 2/16 KS: Functions belo...
[ "def", "parse_value_reference", "(", "parser", ",", "event", ",", "node", ")", ":", "#pylint: disable=unused-argument", "(", "next_event", ",", "next_node", ")", "=", "six", ".", "next", "(", "parser", ")", "# TODO 2/16 KS: Functions below do not exist: i.e. class stuff...
37.72973
28.027027
def apps_job_status_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/apps#get-job-status" api_path = "/api/v2/apps/job_statuses/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
[ "def", "apps_job_status_show", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/apps/job_statuses/{id}.json\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "self", ".", "call", "(", ...
52.8
12.8
def _fft_convolve_gpu(data_g, h_g, res_g = None, plan = None, inplace = False, kernel_is_fft = False): """ fft convolve for gpu buffer """ assert_bufs_type(np.complex64,data_g,h_g) if data_g.shape != h_g.shape: raise ValueError("data and kernel mu...
[ "def", "_fft_convolve_gpu", "(", "data_g", ",", "h_g", ",", "res_g", "=", "None", ",", "plan", "=", "None", ",", "inplace", "=", "False", ",", "kernel_is_fft", "=", "False", ")", ":", "assert_bufs_type", "(", "np", ".", "complex64", ",", "data_g", ",", ...
23.428571
23.095238
def update_text(self): """ Write the current text, and check for any new text changes. This also updates the elapsed time. """ self.write() try: newtext = self.text_queue.get_nowait() self._text = newtext except Empty: pass
[ "def", "update_text", "(", "self", ")", ":", "self", ".", "write", "(", ")", "try", ":", "newtext", "=", "self", ".", "text_queue", ".", "get_nowait", "(", ")", "self", ".", "_text", "=", "newtext", "except", "Empty", ":", "pass" ]
30.2
13.4
def edit_scheme(self): """Edit current scheme.""" dlg = self.scheme_editor_dialog dlg.set_scheme(self.current_scheme) if dlg.exec_(): # Update temp scheme to reflect instant edits on the preview temporal_color_scheme = dlg.get_edited_color_scheme() fo...
[ "def", "edit_scheme", "(", "self", ")", ":", "dlg", "=", "self", ".", "scheme_editor_dialog", "dlg", ".", "set_scheme", "(", "self", ".", "current_scheme", ")", "if", "dlg", ".", "exec_", "(", ")", ":", "# Update temp scheme to reflect instant edits on the preview...
41.307692
13.461538
def install_os_updates(distribution, force=False): """ installs OS updates """ if ('centos' in distribution or 'rhel' in distribution or 'redhat' in distribution): bookshelf2.logging_helpers.log_green('installing OS updates') sudo("yum -y --quiet clean all") sudo(...
[ "def", "install_os_updates", "(", "distribution", ",", "force", "=", "False", ")", ":", "if", "(", "'centos'", "in", "distribution", "or", "'rhel'", "in", "distribution", "or", "'redhat'", "in", "distribution", ")", ":", "bookshelf2", ".", "logging_helpers", "...
47.043478
16.478261
def get(self, mail): """ Get one document store into LinShare.""" users = (v for v in self.list() if v.get('mail') == mail) for i in users: self.log.debug(i) return i return None
[ "def", "get", "(", "self", ",", "mail", ")", ":", "users", "=", "(", "v", "for", "v", "in", "self", ".", "list", "(", ")", "if", "v", ".", "get", "(", "'mail'", ")", "==", "mail", ")", "for", "i", "in", "users", ":", "self", ".", "log", "."...
32.571429
16.285714
def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name):...
[ "def", "_check_for_unit_changes", "(", "name", ")", ":", "contextkey", "=", "'systemd._check_for_unit_changes.{0}'", ".", "format", "(", "name", ")", "if", "contextkey", "not", "in", "__context__", ":", "if", "_untracked_custom_unit_found", "(", "name", ")", "or", ...
39.636364
20.909091
def _strip(text): """Strip articles/whitespace and remove case.""" text = text.strip() text = text.replace(' ', ' ') # remove duplicate spaces text = text.lower() for joiner in TextTitle.JOINERS: text = text.replace(joiner, 'and') for article in TextTitle.AR...
[ "def", "_strip", "(", "text", ")", ":", "text", "=", "text", ".", "strip", "(", ")", "text", "=", "text", ".", "replace", "(", "' '", ",", "' '", ")", "# remove duplicate spaces", "text", "=", "text", ".", "lower", "(", ")", "for", "joiner", "in", ...
37.666667
11.166667
def get_edges_with_citation(self, citation: Citation) -> List[Edge]: """Get the edges with the given citation.""" return self.session.query(Edge).join(Evidence).filter(Evidence.citation == citation)
[ "def", "get_edges_with_citation", "(", "self", ",", "citation", ":", "Citation", ")", "->", "List", "[", "Edge", "]", ":", "return", "self", ".", "session", ".", "query", "(", "Edge", ")", ".", "join", "(", "Evidence", ")", ".", "filter", "(", "Evidenc...
70.666667
26.666667
def getCeilingZoom(self, resolution, unit='meters'): """ Return the maximized zoom level for a given resolution Parameters: resolution -- max. resolution unit -- unit for output (default='meters') """ if resolution in self.RESOLUTIONS: return s...
[ "def", "getCeilingZoom", "(", "self", ",", "resolution", ",", "unit", "=", "'meters'", ")", ":", "if", "resolution", "in", "self", ".", "RESOLUTIONS", ":", "return", "self", ".", "getZoom", "(", "resolution", ")", "lo", ",", "hi", "=", "self", ".", "_g...
35.333333
10.4
def get_decomp_and_e_above_hull(self, entry, allow_negative=False): """ Provides the decomposition and energy above convex hull for an entry. Due to caching, can be much faster if entries with the same composition are processed together. Args: entry: A PDEntry like o...
[ "def", "get_decomp_and_e_above_hull", "(", "self", ",", "entry", ",", "allow_negative", "=", "False", ")", ":", "if", "entry", "in", "self", ".", "stable_entries", ":", "return", "{", "entry", ":", "1", "}", ",", "0", "comp", "=", "entry", ".", "composit...
44.966667
21.3
def dumps(self): """Return path command representation.""" ret_str = self.path_type if self.options is not None: ret_str += self.options.dumps() return ret_str
[ "def", "dumps", "(", "self", ")", ":", "ret_str", "=", "self", ".", "path_type", "if", "self", ".", "options", "is", "not", "None", ":", "ret_str", "+=", "self", ".", "options", ".", "dumps", "(", ")", "return", "ret_str" ]
22
19.666667
def get_boundaries_of_elements_in_dict(models_dict, clearance=0.): """ Get boundaries of all handed models The function checks all model meta data positions to increase boundary starting with a state or scoped variables. It is finally iterated over all states, data and logical port models and linkage if su...
[ "def", "get_boundaries_of_elements_in_dict", "(", "models_dict", ",", "clearance", "=", "0.", ")", ":", "# Determine initial outer coordinates", "right", "=", "0.", "bottom", "=", "0.", "if", "'states'", "in", "models_dict", "and", "models_dict", "[", "'states'", "]...
57.350649
32.493506
def get_edge_by_name(self, source_name: str, target_name: str) -> Optional[Edge]: """ Returns the edge connecting the nodes with the specified names if such an edge exists. Arguments: source_name (str): The name of one of the endpoints of queried edge. target_name ...
[ "def", "get_edge_by_name", "(", "self", ",", "source_name", ":", "str", ",", "target_name", ":", "str", ")", "->", "Optional", "[", "Edge", "]", ":", "nodes", ":", "NodeList", "=", "self", ".", "_graph", ".", "nodes", "source", ":", "Optional", "[", "N...
43.25
24.05
def on_queue_declareok(self, _): """Invoked by pika when queue is declared This method will start consuming or first bind the queue to the exchange if an exchange is provided. After binding, the on_bindok method will be invoked by pika. :param pika.frame.Method _: The Queue.De...
[ "def", "on_queue_declareok", "(", "self", ",", "_", ")", ":", "logger", ".", "debug", "(", "\"Binding %s to %s with %s\"", ",", "self", ".", "_exchange", ",", "self", ".", "_queue", ",", "self", ".", "_routing_key", ")", "if", "self", ".", "_exchange", ":"...
40.333333
25.666667
def blockgen(bytes, block_size=16): ''' a block generator for pprp ''' for i in range(0, len(bytes), block_size): block = bytes[i:i + block_size] block_len = len(block) if block_len > 0: yield block if block_len < block_size: break
[ "def", "blockgen", "(", "bytes", ",", "block_size", "=", "16", ")", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "bytes", ")", ",", "block_size", ")", ":", "block", "=", "bytes", "[", "i", ":", "i", "+", "block_size", "]", "block_le...
31.888889
9.444444
def statichttp(container = None): "wrap a WSGI-style function to a HTTPRequest event handler" def decorator(func): @functools.wraps(func) def handler(event): return _handler(container, event, func) if hasattr(func, '__self__'): handler.__self__ = func.__self__ ...
[ "def", "statichttp", "(", "container", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "handler", "(", "event", ")", ":", "return", "_handler", "(", "container", ",", "event", ...
35.1
12.5
def get_auth(): """Get authorization token for https """ import getpass from requests.auth import HTTPDigestAuth #This binds raw_input to input for Python 2 input_func = input try: input_func = raw_input except NameError: pass uname = input_func("MODSCAG Username:") ...
[ "def", "get_auth", "(", ")", ":", "import", "getpass", "from", "requests", ".", "auth", "import", "HTTPDigestAuth", "#This binds raw_input to input for Python 2", "input_func", "=", "input", "try", ":", "input_func", "=", "raw_input", "except", "NameError", ":", "pa...
29.125
14.0625
def attributes(data): """Return all the non callable and non special attributes of the input data :param data: an object :returns: a list >>> class table: ... def __init__(self, name, rows, cols): ... self.name = name ... self.rows = rows ... self.cols = col...
[ "def", "attributes", "(", "data", ")", ":", "return", "[", "x", "for", "x", "in", "dir", "(", "data", ")", "if", "not", "callable", "(", "x", ")", "and", "not", "x", ".", "startswith", "(", "'__'", ")", "]" ]
26.722222
18.944444
def parse_te(header): """Parse the "TE" header.""" pos = 0 names = [] while pos < len(header): name, pos = expect_re(re_token, header, pos) _, pos = accept_ws(header, pos) _, pos = accept_lit(';', header, pos) _, pos = accept_ws(header, pos) qvalue, pos = accept_r...
[ "def", "parse_te", "(", "header", ")", ":", "pos", "=", "0", "names", "=", "[", "]", "while", "pos", "<", "len", "(", "header", ")", ":", "name", ",", "pos", "=", "expect_re", "(", "re_token", ",", "header", ",", "pos", ")", "_", ",", "pos", "=...
33.1875
10.9375
def importData(directory): """Parse the input files and return two dictionnaries""" dataTask = OrderedDict() dataQueue = OrderedDict() for fichier in sorted(os.listdir(directory)): try: with open("{directory}/{fichier}".format(**locals()), 'rb') as f: fileName, fileTy...
[ "def", "importData", "(", "directory", ")", ":", "dataTask", "=", "OrderedDict", "(", ")", "dataQueue", "=", "OrderedDict", "(", ")", "for", "fichier", "in", "sorted", "(", "os", ".", "listdir", "(", "directory", ")", ")", ":", "try", ":", "with", "ope...
37.75
15.5
def hash(buf, encoding="utf-8"): """ Compute the fuzzy hash of a buffer :param String|Bytes buf: The data to be fuzzy hashed :return: The fuzzy hash :rtype: String :raises InternalError: If lib returns an internal error :raises TypeError: If buf is not String or Bytes """ if isins...
[ "def", "hash", "(", "buf", ",", "encoding", "=", "\"utf-8\"", ")", ":", "if", "isinstance", "(", "buf", ",", "six", ".", "text_type", ")", ":", "buf", "=", "buf", ".", "encode", "(", "encoding", ")", "if", "not", "isinstance", "(", "buf", ",", "six...
30.185185
19.148148
def _inherit_data(self): """ Inherits the data from the parent. """ LOG.debug("'%s' inheriting data from '%s'" % (self.get_name(), self.parent.get_name()), extra=dict(data=self.parent.data)) self.set_data(**s...
[ "def", "_inherit_data", "(", "self", ")", ":", "LOG", ".", "debug", "(", "\"'%s' inheriting data from '%s'\"", "%", "(", "self", ".", "get_name", "(", ")", ",", "self", ".", "parent", ".", "get_name", "(", ")", ")", ",", "extra", "=", "dict", "(", "dat...
41.125
12.375
def fetch(self): ''' Fetch the repo. If the local copy was updated, return True. If the local copy was already up-to-date, return False. This function requires that a _fetch() function be implemented in a sub-class. ''' try: with self.gen_lock(lock_ty...
[ "def", "fetch", "(", "self", ")", ":", "try", ":", "with", "self", ".", "gen_lock", "(", "lock_type", "=", "'update'", ")", ":", "log", ".", "debug", "(", "'Fetching %s remote \\'%s\\''", ",", "self", ".", "role", ",", "self", ".", "id", ")", "# Run pr...
43.535714
22.392857
def decode(self): r"""Return a :math:`N \rightarrow 2^N` decoder. Example Truth Table for a 2:4 decoder: .. csv-table:: :header: :math:`A_1`, :math:`A_0`, \ :math:`D_3`, :math:`D_2`, :math:`D_1`, :math:`D_0` :stub-columns: 2 0, 0, 0, 0, 0, ...
[ "def", "decode", "(", "self", ")", ":", "items", "=", "[", "reduce", "(", "operator", ".", "and_", ",", "boolfunc", ".", "num2term", "(", "i", ",", "self", ".", "_items", ")", ",", "self", ".", "ftype", ".", "box", "(", "1", ")", ")", "for", "i...
31
18.3
def pip_execute(*args, **kwargs): """Overriden pip_execute() to stop sys.path being changed. The act of importing main from the pip module seems to cause add wheels from the /usr/share/python-wheels which are installed by various tools. This function ensures that sys.path remains the same after the cal...
[ "def", "pip_execute", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "_path", "=", "sys", ".", "path", "try", ":", "from", "pip", "import", "main", "as", "_pip_execute", "except", "ImportError", ":", "apt_update", "(", ")", "if", "s...
33
17.681818
def describe(cls, full=False): """Prints a description of the table based on the provided documentation and post processors""" divider_double = "=" * 80 divider_single = "-" * 80 description = cls.__doc__ message = [] message.append(divider_double) message.append(cls.__name__ + ':') ...
[ "def", "describe", "(", "cls", ",", "full", "=", "False", ")", ":", "divider_double", "=", "\"=\"", "*", "80", "divider_single", "=", "\"-\"", "*", "80", "description", "=", "cls", ".", "__doc__", "message", "=", "[", "]", "message", ".", "append", "("...
36.318182
9.772727
def _new_stream(self, idx): '''Randomly select and create a new stream. Parameters ---------- idx : int, [0:n_streams - 1] The stream index to replace ''' # Choose the stream index from the candidate pool self.stream_idxs_[idx] = self.rng.choice( ...
[ "def", "_new_stream", "(", "self", ",", "idx", ")", ":", "# Choose the stream index from the candidate pool", "self", ".", "stream_idxs_", "[", "idx", "]", "=", "self", ".", "rng", ".", "choice", "(", "self", ".", "n_streams", ",", "p", "=", "self", ".", "...
33.111111
17.555556
def _merge_colormaps(kwargs): """Merge colormaps listed in kwargs.""" from trollimage.colormap import Colormap full_cmap = None palette = kwargs['palettes'] if isinstance(palette, Colormap): full_cmap = palette else: for itm in palette: cmap = create_colormap(itm) ...
[ "def", "_merge_colormaps", "(", "kwargs", ")", ":", "from", "trollimage", ".", "colormap", "import", "Colormap", "full_cmap", "=", "None", "palette", "=", "kwargs", "[", "'palettes'", "]", "if", "isinstance", "(", "palette", ",", "Colormap", ")", ":", "full_...
28.611111
14.888889
def AdaBoost(L, K): """[Fig. 18.34]""" def train(dataset): examples, target = dataset.examples, dataset.target N = len(examples) epsilon = 1./(2*N) w = [1./N] * N h, z = [], [] for k in range(K): h_k = L(dataset, w) h.append(h_k) ...
[ "def", "AdaBoost", "(", "L", ",", "K", ")", ":", "def", "train", "(", "dataset", ")", ":", "examples", ",", "target", "=", "dataset", ".", "examples", ",", "dataset", ".", "target", "N", "=", "len", "(", "examples", ")", "epsilon", "=", "1.", "/", ...
37.636364
14.909091
def hints(self, **kwargs): """ Use this method to update hints value of the underlying query example: queryset.hints(permissive=False) """ new_query = self.query.clone() new_query.hints.update(kwargs) return self._clone(query=new_query)
[ "def", "hints", "(", "self", ",", "*", "*", "kwargs", ")", ":", "new_query", "=", "self", ".", "query", ".", "clone", "(", ")", "new_query", ".", "hints", ".", "update", "(", "kwargs", ")", "return", "self", ".", "_clone", "(", "query", "=", "new_q...
31.666667
11
def show_menu(title, options, default=None, height=None, width=None, multiselect=False, precolored=False): """ Shows an interactive menu in the terminal. Arguments: options: list of menu options default: initial option to highlight height: maximum height of the menu width: m...
[ "def", "show_menu", "(", "title", ",", "options", ",", "default", "=", "None", ",", "height", "=", "None", ",", "width", "=", "None", ",", "multiselect", "=", "False", ",", "precolored", "=", "False", ")", ":", "plugins", "=", "[", "FilterPlugin", "(",...
38.235294
19.823529
def low_rank_approximation(A, r): """ Returns approximation of A of rank r in least-squares sense.""" try: u, s, v = np.linalg.svd(A, full_matrices=False) except np.linalg.LinAlgError as e: print('Matrix:', A) print('Matrix rank:', np.linalg.matrix_rank(A)) raise Ar = np...
[ "def", "low_rank_approximation", "(", "A", ",", "r", ")", ":", "try", ":", "u", ",", "s", ",", "v", "=", "np", ".", "linalg", ".", "svd", "(", "A", ",", "full_matrices", "=", "False", ")", "except", "np", ".", "linalg", ".", "LinAlgError", "as", ...
33.588235
15.294118
def generate(cls): """ Generates a random :class:`~SigningKey` object. :rtype: :class:`~SigningKey` """ return cls( libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES), encoder=encoding.RawEncoder, )
[ "def", "generate", "(", "cls", ")", ":", "return", "cls", "(", "libnacl", ".", "randombytes", "(", "libnacl", ".", "crypto_sign_SEEDBYTES", ")", ",", "encoder", "=", "encoding", ".", "RawEncoder", ",", ")" ]
26.2
15.6
def _data_from_response(self, resp_body, key=None): """ This works for most API responses, but some don't structure their listing responses the same way, so overriding this method allows subclasses to handle extraction for those outliers. """ if key: data = re...
[ "def", "_data_from_response", "(", "self", ",", "resp_body", ",", "key", "=", "None", ")", ":", "if", "key", ":", "data", "=", "resp_body", ".", "get", "(", "key", ")", "else", ":", "data", "=", "resp_body", ".", "get", "(", "self", ".", "plural_resp...
38.421053
18.947368
def writeToFile(self, f, packed=True): """ Write serialized object to file. :param f: output file :param packed: If true, will pack contents. """ # Get capnproto schema from instance schema = self.getSchema() # Construct new message, otherwise refered to as `proto` proto = schema.n...
[ "def", "writeToFile", "(", "self", ",", "f", ",", "packed", "=", "True", ")", ":", "# Get capnproto schema from instance", "schema", "=", "self", ".", "getSchema", "(", ")", "# Construct new message, otherwise refered to as `proto`", "proto", "=", "schema", ".", "ne...
23.380952
17.095238
def compare_config(self): """Implementation of NAPALM method compare_config.""" if self.config_session is None: return '' else: commands = ['show session-config named %s diffs' % self.config_session] result = self.device.run_commands(commands, encoding='text')...
[ "def", "compare_config", "(", "self", ")", ":", "if", "self", ".", "config_session", "is", "None", ":", "return", "''", "else", ":", "commands", "=", "[", "'show session-config named %s diffs'", "%", "self", ".", "config_session", "]", "result", "=", "self", ...
37.727273
22.909091
def get_posix_property(value, mode=POSIX): """Retrieve the posix category.""" if mode == POSIX_BYTES: return unidata.ascii_posix_properties[value] elif mode == POSIX_UNICODE: return unidata.unicode_binary[ ('^posix' + value[1:]) if value.startswith('^') else ('posix' + value) ...
[ "def", "get_posix_property", "(", "value", ",", "mode", "=", "POSIX", ")", ":", "if", "mode", "==", "POSIX_BYTES", ":", "return", "unidata", ".", "ascii_posix_properties", "[", "value", "]", "elif", "mode", "==", "POSIX_UNICODE", ":", "return", "unidata", "....
34.727273
17.818182
def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \ -> Generator[Any, None, None]: """ Generate the first value in each row. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: the first value of each row """ return...
[ "def", "genfirstvalues", "(", "cursor", ":", "Cursor", ",", "arraysize", ":", "int", "=", "1000", ")", "->", "Generator", "[", "Any", ",", "None", ",", "None", "]", ":", "return", "(", "row", "[", "0", "]", "for", "row", "in", "genrows", "(", "curs...
27.307692
17.153846
def calculate_marginal_likelihoods(tree, feature, frequencies): """ Calculates marginal likelihoods for each tree node by multiplying state frequencies with their bottom-up and top-down likelihoods. :param tree: ete3.Tree, the tree of interest :param feature: str, character for which the likelihood...
[ "def", "calculate_marginal_likelihoods", "(", "tree", ",", "feature", ",", "frequencies", ")", ":", "bu_lh_feature", "=", "get_personalized_feature_name", "(", "feature", ",", "BU_LH", ")", "bu_lh_sf_feature", "=", "get_personalized_feature_name", "(", "feature", ",", ...
53.428571
24.5
def start_download_thread(self): '''start the downloader''' if self._download_thread: return t = threading.Thread(target=self.downloader) t.daemon = True self._download_thread = t t.start()
[ "def", "start_download_thread", "(", "self", ")", ":", "if", "self", ".", "_download_thread", ":", "return", "t", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "downloader", ")", "t", ".", "daemon", "=", "True", "self", ".", "_downloa...
24.625
16.875
def encode(self, envelope, session, aes_cipher=None, **kwargs): """ :meth:`.WMessengerOnionCoderLayerProto.encode` method implementation. :param envelope: original envelope :param session: original session :param aes_cipher: cipher to use :param kwargs: additional arguments :return: WMessengerBytesEnvelop...
[ "def", "encode", "(", "self", ",", "envelope", ",", "session", ",", "aes_cipher", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "WMessengerBytesEnvelope", "(", "aes_cipher", ".", "encrypt", "(", "envelope", ".", "message", "(", ")", ")", ",",...
36.818182
15.909091
def sync(self): """基于账户/密码去sync数据库 """ if self.wechat_id is not None: res = self.client.find_one({'wechat_id': self.wechat_id}) else: res = self.client.find_one( { 'username': self.username, 'password': self...
[ "def", "sync", "(", "self", ")", ":", "if", "self", ".", "wechat_id", "is", "not", "None", ":", "res", "=", "self", ".", "client", ".", "find_one", "(", "{", "'wechat_id'", ":", "self", ".", "wechat_id", "}", ")", "else", ":", "res", "=", "self", ...
26.28
19.76
def add_vo_information_about_user(self, name_id): """ Add information to the knowledge I have about the user. This is for Virtual organizations. :param name_id: The subject identifier :return: A possibly extended knowledge. """ ava = {} try: (ava, _)...
[ "def", "add_vo_information_about_user", "(", "self", ",", "name_id", ")", ":", "ava", "=", "{", "}", "try", ":", "(", "ava", ",", "_", ")", "=", "self", ".", "users", ".", "get_identity", "(", "name_id", ")", "except", "KeyError", ":", "pass", "# is th...
31.15
16.75
def extend_volume(self, volume, size): """Extend a volume to a new, larger size. :param volume: Name of the volume to be extended. :type volume: str :type size: int or str :param size: Size in bytes, or string representing the size of the volume to be create...
[ "def", "extend_volume", "(", "self", ",", "volume", ",", "size", ")", ":", "return", "self", ".", "set_volume", "(", "volume", ",", "size", "=", "size", ",", "truncate", "=", "False", ")" ]
27.266667
22.733333
def _call(self, x, out=None, **kwargs): """Raw evaluation method.""" if out is None: return self._call_out_of_place(x, **kwargs) else: self._call_in_place(x, out=out, **kwargs)
[ "def", "_call", "(", "self", ",", "x", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "out", "is", "None", ":", "return", "self", ".", "_call_out_of_place", "(", "x", ",", "*", "*", "kwargs", ")", "else", ":", "self", ".", "_...
36.5
12.166667
def main(): """ Main function of maya launcher. Parses the arguments and tries to launch maya with given them. """ config = build_config() parser = argparse.ArgumentParser( description=""" Maya Launcher is a useful script that tries to deal with all important s...
[ "def", "main", "(", ")", ":", "config", "=", "build_config", "(", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"\"\"\r\n Maya Launcher is a useful script that tries to deal with all\r\n important system environments maya uses whe...
30.552083
18.864583
def down_capture(returns, factor_returns, **kwargs): """ Compute the capture ratio for periods when the benchmark return is negative Parameters ---------- returns : pd.Series or np.ndarray Returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_...
[ "def", "down_capture", "(", "returns", ",", "factor_returns", ",", "*", "*", "kwargs", ")", ":", "return", "down", "(", "returns", ",", "factor_returns", ",", "function", "=", "capture", ",", "*", "*", "kwargs", ")" ]
32.1875
22.5
def _draw_gradient(self, hue): """Draw the gradient and put the cursor on hue.""" self.delete("gradient") self.delete("cursor") del self.gradient width = self.winfo_width() height = self.winfo_height() self.gradient = tk.PhotoImage(master=self, width=width, heigh...
[ "def", "_draw_gradient", "(", "self", ",", "hue", ")", ":", "self", ".", "delete", "(", "\"gradient\"", ")", "self", ".", "delete", "(", "\"cursor\"", ")", "del", "self", ".", "gradient", "width", "=", "self", ".", "winfo_width", "(", ")", "height", "=...
37
17.857143
def _validate_templates(self, templates): """ :param templates: :return: """ if templates is None: return templates if not isinstance(templates, list): raise TypeError(logger.error("templates should be a list.")) for template in templates...
[ "def", "_validate_templates", "(", "self", ",", "templates", ")", ":", "if", "templates", "is", "None", ":", "return", "templates", "if", "not", "isinstance", "(", "templates", ",", "list", ")", ":", "raise", "TypeError", "(", "logger", ".", "error", "(", ...
40
22.896552
def register(self, class_path): """ Register a new metric set :param class_path: a string with the import path of the metricset class """ if class_path in self._metricsets: return else: try: class_obj = import_string(class_path) ...
[ "def", "register", "(", "self", ",", "class_path", ")", ":", "if", "class_path", "in", "self", ".", "_metricsets", ":", "return", "else", ":", "try", ":", "class_obj", "=", "import_string", "(", "class_path", ")", "self", ".", "_metricsets", "[", "class_pa...
39
17.769231
def f_solpos(times, latitude, longitude): """ Calculate solar position for lat/long at times. :param times: Python :class:`datetime.datetime` object. :type times: list :param latitude: latitude [degrees] :type latitude: float :param longitude: longitude [degrees] :type longitude: float ...
[ "def", "f_solpos", "(", "times", ",", "latitude", ",", "longitude", ")", ":", "# pvlib converts Python datetime objects to pandas DatetimeIndex", "solpos", "=", "pvlib", ".", "solarposition", ".", "get_solarposition", "(", "times", ",", "latitude", ",", "longitude", "...
41.647059
16.235294
def _run_cmd(cmd): """Run command specified by :cmd: and return stdout, stderr and code.""" if not os.path.exists(cmd[0]): cmd[0] = shutil.which(cmd[0]) assert cmd[0] is not None shebang_parts = parseshebang.parse(cmd[0]) proc = subprocess.Popen(shebang_parts + cmd, ...
[ "def", "_run_cmd", "(", "cmd", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "cmd", "[", "0", "]", ")", ":", "cmd", "[", "0", "]", "=", "shutil", ".", "which", "(", "cmd", "[", "0", "]", ")", "assert", "cmd", "[", "0", "]", ...
31.235294
15.117647
def build_options(kwargs=None): '''Build options for tabula-java Args: options (str, optional): Raw option string for tabula-java. pages (str, int, :obj:`list` of :obj:`int`, optional): An optional values specifying pages to extract from. It allows `str`,`int...
[ "def", "build_options", "(", "kwargs", "=", "None", ")", ":", "__options", "=", "[", "]", "if", "kwargs", "is", "None", ":", "kwargs", "=", "{", "}", "options", "=", "kwargs", ".", "get", "(", "'options'", ",", "''", ")", "# handle options described in s...
35.777778
20.444444
def fill_out(self, data, prefix='', turbo=False): """ Shortcut for filling out first ``<form>`` on page. See :py:class:`~webdriverwrapper.forms.Form` for more information. .. versionadded:: 2.0 """ return self.get_elm(tag_name='form').fill_out(data, prefix, turbo)
[ "def", "fill_out", "(", "self", ",", "data", ",", "prefix", "=", "''", ",", "turbo", "=", "False", ")", ":", "return", "self", ".", "get_elm", "(", "tag_name", "=", "'form'", ")", ".", "fill_out", "(", "data", ",", "prefix", ",", "turbo", ")" ]
38.25
18.25
def prefix(handlers, default=None, error='The requested prefix does not match any of those allowed'): """Returns a content in a different format based on the prefix placed at the end of the URL route should pass in a dict with the following format: {'[prefix]': action, ... ...
[ "def", "prefix", "(", "handlers", ",", "default", "=", "None", ",", "error", "=", "'The requested prefix does not match any of those allowed'", ")", ":", "def", "output_type", "(", "data", ",", "request", ",", "response", ")", ":", "path", "=", "request", ".", ...
43.24
23
def discover(timeout=5, include_invisible=False, interface_addr=None): """ Discover Sonos zones on the local network. Return a set of `SoCo` instances for each zone found. Include invisible zones (bridges and slave zones in stereo pairs if ``include_invisible`` is `True`. Will block for up to ``timeout...
[ "def", "discover", "(", "timeout", "=", "5", ",", "include_invisible", "=", "False", ",", "interface_addr", "=", "None", ")", ":", "def", "create_socket", "(", "interface_addr", "=", "None", ")", ":", "\"\"\" A helper function for creating a socket for discover purpos...
43.134146
21.969512
def postActivate_(self): """Create temporary file for image dumps and the analyzer itself """ self.tmpfile = os.path.join(constant.tmpdir,"valkka-"+str(os.getpid())) # e.g. "/tmp/valkka-10968" self.analyzer = ExternalDetector( executable = self.executable, image_...
[ "def", "postActivate_", "(", "self", ")", ":", "self", ".", "tmpfile", "=", "os", ".", "path", ".", "join", "(", "constant", ".", "tmpdir", ",", "\"valkka-\"", "+", "str", "(", "os", ".", "getpid", "(", ")", ")", ")", "# e.g. \"/tmp/valkka-10968\" ", "...
44
14.555556
def list_cert_bindings(site): ''' List certificate bindings for an IIS site. .. versionadded:: 2016.11.0 Args: site (str): The IIS site name. Returns: dict: A dictionary of the binding names and properties. CLI Example: .. code-block:: bash salt '*' win_iis.list...
[ "def", "list_cert_bindings", "(", "site", ")", ":", "ret", "=", "dict", "(", ")", "sites", "=", "list_sites", "(", ")", "if", "site", "not", "in", "sites", ":", "log", ".", "warning", "(", "'Site not found: %s'", ",", "site", ")", "return", "ret", "for...
21.818182
25.151515
def save_date(self): """ Invitations with the same workflow status are deleted. Workflow instance and invitation roles change. """ task_invitation = TaskInvitation.objects.get(self.task_invitation_key) wfi = task_invitation.instance if wfi.current_actor.e...
[ "def", "save_date", "(", "self", ")", ":", "task_invitation", "=", "TaskInvitation", ".", "objects", ".", "get", "(", "self", ".", "task_invitation_key", ")", "wfi", "=", "task_invitation", ".", "instance", "if", "wfi", ".", "current_actor", ".", "exist", "a...
36.5
21.642857
def insert(self, index, x): """ See :meth:`~pluginsmanager.observer.observable_list.ObservableList.insert()` method """ self.check_insertion(x) self.real_list.insert(index, x) self._items |= {x}
[ "def", "insert", "(", "self", ",", "index", ",", "x", ")", ":", "self", ".", "check_insertion", "(", "x", ")", "self", ".", "real_list", ".", "insert", "(", "index", ",", "x", ")", "self", ".", "_items", "|=", "{", "x", "}" ]
29.5
16
def get_pandas_df(self, hql, parameters=None): """ Get a pandas dataframe from a sql query. """ import pandas cursor = self.get_cursor() try: cursor.execute(self._strip_sql(hql), parameters) data = cursor.fetchall() except DatabaseError as ...
[ "def", "get_pandas_df", "(", "self", ",", "hql", ",", "parameters", "=", "None", ")", ":", "import", "pandas", "cursor", "=", "self", ".", "get_cursor", "(", ")", "try", ":", "cursor", ".", "execute", "(", "self", ".", "_strip_sql", "(", "hql", ")", ...
34.055556
13.166667
def search(query, engine='g', site="", file_type = 'pdf', limit = 10): """ main function to search for links and return valid ones """ if site == "": search_query = "filetype:{0} {1}".format(file_type, query) else: search_query = "site:{0} filetype:{1} {2}".format(site,file_type, query) headers = { 'User A...
[ "def", "search", "(", "query", ",", "engine", "=", "'g'", ",", "site", "=", "\"\"", ",", "file_type", "=", "'pdf'", ",", "limit", "=", "10", ")", ":", "if", "site", "==", "\"\"", ":", "search_query", "=", "\"filetype:{0} {1}\"", ".", "format", "(", "...
23.870968
23.419355
def contains_non_repeat_actions(self): ''' Because repeating repeat actions can get ugly real fast ''' for action in self.actions: if not isinstance(action, (int, dynamic.RepeatCommand)): return True return False
[ "def", "contains_non_repeat_actions", "(", "self", ")", ":", "for", "action", "in", "self", ".", "actions", ":", "if", "not", "isinstance", "(", "action", ",", "(", "int", ",", "dynamic", ".", "RepeatCommand", ")", ")", ":", "return", "True", "return", "...
34.125
18.625
def generate_template_arc_tree(self): ''' Generate a seven point template in this arc. Arc must be empty. ''' arc_root = self.arc_root_node if not arc_root: arc_root = ArcElementNode.add_root( arc_element_type='root', description='root ...
[ "def", "generate_template_arc_tree", "(", "self", ")", ":", "arc_root", "=", "self", ".", "arc_root_node", "if", "not", "arc_root", ":", "arc_root", "=", "ArcElementNode", ".", "add_root", "(", "arc_element_type", "=", "'root'", ",", "description", "=", "'root o...
46.555556
21.444444
def slide_path(builder, pagename=None): """Calculate the relative path to the Slides for pagename.""" return builder.get_relative_uri( pagename or builder.current_docname, os.path.join( builder.app.config.slide_relative_path, pagename or builder.current_docname, ...
[ "def", "slide_path", "(", "builder", ",", "pagename", "=", "None", ")", ":", "return", "builder", ".", "get_relative_uri", "(", "pagename", "or", "builder", ".", "current_docname", ",", "os", ".", "path", ".", "join", "(", "builder", ".", "app", ".", "co...
34.888889
13
def raw_from_delimited(msgs: DelimitedMsg) -> RawMsgs: """\ From a message consisting of header frames, delimiter frame, and payload frames, return a tuple `(header, payload)`. The payload frames may be returned as sequences of bytes (raw) or as `Message`s. """ delim = _rindex(msgs, b'') return ...
[ "def", "raw_from_delimited", "(", "msgs", ":", "DelimitedMsg", ")", "->", "RawMsgs", ":", "delim", "=", "_rindex", "(", "msgs", ",", "b''", ")", "return", "tuple", "(", "msgs", "[", ":", "delim", "]", ")", ",", "tuple", "(", "msgs", "[", "delim", "+"...
51.142857
23.285714
def _add_exac(self, variant_obj, gemini_variant): """Add the gmaf frequency Args: variant_obj (puzzle.models.Variant) gemini_variant (GeminiQueryRow) """ exac = gemini_variant['aaf_exac_all'] if exac: exac = float(exac) ...
[ "def", "_add_exac", "(", "self", ",", "variant_obj", ",", "gemini_variant", ")", ":", "exac", "=", "gemini_variant", "[", "'aaf_exac_all'", "]", "if", "exac", ":", "exac", "=", "float", "(", "exac", ")", "variant_obj", ".", "add_frequency", "(", "'ExAC'", ...
33.230769
13.076923
def dump_stats(myStats): """ Show stats when pings are done """ print("\n----%s PYTHON PING Statistics----" % (myStats.thisIP)) if myStats.pktsSent > 0: myStats.fracLoss = (myStats.pktsSent - myStats.pktsRcvd) \ / myStats.pktsSent print(("%d packets transmitted, %d pack...
[ "def", "dump_stats", "(", "myStats", ")", ":", "print", "(", "\"\\n----%s PYTHON PING Statistics----\"", "%", "(", "myStats", ".", "thisIP", ")", ")", "if", "myStats", ".", "pktsSent", ">", "0", ":", "myStats", ".", "fracLoss", "=", "(", "myStats", ".", "p...
25.961538
19.192308
def create_user(username, password, superuser=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra user with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password ...
[ "def", "create_user", "(", "username", ",", "password", ",", "superuser", "=", "False", ",", "contact_points", "=", "None", ",", "port", "=", "None", ",", "cql_user", "=", "None", ",", "cql_pass", "=", "None", ")", ":", "superuser_cql", "=", "'superuser'",...
43.170213
31.680851
def include_library(libname): """Check if a dynamic library should be included with application or not.""" # For configuration phase we need to have exclude / include lists None # so these checking is skipped and library gets included. if exclude_list: if exclude_list.search(libname) and not inc...
[ "def", "include_library", "(", "libname", ")", ":", "# For configuration phase we need to have exclude / include lists None", "# so these checking is skipped and library gets included.", "if", "exclude_list", ":", "if", "exclude_list", ".", "search", "(", "libname", ")", "and", ...
40.466667
18.733333