text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _find_context_dependent_names(self): """Finds texts whose translation depends on context. Example. Here the word "Palacio" is translated from Spanish to English in multiple ways. Feed language is es (Spanish). trans_id,lang,translation stop-name-1,es,Palacio...
[ "def", "_find_context_dependent_names", "(", "self", ")", ":", "n_occurences_of_original", "=", "{", "}", "for", "trans_id", ",", "translations", "in", "self", ".", "translations_map", ".", "items", "(", ")", ":", "try", ":", "original_name", "=", "translations"...
37.903226
0.00166
def add_members(self, project, params={}, **options): """Adds the specified list of users as members of the project. Returns the updated project record. Parameters ---------- project : {Id} The project to add members to. [data] : {Object} Data for the request - member...
[ "def", "add_members", "(", "self", ",", "project", ",", "params", "=", "{", "}", ",", "*", "*", "options", ")", ":", "path", "=", "\"/projects/%s/addMembers\"", "%", "(", "project", ")", "return", "self", ".", "client", ".", "post", "(", "path", ",", ...
44.181818
0.008065
def complexity_fd_petrosian(signal): """ Computes the Petrosian Fractal Dimension of a signal. Based on the `pyrem <https://github.com/gilestrolab/pyrem>`_ repo by Quentin Geissmann. Parameters ---------- signal : list or array List or array of values. Returns ---------- fd_pet...
[ "def", "complexity_fd_petrosian", "(", "signal", ")", ":", "diff", "=", "np", ".", "diff", "(", "signal", ")", "# x[i] * x[i-1] for i in t0 -> tmax", "prod", "=", "diff", "[", "1", ":", "-", "1", "]", "*", "diff", "[", "0", ":", "-", "2", "]", "# Numbe...
24.142857
0.002437
def reset_pst(self,arg): """ reset the LinearAnalysis.pst attribute Parameters ---------- arg : (str or matrix) the value to assign to the pst attribute """ self.logger.statement("resetting pst") self.__pst = None self.pst_arg = arg
[ "def", "reset_pst", "(", "self", ",", "arg", ")", ":", "self", ".", "logger", ".", "statement", "(", "\"resetting pst\"", ")", "self", ".", "__pst", "=", "None", "self", ".", "pst_arg", "=", "arg" ]
24.916667
0.009677
def CheckProperties(cls, tagname, attrs): """ Return True if tagname and attrs are the XML tag name and element attributes, respectively, of a Table element whose Name attribute matches the .tableName attribute of this class according to CompareTableNames(); return False otherwise. The Table parent class ...
[ "def", "CheckProperties", "(", "cls", ",", "tagname", ",", "attrs", ")", ":", "return", "tagname", "==", "cls", ".", "tagName", "and", "not", "CompareTableNames", "(", "attrs", "[", "u\"Name\"", "]", ",", "cls", ".", "tableName", ")" ]
38.166667
0.026989
def f_string_check(self, original, loc, tokens): """Handle Python 3.6 format strings.""" return self.check_py("36", "format string", original, loc, tokens)
[ "def", "f_string_check", "(", "self", ",", "original", ",", "loc", ",", "tokens", ")", ":", "return", "self", ".", "check_py", "(", "\"36\"", ",", "\"format string\"", ",", "original", ",", "loc", ",", "tokens", ")" ]
56.333333
0.011696
def cell(self, w,h=0,txt='',border=0,ln=0,align='',fill=0,link=''): "Output a cell" txt = self.normalize_text(txt) k=self.k if(self.y+h>self.page_break_trigger and not self.in_footer and self.accept_page_break()): #Automatic page break x=self.x ws=self...
[ "def", "cell", "(", "self", ",", "w", ",", "h", "=", "0", ",", "txt", "=", "''", ",", "border", "=", "0", ",", "ln", "=", "0", ",", "align", "=", "''", ",", "fill", "=", "0", ",", "link", "=", "''", ")", ":", "txt", "=", "self", ".", "n...
40.538462
0.026462
def _evaluate(self,R,phi=0.,t=0.): """ NAME: _evaluate PURPOSE: evaluate the potential at R,phi,t INPUT: R - Galactocentric cylindrical radius phi - azimuth t - time OUTPUT: Phi(R,phi,t) HISTORY: ...
[ "def", "_evaluate", "(", "self", ",", "R", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "if", "not", "self", ".", "_tform", "is", "None", ":", "if", "t", "<", "self", ".", "_tform", ":", "smooth", "=", "0.", "elif", "t", "<", "self",...
33.344828
0.01608
def geodetic2aer(lat: float, lon: float, h: float, lat0: float, lon0: float, h0: float, ell=None, deg: bool = True) -> Tuple[float, float, float]: """ gives azimuth, elevation and slant range from an Observer to a Point with geodetic coordinates. Parameters ----------...
[ "def", "geodetic2aer", "(", "lat", ":", "float", ",", "lon", ":", "float", ",", "h", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "h0", ":", "float", ",", "ell", "=", "None", ",", "deg", ":", "bool", "=", "True", ")"...
30.461538
0.001631
def post_process(self, dir_name, d): """ Simple post-processing for various files other than the vasprun.xml. Called by generate_task_doc. Modify this if your runs have other kinds of processing requirements. Args: dir_name: The dir_name. ...
[ "def", "post_process", "(", "self", ",", "dir_name", ",", "d", ")", ":", "logger", ".", "info", "(", "\"Post-processing dir:{}\"", ".", "format", "(", "dir_name", ")", ")", "fullpath", "=", "os", ".", "path", ".", "abspath", "(", "dir_name", ")", "# VASP...
40.948454
0.001475
def bind_end(self, stream, future): """Bind a 'TaskEndTransformer' to a stream.""" if not isinstance(stream, Stream): future.set_result(None) else: stream.pipe(TaskEndTransformer(future))
[ "def", "bind_end", "(", "self", ",", "stream", ",", "future", ")", ":", "if", "not", "isinstance", "(", "stream", ",", "Stream", ")", ":", "future", ".", "set_result", "(", "None", ")", "else", ":", "stream", ".", "pipe", "(", "TaskEndTransformer", "("...
32.333333
0.035176
def to_text(self, origin=None, relativize=True, **kw): """Convert the message to text. The I{origin}, I{relativize}, and any other keyword arguments are passed to the rrset to_wire() method. @rtype: string """ s = cStringIO.StringIO() print >> s, 'id %d' % sel...
[ "def", "to_text", "(", "self", ",", "origin", "=", "None", ",", "relativize", "=", "True", ",", "*", "*", "kw", ")", ":", "s", "=", "cStringIO", ".", "StringIO", "(", ")", "print", ">>", "s", ",", "'id %d'", "%", "self", ".", "id", "print", ">>",...
37.02
0.001579
def _normalize_for_correlation(data, axis, return_nans=False): """normalize the data before computing correlation The data will be z-scored and divided by sqrt(n) along the assigned axis Parameters ---------- data: 2D array axis: int specify which dimension of the data should be n...
[ "def", "_normalize_for_correlation", "(", "data", ",", "axis", ",", "return_nans", "=", "False", ")", ":", "shape", "=", "data", ".", "shape", "data", "=", "zscore", "(", "data", ",", "axis", "=", "axis", ",", "ddof", "=", "0", ")", "# if zscore fails (s...
26.137931
0.001272
def write_or_delete_file(self, what, filename, data, force=False): """Write `data` to `filename` or delete if empty If `data` is non-empty, this routine is the same as ``write_file()``. If `data` is empty but not ``None``, this is the same as calling ``delete_file(filename)`. If `data`...
[ "def", "write_or_delete_file", "(", "self", ",", "what", ",", "filename", ",", "data", ",", "force", "=", "False", ")", ":", "if", "data", ":", "self", ".", "write_file", "(", "what", ",", "filename", ",", "data", ")", "elif", "os", ".", "path", ".",...
45.052632
0.002288
def write(self, filename=None): """Save template to xml. Before saving template will update date, start position, well positions, and counts. Parameters ---------- filename : str If not set, XML will be written to self.filename. """ if not filename: ...
[ "def", "write", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "not", "filename", ":", "filename", "=", "self", ".", "filename", "# update time", "self", ".", "properties", ".", "CurrentDate", "=", "_current_time", "(", ")", "# set rubber band to...
30.586957
0.002066
def _GetOpener(self): """Returns an OpenerDirector that supports cookies and ignores redirects. Returns: A urllib2.OpenerDirector object. """ opener = urllib2.OpenerDirector() opener.add_handler(urllib2.ProxyHandler()) opener.add_handler(urllib2.UnknownHandler()) opener.add_handler(urllib2.HTTPHandler...
[ "def", "_GetOpener", "(", "self", ")", ":", "opener", "=", "urllib2", ".", "OpenerDirector", "(", ")", "opener", ".", "add_handler", "(", "urllib2", ".", "ProxyHandler", "(", ")", ")", "opener", ".", "add_handler", "(", "urllib2", ".", "UnknownHandler", "(...
36.685714
0.027314
def api_keys(self, serverid, api_key): """Load object with id/API pair Args: serverid (int): Discord 'guild' webhook is attached to api_key (`str`:uuid): unique ID for webhook """ if serverid and api_key: self.can_query = True # Yes, we _are_ (will b...
[ "def", "api_keys", "(", "self", ",", "serverid", ",", "api_key", ")", ":", "if", "serverid", "and", "api_key", ":", "self", ".", "can_query", "=", "True", "# Yes, we _are_ (will be) configured", "self", ".", "serverid", "=", "int", "(", "serverid", ")", "sel...
36.538462
0.008214
def write_headers(self): """ Output table header to console and csv file (if present). """ h1 = [] h2 = [] for m in self.values(): h2.append(m.render_subtitle()) h1.append(m.render_title()) stdout.write(" ".join(h1)) std...
[ "def", "write_headers", "(", "self", ")", ":", "h1", "=", "[", "]", "h2", "=", "[", "]", "for", "m", "in", "self", ".", "values", "(", ")", ":", "h2", ".", "append", "(", "m", ".", "render_subtitle", "(", ")", ")", "h1", ".", "append", "(", "...
33.333333
0.001767
def stream(self, label=None, selector=None): """Create an outgoing stream originating from this node. More nodes may be attached onto the outgoing stream. """ return self.__outgoing_stream_type(self, label, upstream_selector=selector)
[ "def", "stream", "(", "self", ",", "label", "=", "None", ",", "selector", "=", "None", ")", ":", "return", "self", ".", "__outgoing_stream_type", "(", "self", ",", "label", ",", "upstream_selector", "=", "selector", ")" ]
43.666667
0.011236
def get_transactions(self): """Get all your deposits and withdrawals. Returns: dict: lists of your NMR and USD transactions The returned dict has the following structure: * nmrDeposits (`list`) contains items with fields: * from (`str`) ...
[ "def", "get_transactions", "(", "self", ")", ":", "query", "=", "\"\"\"\n query {\n user {\n nmrDeposits {\n from\n posted\n status\n to\n txHash\n value\n }\n ...
34.268519
0.00105
def _rule_as_string(self, rule): """ Converts a tinycss rule to a formatted CSS string :param rule: The rule to format :type rule: tinycss Rule object :returns: The Rule as a CSS string :rtype: str """ if isinstance(rule, RuleSet): # Simple CS...
[ "def", "_rule_as_string", "(", "self", ",", "rule", ")", ":", "if", "isinstance", "(", "rule", ",", "RuleSet", ")", ":", "# Simple CSS rule : a { color: red; }", "return", "'%s{%s}'", "%", "(", "self", ".", "_selector_as_string", "(", "rule", ".", "selector", ...
33.65
0.002166
def find_next(start, stop, i2hits): """ which protein has the best hit, the one to the 'right' or to the 'left?' """ if start not in i2hits and stop in i2hits: index = stop elif stop not in i2hits and start in i2hits: index = start elif start not in i2hits and stop not in i2hits:...
[ "def", "find_next", "(", "start", ",", "stop", ",", "i2hits", ")", ":", "if", "start", "not", "in", "i2hits", "and", "stop", "in", "i2hits", ":", "index", "=", "stop", "elif", "stop", "not", "in", "i2hits", "and", "start", "in", "i2hits", ":", "index...
28.384615
0.001311
def upload_file( self, filename, upload_as=None, blocksize=None, callback=None, information_callback=None, allow_timeout=False, ): """Uploads a file with given filename to this room. You may specify upload_as to change the name it is uploaded a...
[ "def", "upload_file", "(", "self", ",", "filename", ",", "upload_as", "=", "None", ",", "blocksize", "=", "None", ",", "callback", "=", "None", ",", "information_callback", "=", "None", ",", "allow_timeout", "=", "False", ",", ")", ":", "with", "delayed_cl...
37
0.001003
def extract_features(self, dataset, missing_value_action='auto'): """ For each example in the dataset, extract the leaf indices of each tree as features. For multiclass classification, each leaf index contains #num_class numbers. The returned feature vectors can be used...
[ "def", "extract_features", "(", "self", ",", "dataset", ",", "missing_value_action", "=", "'auto'", ")", ":", "_raise_error_if_not_sframe", "(", "dataset", ",", "\"dataset\"", ")", "if", "missing_value_action", "==", "'auto'", ":", "missing_value_action", "=", "sele...
41
0.001276
def info(ctx): """ Display status of OATH application. """ controller = ctx.obj['controller'] version = controller.version click.echo( 'OATH version: {}.{}.{}'.format(version[0], version[1], version[2])) click.echo('Password protection ' + ('enabled' if controller.lock...
[ "def", "info", "(", "ctx", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "version", "=", "controller", ".", "version", "click", ".", "echo", "(", "'OATH version: {}.{}.{}'", ".", "format", "(", "version", "[", "0", "]", ",", ...
35.722222
0.001515
def set_keys(self, keys): """ Parse all the key codes and save them """ codes = {} for key in keys: parts = [k.strip().lower() for k in key.split("+")] code = KEYS.get(parts[-1]) modifier = Qt.KeyboardModifiers() if code is None: ra...
[ "def", "set_keys", "(", "self", ",", "keys", ")", ":", "codes", "=", "{", "}", "for", "key", "in", "keys", ":", "parts", "=", "[", "k", ".", "strip", "(", ")", ".", "lower", "(", ")", "for", "k", "in", "key", ".", "split", "(", "\"+\"", ")", ...
40.6
0.002407
def work(self, socket, call, args, kwargs, topics=()): """Calls a function and send results to the collector. It supports all of function actions. A function could return, yield, raise any packable objects. """ task_id = uuid4_bytes() reply_socket, topics = self.replier...
[ "def", "work", "(", "self", ",", "socket", ",", "call", ",", "args", ",", "kwargs", ",", "topics", "=", "(", ")", ")", ":", "task_id", "=", "uuid4_bytes", "(", ")", "reply_socket", ",", "topics", "=", "self", ".", "replier", "(", "socket", ",", "to...
41.297872
0.002013
def add_backend(self, backend): "Add a RapidSMS backend to this tenant" if backend in self.get_backends(): return backend_link, created = BackendLink.all_tenants.get_or_create(backend=backend) self.backendlink_set.add(backend_link)
[ "def", "add_backend", "(", "self", ",", "backend", ")", ":", "if", "backend", "in", "self", ".", "get_backends", "(", ")", ":", "return", "backend_link", ",", "created", "=", "BackendLink", ".", "all_tenants", ".", "get_or_create", "(", "backend", "=", "ba...
45
0.010909
def _dnsname_match(dn, hostname, max_wildcards=1): """Matching according to RFC 6125, section 6.4.3 http://tools.ietf.org/html/rfc6125#section-6.4.3 """ pats = [] if not dn: return False split_dn = dn.split(r'.') leftmost, remainder = split_dn[0], split_dn[1:] wildcards = left...
[ "def", "_dnsname_match", "(", "dn", ",", "hostname", ",", "max_wildcards", "=", "1", ")", ":", "pats", "=", "[", "]", "if", "not", "dn", ":", "return", "False", "split_dn", "=", "dn", ".", "split", "(", "r'.'", ")", "leftmost", ",", "remainder", "=",...
37.9375
0.000535
def read_dna(path): '''Read DNA from file. Uses BioPython and coerces to coral format. :param path: Full path to input file. :type path: str :returns: DNA sequence. :rtype: coral.DNA ''' filename, ext = os.path.splitext(os.path.split(path)[-1]) genbank_exts = ['.gb', '.ape'] fasta...
[ "def", "read_dna", "(", "path", ")", ":", "filename", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "split", "(", "path", ")", "[", "-", "1", "]", ")", "genbank_exts", "=", "[", "'.gb'", ",", "'.ape'", "]", "...
29.3125
0.000688
def distance_matrix(self, leaf_labels=False): '''Return a distance matrix (2D dictionary) of the leaves of this ``Tree`` Args: ``leaf_labels`` (``bool``): ``True`` to have keys be labels of leaf ``Node`` objects, otherwise ``False`` to have keys be ``Node`` objects Returns: ...
[ "def", "distance_matrix", "(", "self", ",", "leaf_labels", "=", "False", ")", ":", "M", "=", "dict", "(", ")", "leaf_dists", "=", "dict", "(", ")", "for", "node", "in", "self", ".", "traverse_postorder", "(", ")", ":", "if", "node", ".", "is_leaf", "...
53.589744
0.009868
def retrieve_commands(self, module): """ Function smartly imports Command type classes given module Args ---- module (module): The module which Command classes will be extracted from Returns ------- commands (list): A list of ...
[ "def", "retrieve_commands", "(", "self", ",", "module", ")", ":", "commands", "=", "[", "]", "for", "name", ",", "obj", "in", "inspect", ".", "getmembers", "(", "module", ")", ":", "if", "name", "!=", "'Command'", "and", "'Command'", "in", "name", ":",...
28.133333
0.002291
def zcta_to_lat_long(zcta): """Get location of ZCTA centroid Retrieves latitude and longitude of centroid of ZCTA to use for matching with weather station. Parameters ---------- zcta : str ID of the target ZCTA. Returns ------- latitude : float Latitude of centroid...
[ "def", "zcta_to_lat_long", "(", "zcta", ")", ":", "valid_zcta_or_raise", "(", "zcta", ")", "conn", "=", "metadata_db_connection_proxy", ".", "get_connection", "(", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "\"\"\"\n sel...
20.641026
0.001186
def corr_heatmap( x, mask_half=True, cmap="RdYlGn_r", vmin=-1, vmax=1, linewidths=0.5, square=True, figsize=(10, 10), **kwargs ): """Wrapper around seaborn.heatmap for visualizing correlation matrix. Parameters ---------- x : DataFrame Underly...
[ "def", "corr_heatmap", "(", "x", ",", "mask_half", "=", "True", ",", "cmap", "=", "\"RdYlGn_r\"", ",", "vmin", "=", "-", "1", ",", "vmax", "=", "1", ",", "linewidths", "=", "0.5", ",", "square", "=", "True", ",", "figsize", "=", "(", "10", ",", "...
26.588235
0.000711
def superimpose(self, module): """ superimpose a task module on registered tasks''' :param module: ape tasks module that is superimposed on available ape tasks :return: None """ featuremonkey.compose(module, self._tasks) self._tasks.FEATURE_SELECTION.append(module...
[ "def", "superimpose", "(", "self", ",", "module", ")", ":", "featuremonkey", ".", "compose", "(", "module", ",", "self", ".", "_tasks", ")", "self", ".", "_tasks", ".", "FEATURE_SELECTION", ".", "append", "(", "module", ".", "__name__", ")" ]
40.375
0.009091
def register_view(self, view): """Loads the text taking it from the model, then starts a timer to scroll it.""" self.view.set_text(self.model.credits) gobject.timeout_add(1500, self.on_begin_scroll) return
[ "def", "register_view", "(", "self", ",", "view", ")", ":", "self", ".", "view", ".", "set_text", "(", "self", ".", "model", ".", "credits", ")", "gobject", ".", "timeout_add", "(", "1500", ",", "self", ".", "on_begin_scroll", ")", "return" ]
40
0.008163
def psaux(name): ''' Retrieve information corresponding to a "ps aux" filtered with the given pattern. It could be just a name or a regular expression (using python search from "re" module). CLI Example: .. code-block:: bash salt '*' ps.psaux www-data.+apache2 ''' sanitize_nam...
[ "def", "psaux", "(", "name", ")", ":", "sanitize_name", "=", "six", ".", "text_type", "(", "name", ")", "pattern", "=", "re", ".", "compile", "(", "sanitize_name", ")", "salt_exception_pattern", "=", "re", ".", "compile", "(", "\"salt.+ps.psaux.+\"", ")", ...
31.033333
0.001042
def find_f(data): """ Given a distribution of directions, this function determines parameters (elongation, inclination, flattening factor, and elongation direction) that are consistent with the TK03 secular variation model. Parameters ---------- data : array of declination, inclination pair...
[ "def", "find_f", "(", "data", ")", ":", "rad", "=", "np", ".", "pi", "/", "180.", "Es", ",", "Is", ",", "Fs", ",", "V2s", "=", "[", "]", ",", "[", "]", ",", "[", "]", ",", "[", "]", "ppars", "=", "doprinc", "(", "data", ")", "D", "=", "...
37.193548
0.000845
def is_cnpjcpf(numero, estrito=False): """Uma versão conveniente para usar em testes condicionais. Apenas retorna verdadeiro ou falso, conforme o argumento é validado. :param bool estrito: Padrão ``False``, indica se apenas os dígitos do número deverão ser considerados. Se verdadeiro, potenciais ca...
[ "def", "is_cnpjcpf", "(", "numero", ",", "estrito", "=", "False", ")", ":", "_numero", "=", "digitos", "(", "numero", ")", "if", "not", "estrito", "else", "numero", "try", ":", "cnpj", "(", "_numero", ")", "return", "True", "except", "NumeroCNPJError", "...
33
0.001473
def update(self, campaign_id, title, is_smooth, online_status, nick=None): '''xxxxx.xxxxx.campaign.update =================================== 更新一个推广计划,可以设置推广计划名字、是否平滑消耗,只有在设置了日限额后平滑消耗才会产生作用。''' request = TOPRequest('xxxxx.xxxxx.campaign.update') request['campaign_id'] = campaign_...
[ "def", "update", "(", "self", ",", "campaign_id", ",", "title", ",", "is_smooth", ",", "online_status", ",", "nick", "=", "None", ")", ":", "request", "=", "TOPRequest", "(", "'xxxxx.xxxxx.campaign.update'", ")", "request", "[", "'campaign_id'", "]", "=", "c...
54
0.016692
def get_all_bundle_tasks(self, bundle_ids=None, filters=None): """ Retrieve current bundling tasks. If no bundle id is specified, all tasks are retrieved. :type bundle_ids: list :param bundle_ids: A list of strings containing identifiers for previously...
[ "def", "get_all_bundle_tasks", "(", "self", ",", "bundle_ids", "=", "None", ",", "filters", "=", "None", ")", ":", "params", "=", "{", "}", "if", "bundle_ids", ":", "self", ".", "build_list_params", "(", "params", ",", "bundle_ids", ",", "'BundleId'", ")",...
42.142857
0.001657
def _get_headnode_dict(fixer_list): """ Accepts a list of fixers and returns a dictionary of head node type --> fixer list. """ head_nodes = collections.defaultdict(list) every = [] for fixer in fixer_list: if fixer.pattern: try: heads = _get_head_types(fixer...
[ "def", "_get_headnode_dict", "(", "fixer_list", ")", ":", "head_nodes", "=", "collections", ".", "defaultdict", "(", "list", ")", "every", "=", "[", "]", "for", "fixer", "in", "fixer_list", ":", "if", "fixer", ".", "pattern", ":", "try", ":", "heads", "=...
37.869565
0.00112
def invert(self): """ Convert solid space to empty space and empty space to solid space. """ for poly in self.polygons: poly.flip() self.plane.flip() if self.front: self.front.invert() if self.back: self.back.invert() ...
[ "def", "invert", "(", "self", ")", ":", "for", "poly", "in", "self", ".", "polygons", ":", "poly", ".", "flip", "(", ")", "self", ".", "plane", ".", "flip", "(", ")", "if", "self", ".", "front", ":", "self", ".", "front", ".", "invert", "(", ")...
27.214286
0.01269
def highlight_syntax(src, lang, linenums=False): """Pass code to the [Pygments](http://pygments.pocoo.org/) highliter with optional line numbers. The output should then be styled with CSS to your liking. No styles are applied by default - only styling hooks (i.e.: <span class="k">). """ src = s...
[ "def", "highlight_syntax", "(", "src", ",", "lang", ",", "linenums", "=", "False", ")", ":", "src", "=", "src", ".", "strip", "(", "'\\n'", ")", "if", "not", "lang", ":", "lexer", "=", "TextLexer", "(", ")", "else", ":", "try", ":", "lexer", "=", ...
36.083333
0.001125
def avail_locations(call=None): ''' Return a dict of all available regions. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) ret = {} ret['loc...
[ "def", "avail_locations", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The avail_locations function must be called with '", "'-f or --function, or with the --list-locations option'", ")", "ret", "=", "{", ...
33.387097
0.000939
def register_module_classes(yaml: ruamel.yaml.YAML, modules: Optional[Iterable[Any]] = None) -> ruamel.yaml.YAML: """ Register all classes in the given modules with the YAML object. This is a simple helper function. """ # Validation if modules is None: modules = [] # Extract the classe...
[ "def", "register_module_classes", "(", "yaml", ":", "ruamel", ".", "yaml", ".", "YAML", ",", "modules", ":", "Optional", "[", "Iterable", "[", "Any", "]", "]", "=", "None", ")", "->", "ruamel", ".", "yaml", ".", "YAML", ":", "# Validation", "if", "modu...
37.470588
0.01072
def stop(self, force=False): """ Send a terminate request. :param bool force: ignore the remote devices response """ if self._initialized: self.send(C1218TerminateRequest()) data = self.recv() if data == b'\x00' or force: self._initialized = False self._toggle_bit = False return True r...
[ "def", "stop", "(", "self", ",", "force", "=", "False", ")", ":", "if", "self", ".", "_initialized", ":", "self", ".", "send", "(", "C1218TerminateRequest", "(", ")", ")", "data", "=", "self", ".", "recv", "(", ")", "if", "data", "==", "b'\\x00'", ...
22.714286
0.042296
def rvs_alt(self, *args, **kwargs): """{0}""" l = kwargs.get('l', 1) b = kwargs.get('b', 1e5) size = kwargs.get('size', 1) model_cdf = self.cdf(np.arange(l, b + 1), *args) unif_rands = np.random.random(size) model_rands = np.array([np.where(tx <= model_cdf)[0][0...
[ "def", "rvs_alt", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "l", "=", "kwargs", ".", "get", "(", "'l'", ",", "1", ")", "b", "=", "kwargs", ".", "get", "(", "'b'", ",", "1e5", ")", "size", "=", "kwargs", ".", "get", "...
30.153846
0.009901
def from_file(cls, filename): """Initialize datasource from file (.tds ot .tdsx)""" dsxml = xml_open(filename, 'datasource').getroot() return cls(dsxml, filename)
[ "def", "from_file", "(", "cls", ",", "filename", ")", ":", "dsxml", "=", "xml_open", "(", "filename", ",", "'datasource'", ")", ".", "getroot", "(", ")", "return", "cls", "(", "dsxml", ",", "filename", ")" ]
36.6
0.010695
def htmlCtxtUseOptions(self, options): """Applies the options to the parser context """ ret = libxml2mod.htmlCtxtUseOptions(self._o, options) return ret
[ "def", "htmlCtxtUseOptions", "(", "self", ",", "options", ")", ":", "ret", "=", "libxml2mod", ".", "htmlCtxtUseOptions", "(", "self", ".", "_o", ",", "options", ")", "return", "ret" ]
43.25
0.011364
def add_node(self, node_name, dataframe=False): """ Add a single node to the network. """ if node_name is None: return None return self.add_nodes([node_name], dataframe=dataframe)
[ "def", "add_node", "(", "self", ",", "node_name", ",", "dataframe", "=", "False", ")", ":", "if", "node_name", "is", "None", ":", "return", "None", "return", "self", ".", "add_nodes", "(", "[", "node_name", "]", ",", "dataframe", "=", "dataframe", ")" ]
42.2
0.009302
def likelihood(self, outcomes, modelparams, expparams): """ Calculates the likelihood function at the states specified by modelparams and measurement specified by expparams. This is given by the Born rule and is the probability of outcomes given the state and measurement operato...
[ "def", "likelihood", "(", "self", ",", "outcomes", ",", "modelparams", ",", "expparams", ")", ":", "# By calling the superclass implementation, we can consolidate", "# call counting there.", "super", "(", "RebitStatePauliModel", ",", "self", ")", ".", "likelihood", "(", ...
36.058824
0.012708
def drop_all(self): """Drops all tables in the database""" log.info('dropping tables in %s', self.engine.url) self.session.commit() models.Base.metadata.drop_all(self.engine) self.session.commit()
[ "def", "drop_all", "(", "self", ")", ":", "log", ".", "info", "(", "'dropping tables in %s'", ",", "self", ".", "engine", ".", "url", ")", "self", ".", "session", ".", "commit", "(", ")", "models", ".", "Base", ".", "metadata", ".", "drop_all", "(", ...
38.5
0.008475
def check_frequency(freq, res, aniso, epermH, epermV, mpermH, mpermV, verb): r"""Calculate frequency-dependent parameters. This check-function is called from one of the modelling routines in :mod:`model`. Consult these modelling routines for a detailed description of the input parameters. Paramet...
[ "def", "check_frequency", "(", "freq", ",", "res", ",", "aniso", ",", "epermH", ",", "epermV", ",", "mpermH", ",", "mpermV", ",", "verb", ")", ":", "global", "_min_freq", "# Check if the user provided a model for etaH/etaV/zetaH/zetaV", "if", "isinstance", "(", "r...
31.26087
0.000449
def eval(self, cmd): """Evaluate a given command. The command is parsed and the output returned as a list of lines (strings). Raises a SCOCmdSyntaxError in case the command cannot be parsed. Parameters ---------- cmd : strings Command string Returns...
[ "def", "eval", "(", "self", ",", "cmd", ")", ":", "tokens", "=", "cmd", ".", "upper", "(", ")", ".", "split", "(", ")", "if", "len", "(", "tokens", ")", "==", "2", "and", "tokens", "[", "0", "]", "==", "'LIST'", ":", "if", "tokens", "[", "1",...
36.466667
0.001781
def _run_search_request( self, protocol_request, object_name, protocol_response_class): """ Runs the specified request at the specified object_name and instantiates an object of the specified class. We yield each object in listAttr. If pages of results are present, repeat th...
[ "def", "_run_search_request", "(", "self", ",", "protocol_request", ",", "object_name", ",", "protocol_response_class", ")", ":", "not_done", "=", "True", "while", "not_done", ":", "response_object", "=", "self", ".", "_run_search_page_request", "(", "protocol_request...
46.368421
0.002225
def allow_ast_comparison(): """This ugly little monkey-patcher adds in a helper class to all the AST node types. This helper class allows eq/ne comparisons to work, so that entire trees can be easily compared by Python's comparison machinery. Used by the anti8 functions to compare old and new ASTs....
[ "def", "allow_ast_comparison", "(", ")", ":", "class", "CompareHelper", "(", "object", ")", ":", "def", "__eq__", "(", "self", ",", "other", ")", ":", "return", "type", "(", "self", ")", "==", "type", "(", "other", ")", "and", "vars", "(", "self", ")...
33.576923
0.001114
def _parse_cod_segment(cls, fptr): """Parse the COD segment. Parameters ---------- fptr : file Open file object. Returns ------- CODSegment The current COD segment. """ offset = fptr.tell() - 2 read_buffer = fptr....
[ "def", "_parse_cod_segment", "(", "cls", ",", "fptr", ")", ":", "offset", "=", "fptr", ".", "tell", "(", ")", "-", "2", "read_buffer", "=", "fptr", ".", "read", "(", "2", ")", "length", ",", "=", "struct", ".", "unpack", "(", "'>H'", ",", "read_buf...
25.55
0.001885
def remover(self, id_net_type): """Remove network type by its identifier. :param id_net_type: Network type identifier. :return: None :raise TipoRedeNaoExisteError: Network type does not exist. :raise TipoRedeError: Network type is associated with network. :raise Invali...
[ "def", "remover", "(", "self", ",", "id_net_type", ")", ":", "if", "not", "is_valid_int_param", "(", "id_net_type", ")", ":", "raise", "InvalidParameterError", "(", "u'Network type is invalid or was not informed.'", ")", "url", "=", "'net_type/'", "+", "str", "(", ...
36.636364
0.002418
def cond_uniqualize(l,**kwargs): ''' from elist.elist import * l = [('BIGipServer', 'rd100'), ('TS013d8ed5', '00A0'), ('BIGipServer', 'rd200'), ('TS013d8ed5', '00B0'), ('SID', '1'), ('SID', '2')] def cond_func(ele,*args): cond = ele[0] return(cond) ...
[ "def", "cond_uniqualize", "(", "l", ",", "*", "*", "kwargs", ")", ":", "cond_func", "=", "kwargs", "[", "'cond_func'", "]", "if", "(", "'cond_func_args'", "in", "kwargs", ")", ":", "cond_func_args", "=", "kwargs", "[", "'cond_func_args'", "]", "else", ":",...
30.030303
0.008305
def append(self, _, child, name=None): """Adds childs to this tag, after the current existing childs.""" self._insert(child, name=name) return self
[ "def", "append", "(", "self", ",", "_", ",", "child", ",", "name", "=", "None", ")", ":", "self", ".", "_insert", "(", "child", ",", "name", "=", "name", ")", "return", "self" ]
42
0.011696
def quantile(x, q, interpolation_method='fraction'): """ Compute sample quantile or quantiles of the input array. For example, q=0.5 computes the median. The `interpolation_method` parameter supports three values, namely `fraction` (default), `lower` and `higher`. Interpolation is done only, if...
[ "def", "quantile", "(", "x", ",", "q", ",", "interpolation_method", "=", "'fraction'", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "mask", "=", "isna", "(", "x", ")", "x", "=", "x", "[", "~", "mask", "]", "values", "=", "np", ".", ...
30.961538
0.000401
def delete_parameter_group(name, region=None, key=None, keyid=None, profile=None): ''' Delete an RDS parameter group. CLI example:: salt myminion boto_rds.delete_parameter_group my-param-group \ region=us-east-1 ''' try: conn = _get_conn(r...
[ "def", "delete_parameter_group", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", ...
34.35
0.001416
def create_alias(self, alias_name): """Creates an alias pointing to the index configured in this connection""" return self._es_conn.indices.put_alias(index=self._es_index, name=alias_name)
[ "def", "create_alias", "(", "self", ",", "alias_name", ")", ":", "return", "self", ".", "_es_conn", ".", "indices", ".", "put_alias", "(", "index", "=", "self", ".", "_es_index", ",", "name", "=", "alias_name", ")" ]
50.5
0.019512
def mkchange(text0,text1,version,mtime): "return a Change diffing the two strings" return Change(version,mtime,ucrc(text1),diff.word_diff(text0,text1))
[ "def", "mkchange", "(", "text0", ",", "text1", ",", "version", ",", "mtime", ")", ":", "return", "Change", "(", "version", ",", "mtime", ",", "ucrc", "(", "text1", ")", ",", "diff", ".", "word_diff", "(", "text0", ",", "text1", ")", ")" ]
51.666667
0.063694
def toYearFraction(date): """Converts :class:`datetime.date` or :class:`datetime.datetime` to decimal year. Parameters ========== date : :class:`datetime.date` or :class:`datetime.datetime` Returns ======= year : float Decimal year Notes ===== The algorithm is take...
[ "def", "toYearFraction", "(", "date", ")", ":", "def", "sinceEpoch", "(", "date", ")", ":", "\"\"\"returns seconds since epoch\"\"\"", "return", "time", ".", "mktime", "(", "date", ".", "timetuple", "(", ")", ")", "year", "=", "date", ".", "year", "startOfTh...
26.548387
0.001172
def _sort_dd_skips(configs, dd_indices_all): """Given a set of dipole-dipole configurations, sort them according to their current skip. Parameters ---------- configs: Nx4 numpy.ndarray Dipole-Dipole configurations Returns ------- dd_configs_sorted: dict dictionary with ...
[ "def", "_sort_dd_skips", "(", "configs", ",", "dd_indices_all", ")", ":", "config_current_skips", "=", "np", ".", "abs", "(", "configs", "[", ":", ",", "1", "]", "-", "configs", "[", ":", ",", "0", "]", ")", "if", "np", ".", "all", "(", "np", ".", ...
29.25
0.001034
def _cubic_bernstein(p0, p1, p2, p3, t): """ Evaluate polynomial of given bernstein coefficients using de Casteljau's algorithm. """ u = 1 - t return p0*(u**3) + 3*t*u*(p1*u + p2*t) + p3*(t**3)
[ "def", "_cubic_bernstein", "(", "p0", ",", "p1", ",", "p2", ",", "p3", ",", "t", ")", ":", "u", "=", "1", "-", "t", "return", "p0", "*", "(", "u", "**", "3", ")", "+", "3", "*", "t", "*", "u", "*", "(", "p1", "*", "u", "+", "p2", "*", ...
33.571429
0.008299
def puts_err(s='', newline=True, stream=STDERR): """Prints given string to stderr.""" puts(s, newline, stream)
[ "def", "puts_err", "(", "s", "=", "''", ",", "newline", "=", "True", ",", "stream", "=", "STDERR", ")", ":", "puts", "(", "s", ",", "newline", ",", "stream", ")" ]
38.666667
0.008475
def set_state(self, newState, timer=0): """This function is called when the client wants to change state.""" if _debug: ServerSSM._debug("set_state %r (%s) timer=%r", newState, SSM.transactionLabels[newState], timer) # do the regular state change SSM.set_state(self, newState, timer) ...
[ "def", "set_state", "(", "self", ",", "newState", ",", "timer", "=", "0", ")", ":", "if", "_debug", ":", "ServerSSM", ".", "_debug", "(", "\"set_state %r (%s) timer=%r\"", ",", "newState", ",", "SSM", ".", "transactionLabels", "[", "newState", "]", ",", "t...
48.4375
0.008861
def listdir_attr(self, path='.'): """ Return a list containing L{SFTPAttributes} objects corresponding to files in the given C{path}. The list is in arbitrary order. It does not include the special entries C{'.'} and C{'..'} even if they are present in the folder. The ...
[ "def", "listdir_attr", "(", "self", ",", "path", "=", "'.'", ")", ":", "path", "=", "self", ".", "_adjust_cwd", "(", "path", ")", "self", ".", "_log", "(", "DEBUG", ",", "'listdir(%r)'", "%", "path", ")", "t", ",", "msg", "=", "self", ".", "_reques...
39.604651
0.001146
def main(): """ Parses user input for a package name :return: """ parser = argparse.ArgumentParser('Determines the health of a package') parser.add_argument( 'package_name', help='Name of package listed on pypi.python.org', ) parser.add_argument( 'package_versio...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "'Determines the health of a package'", ")", "parser", ".", "add_argument", "(", "'package_name'", ",", "help", "=", "'Name of package listed on pypi.python.org'", ",", ")", "parser",...
26.03125
0.002315
def tweet_list_handler(request, tweet_list_builder, msg_prefix=""): """ This is a generic function to handle any intent that reads out a list of tweets""" # tweet_list_builder is a function that takes a unique identifier and returns a list of things to say tweets = tweet_list_builder(request.access_token()...
[ "def", "tweet_list_handler", "(", "request", ",", "tweet_list_builder", ",", "msg_prefix", "=", "\"\"", ")", ":", "# tweet_list_builder is a function that takes a unique identifier and returns a list of things to say", "tweets", "=", "tweet_list_builder", "(", "request", ".", "...
62.1875
0.009901
def _general_init(self, opts, out=None): """ Initializes a variety of variables depending on user input. @return: a tuple containing a boolean value indicating whether progressbars should be hidden, functionality and enabled functionality. """ se...
[ "def", "_general_init", "(", "self", ",", "opts", ",", "out", "=", "None", ")", ":", "self", ".", "session", "=", "Session", "(", ")", "if", "out", ":", "self", ".", "out", "=", "out", "else", ":", "self", ".", "out", "=", "self", ".", "_output",...
36.24
0.001612
def setproject_cmd(argv): """Given a virtualenv directory and a project directory, set the \ virtualenv up to be associated with the project.""" args = dict(enumerate(argv)) project = os.path.abspath(args.get(1, '.')) env = args.get(0, os.environ.get('VIRTUAL_ENV')) if not env: sys.exit(...
[ "def", "setproject_cmd", "(", "argv", ")", ":", "args", "=", "dict", "(", "enumerate", "(", "argv", ")", ")", "project", "=", "os", ".", "path", ".", "abspath", "(", "args", ".", "get", "(", "1", ",", "'.'", ")", ")", "env", "=", "args", ".", "...
45.384615
0.001661
def _create_or_update_user( self, create, name, password, read_only, **kwargs): """Use a command to create (if create=True) or modify a user. """ opts = {} if read_only or (create and "roles" not in kwargs): warnings.warn("Creating a user with the read_only option...
[ "def", "_create_or_update_user", "(", "self", ",", "create", ",", "name", ",", "password", ",", "read_only", ",", "*", "*", "kwargs", ")", ":", "opts", "=", "{", "}", "if", "read_only", "or", "(", "create", "and", "\"roles\"", "not", "in", "kwargs", ")...
42.108108
0.001255
def dbsafe_encode(value, compress_object=False): """ We use deepcopy() here to avoid a problem with cPickle, where dumps can generate different character streams for same lookup value if they are referenced differently. The reason this is important is because we do all of our lookups as simple ...
[ "def", "dbsafe_encode", "(", "value", ",", "compress_object", "=", "False", ")", ":", "if", "not", "compress_object", ":", "value", "=", "b64encode", "(", "dumps", "(", "deepcopy", "(", "value", ")", ")", ")", "else", ":", "value", "=", "b64encode", "(",...
41.733333
0.001563
def apply_model(refwcs): """ Apply distortion model to WCS, including modifying CD with linear distortion terms """ # apply distortion model to CD matrix if 'ocx10' in refwcs.__dict__ and refwcs.ocx10 is not None: linmat = np.array([[refwcs.ocx11,refwcs.ocx10],[refwcs.ocy11,refwcs.ocy10...
[ "def", "apply_model", "(", "refwcs", ")", ":", "# apply distortion model to CD matrix", "if", "'ocx10'", "in", "refwcs", ".", "__dict__", "and", "refwcs", ".", "ocx10", "is", "not", "None", ":", "linmat", "=", "np", ".", "array", "(", "[", "[", "refwcs", "...
35.384615
0.012712
def either(*funcs): """ A utility function for selecting the first non-null query. Parameters: funcs: One or more functions Returns: A function that, when called with a :class:`Node`, will pass the input to each `func`, and return the first non-Falsey result. Examples...
[ "def", "either", "(", "*", "funcs", ")", ":", "def", "either", "(", "val", ")", ":", "for", "func", "in", "funcs", ":", "result", "=", "val", ".", "apply", "(", "func", ")", "if", "result", ":", "return", "result", "return", "Null", "(", ")", "re...
21.214286
0.00161
def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn...
[ "def", "role_exists", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", ...
25.25
0.002387
def dfs_grid(grid, i, j, mark='X', free='.'): """DFS on a grid, mark connected component, iterative version :param grid: matrix, 4-neighborhood :param i,j: cell in this matrix, start of DFS exploration :param free: symbol for walkable cells :param mark: symbol to overwrite visited vertices :com...
[ "def", "dfs_grid", "(", "grid", ",", "i", ",", "j", ",", "mark", "=", "'X'", ",", "free", "=", "'.'", ")", ":", "height", "=", "len", "(", "grid", ")", "width", "=", "len", "(", "grid", "[", "0", "]", ")", "to_visit", "=", "[", "(", "i", ",...
36.333333
0.001277
def apps_notify_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/apps#send-notification-to-app" api_path = "/api/v2/apps/notify.json" return self.call(api_path, method="POST", data=data, **kwargs)
[ "def", "apps_notify_create", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/apps/notify.json\"", "return", "self", ".", "call", "(", "api_path", ",", "method", "=", "\"POST\"", ",", "data", "=", "data", ",", "*", ...
62
0.011952
def checkASN(filename): """ Determine if the filename provided to the function belongs to an association. Parameters ---------- filename: string Returns ------- validASN : boolean value """ # Extract the file extn type: extnType = filename[filename.rfind('_')+1:filena...
[ "def", "checkASN", "(", "filename", ")", ":", "# Extract the file extn type:", "extnType", "=", "filename", "[", "filename", ".", "rfind", "(", "'_'", ")", "+", "1", ":", "filename", ".", "rfind", "(", "'.'", ")", "]", "# Determine if this extn name is valid for...
21.181818
0.002053
def explore_uri(self, explorer_resource, show_back=True): """INTERACTIVE exploration of capabilities document(s) starting at a given URI. Will flag warnings if the document is not of type listed in caps. """ uri = explorer_resource.uri caps = explorer_resource.acceptable_capabil...
[ "def", "explore_uri", "(", "self", ",", "explorer_resource", ",", "show_back", "=", "True", ")", ":", "uri", "=", "explorer_resource", ".", "uri", "caps", "=", "explorer_resource", ".", "acceptable_capabilities", "checks", "=", "explorer_resource", ".", "checks", ...
38.738462
0.001162
def get_changelog_types(pr_payload): """ Fetch the labels from the PR and process the ones related to the changelog. """ changelog_labels = [] for name in get_pr_labels(pr_payload): if name.startswith(CHANGELOG_LABEL_PREFIX): # only add the name, e.g. for `changelog/Added` it's j...
[ "def", "get_changelog_types", "(", "pr_payload", ")", ":", "changelog_labels", "=", "[", "]", "for", "name", "in", "get_pr_labels", "(", "pr_payload", ")", ":", "if", "name", ".", "startswith", "(", "CHANGELOG_LABEL_PREFIX", ")", ":", "# only add the name, e.g. fo...
38.636364
0.002299
def make_directory(self, directory_name, *args, **kwargs): """ :meth:`.WNetworkClientProto.make_directory` method implementation """ self.dav_client().mkdir(self.join_path(self.session_path(), directory_name))
[ "def", "make_directory", "(", "self", ",", "directory_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "dav_client", "(", ")", ".", "mkdir", "(", "self", ".", "join_path", "(", "self", ".", "session_path", "(", ")", ",", "dire...
53
0.023256
def _db_pre_transform(self, train_tfm:List[Callable], valid_tfm:List[Callable]): "Call `train_tfm` and `valid_tfm` after opening image, before converting from `PIL.Image`" self.train_ds.x.after_open = compose(train_tfm) self.valid_ds.x.after_open = compose(valid_tfm) return self
[ "def", "_db_pre_transform", "(", "self", ",", "train_tfm", ":", "List", "[", "Callable", "]", ",", "valid_tfm", ":", "List", "[", "Callable", "]", ")", ":", "self", ".", "train_ds", ".", "x", ".", "after_open", "=", "compose", "(", "train_tfm", ")", "s...
58.2
0.016949
def get_bind_modules(verbose=False): """Get available bind modules. Returns: dict: Map of (name, filepath) listing all bind modules. """ builtin_path = os.path.join(module_root_path, "bind") searchpaths = config.bind_module_path + [builtin_path] bindnames = {} for path in searchpat...
[ "def", "get_bind_modules", "(", "verbose", "=", "False", ")", ":", "builtin_path", "=", "os", ".", "path", ".", "join", "(", "module_root_path", ",", "\"bind\"", ")", "searchpaths", "=", "config", ".", "bind_module_path", "+", "[", "builtin_path", "]", "bind...
30.583333
0.001321
def _cbCvtReply(self, msg, returnSignature): """ Converts a remote method call reply message into an appropriate callback value. """ if msg is None: return None if returnSignature != _NO_CHECK_RETURN: if not returnSignature: ...
[ "def", "_cbCvtReply", "(", "self", ",", "msg", ",", "returnSignature", ")", ":", "if", "msg", "is", "None", ":", "return", "None", "if", "returnSignature", "!=", "_NO_CHECK_RETURN", ":", "if", "not", "returnSignature", ":", "if", "msg", ".", "signature", "...
34.941176
0.001638
def format_message_type(message_type): """ Get printable version for message type :param message_type: Message type :type message_type: int :return: Printable version :rtype: str """ if message_type == MsgType.NOT_SET: return "NOT_SET" elif message_type == MsgType.ACK: ...
[ "def", "format_message_type", "(", "message_type", ")", ":", "if", "message_type", "==", "MsgType", ".", "NOT_SET", ":", "return", "\"NOT_SET\"", "elif", "message_type", "==", "MsgType", ".", "ACK", ":", "return", "\"ACK\"", "elif", "message_type", "==", "MsgTyp...
27.2
0.00142
def _consolidate_repo_sources(sources): ''' Consolidate APT sources. ''' if not isinstance(sources, sourceslist.SourcesList): raise TypeError( '\'{0}\' not a \'{1}\''.format( type(sources), sourceslist.SourcesList ) ) consolida...
[ "def", "_consolidate_repo_sources", "(", "sources", ")", ":", "if", "not", "isinstance", "(", "sources", ",", "sourceslist", ".", "SourcesList", ")", ":", "raise", "TypeError", "(", "'\\'{0}\\' not a \\'{1}\\''", ".", "format", "(", "type", "(", "sources", ")", ...
30.880952
0.001495
def _is_billing_complete(self): """Has the specified `fixed_amount` been billed? If so, we should not be enacting this RecurringCost. """ if self.is_one_off(): return self.get_billed_amount() >= Balance(self.fixed_amount, self.currency) else: return False
[ "def", "_is_billing_complete", "(", "self", ")", ":", "if", "self", ".", "is_one_off", "(", ")", ":", "return", "self", ".", "get_billed_amount", "(", ")", ">=", "Balance", "(", "self", ".", "fixed_amount", ",", "self", ".", "currency", ")", "else", ":",...
34.666667
0.009375
def write_combined_transit_stop_to_stop_network(gtfs, output_path, fmt=None): """ Parameters ---------- gtfs : gtfspy.GTFS output_path : str fmt: None, optional defaulting to "edg" and writing results as ".edg" files If "csv" csv files are produced instead """ if fmt is N...
[ "def", "write_combined_transit_stop_to_stop_network", "(", "gtfs", ",", "output_path", ",", "fmt", "=", "None", ")", ":", "if", "fmt", "is", "None", ":", "fmt", "=", "\"edg\"", "multi_di_graph", "=", "combined_stop_to_stop_transit_network", "(", "gtfs", ")", "_wri...
36.384615
0.002062
def config(conf_path='/etc/rsyncd.conf'): ''' .. versionchanged:: 2016.3.0 Return data now contains just the contents of the rsyncd.conf as a string, instead of a dictionary as returned from :py:func:`cmd.run_all <salt.modules.cmdmod.run_all>`. Returns the contents of the rsync conf...
[ "def", "config", "(", "conf_path", "=", "'/etc/rsyncd.conf'", ")", ":", "ret", "=", "''", "try", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "conf_path", ",", "'r'", ")", "as", "fp_", ":", "for", "line", "in", "fp_", ":", "r...
31.375
0.000773
def _send(self, data): """Send data over current socket :param data: registers value to write :type data: str (Python2) or class bytes (Python3) :returns: True if send ok or None if error :rtype: bool or None """ # check link if self.__sock is None: ...
[ "def", "_send", "(", "self", ",", "data", ")", ":", "# check link", "if", "self", ".", "__sock", "is", "None", ":", "self", ".", "__debug_msg", "(", "'call _send on close socket'", ")", "return", "None", "# send", "data_l", "=", "len", "(", "data", ")", ...
30.307692
0.00246
def tree2commands(self, adapter, session, lastcmds, xsync): '''Consumes an ET protocol tree and converts it to state.Command commands''' # do some preliminary sanity checks... # todo: do i really want to be using assert statements?... assert xsync.tag == constants.NODE_SYNCML assert len(xsync) == ...
[ "def", "tree2commands", "(", "self", ",", "adapter", ",", "session", ",", "lastcmds", ",", "xsync", ")", ":", "# do some preliminary sanity checks...", "# todo: do i really want to be using assert statements?...", "assert", "xsync", ".", "tag", "==", "constants", ".", "...
43.603448
0.021268
def add(self, command, response): """ Register a command/response pair. The command may be either a string (which is then automatically compiled into a regular expression), or a pre-compiled regular expression object. If the given response handler is a string, it is sen...
[ "def", "add", "(", "self", ",", "command", ",", "response", ")", ":", "command", "=", "re", ".", "compile", "(", "command", ")", "self", ".", "response_list", ".", "append", "(", "(", "command", ",", "response", ")", ")" ]
40.1
0.002436
def _splitext(p, sep, altsep, extsep): """Split the extension from a pathname. Extension is everything from the last dot to the end, ignoring leading dots. Returns "(root, ext)"; ext may be empty.""" sepIndex = p.rfind(sep) if altsep: altsepIndex = p.rfind(altsep) sepIndex = max(s...
[ "def", "_splitext", "(", "p", ",", "sep", ",", "altsep", ",", "extsep", ")", ":", "sepIndex", "=", "p", ".", "rfind", "(", "sep", ")", "if", "altsep", ":", "altsepIndex", "=", "p", ".", "rfind", "(", "altsep", ")", "sepIndex", "=", "max", "(", "s...
30.095238
0.001534
def sign(self, msg): """sign a message""" signature = SHA256.new() signature.update(self._mackey1) signature.update(msg) signature.update(self._mackey2) return signature.digest()
[ "def", "sign", "(", "self", ",", "msg", ")", ":", "signature", "=", "SHA256", ".", "new", "(", ")", "signature", ".", "update", "(", "self", ".", "_mackey1", ")", "signature", ".", "update", "(", "msg", ")", "signature", ".", "update", "(", "self", ...
31.428571
0.00885
def locateChild(self, ctx, segments): """ Look up a shared item for the role viewing this SharingIndex and return a L{PublicAthenaLivePage} containing that shared item's fragment to the user. These semantics are UNSTABLE. This method is adequate for simple uses, but it ...
[ "def", "locateChild", "(", "self", ",", "ctx", ",", "segments", ")", ":", "shareID", "=", "segments", "[", "0", "]", ".", "decode", "(", "'utf-8'", ")", "role", "=", "self", ".", "webViewer", ".", "roleIn", "(", "self", ".", "userStore", ")", "# if t...
38.627907
0.001762