text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _prepare_smoove_bams(full_bams, sr_bams, disc_bams, items, tx_work_dir): """Prepare BAMs for smoove, linking in pre-existing split/disc BAMs if present. Smoove can use pre-existing discordant and split BAMs prepared by samblaster if present as $sample.split.bam and $sample.disc.bam. """ input_d...
[ "def", "_prepare_smoove_bams", "(", "full_bams", ",", "sr_bams", ",", "disc_bams", ",", "items", ",", "tx_work_dir", ")", ":", "input_dir", "=", "utils", ".", "safe_makedir", "(", "tx_work_dir", ")", "out", "=", "[", "]", "for", "full", ",", "sr", ",", "...
46.9
22.2
def _uncythonized_model(self, beta): """ Creates the structure of the model Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- theta : np.array Contains the predicted value...
[ "def", "_uncythonized_model", "(", "self", ",", "beta", ")", ":", "parm", "=", "np", ".", "array", "(", "[", "self", ".", "latent_variables", ".", "z_list", "[", "k", "]", ".", "prior", ".", "transform", "(", "beta", "[", "k", "]", ")", "for", "k",...
40
31.965517
def entry(argv): ''' Command entry ''' command_dic = { 'migrate': run_migrate, 'init': run_init, 'send_nologin': run_send_nologin, 'send_all': run_send_all, 'review': run_review, 'sitemap': run_sitemap, 'editmap': run_editmap, 'check_kind':...
[ "def", "entry", "(", "argv", ")", ":", "command_dic", "=", "{", "'migrate'", ":", "run_migrate", ",", "'init'", ":", "run_init", ",", "'send_nologin'", ":", "run_send_nologin", ",", "'send_all'", ":", "run_send_all", ",", "'review'", ":", "run_review", ",", ...
29.45098
11.529412
def cart_get(self, CartId=None, HMAC=None, **kwargs): """CartGet fetches existing cart :param CartId: see CartCreate :param HMAC: see CartCreate :return: An :class:`~.AmazonCart`. """ if not CartId or not HMAC: raise CartException('CartId required for CartGet ...
[ "def", "cart_get", "(", "self", ",", "CartId", "=", "None", ",", "HMAC", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "CartId", "or", "not", "HMAC", ":", "raise", "CartException", "(", "'CartId required for CartGet call'", ")", "response", ...
35
13.466667
def update(self, data): "returns True if unknown" if data not in self.filter: self.filter.append(data) if len(self.filter) > self.max_items: self.filter.pop(0) return True else: self.filter.append(self.filter.pop(0)) ret...
[ "def", "update", "(", "self", ",", "data", ")", ":", "if", "data", "not", "in", "self", ".", "filter", ":", "self", ".", "filter", ".", "append", "(", "data", ")", "if", "len", "(", "self", ".", "filter", ")", ">", "self", ".", "max_items", ":", ...
32
11.8
def clear(self): """Restart with a clean config""" self._config = configparser.RawConfigParser() # Override config from command line even if we modify the config file and live reload it. self._override_config = {} self.read_config()
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_config", "=", "configparser", ".", "RawConfigParser", "(", ")", "# Override config from command line even if we modify the config file and live reload it.", "self", ".", "_override_config", "=", "{", "}", "self", "."...
38.142857
22
def add_header_check(self, code=HEADER_CHECK_FAILED, message=MESSAGES[HEADER_CHECK_FAILED]): """ Add a header check, i.e., check whether the header record is consistent with the expected field names. Arguments --------- ...
[ "def", "add_header_check", "(", "self", ",", "code", "=", "HEADER_CHECK_FAILED", ",", "message", "=", "MESSAGES", "[", "HEADER_CHECK_FAILED", "]", ")", ":", "t", "=", "code", ",", "message", "self", ".", "_header_checks", ".", "append", "(", "t", ")" ]
29.421053
21.947368
def close(self): """Close all connections in the pool.""" self._lock.acquire() try: while self._idle_cache: # close all idle connections con = self._idle_cache.pop(0) try: con.close() except Exception: ...
[ "def", "close", "(", "self", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "while", "self", ".", "_idle_cache", ":", "# close all idle connections", "con", "=", "self", ".", "_idle_cache", ".", "pop", "(", "0", ")", "try", ":", ...
34.714286
12.428571
def unregister_iq_request_handler(self, type_, payload_cls): """ Unregister a coroutine previously registered with :meth:`register_iq_request_handler`. :param type_: IQ type to react to (must be a request type). :type type_: :class:`~structs.IQType` :param payload_cls: P...
[ "def", "unregister_iq_request_handler", "(", "self", ",", "type_", ",", "payload_cls", ")", ":", "type_", "=", "self", ".", "_coerce_enum", "(", "type_", ",", "structs", ".", "IQType", ")", "del", "self", ".", "_iq_request_map", "[", "type_", ",", "payload_c...
40.9
22.9
def rec_sqrt(x, context=None): """ Return the reciprocal square root of x. Return +Inf if x is ±0, +0 if x is +Inf, and NaN if x is negative. """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_rec_sqrt, (BigFloat._implicit_convert(x),), context, ...
[ "def", "rec_sqrt", "(", "x", ",", "context", "=", "None", ")", ":", "return", "_apply_function_in_current_context", "(", "BigFloat", ",", "mpfr", ".", "mpfr_rec_sqrt", ",", "(", "BigFloat", ".", "_implicit_convert", "(", "x", ")", ",", ")", ",", "context", ...
23.769231
17.307692
def get_glitter_app(self, glitter_app_name): """ Retrieve the Glitter App config for a specific Glitter App. """ if not self.discovered: self.discover_glitter_apps() try: glitter_app = self.glitter_apps[glitter_app_name] return glitter_app ...
[ "def", "get_glitter_app", "(", "self", ",", "glitter_app_name", ")", ":", "if", "not", "self", ".", "discovered", ":", "self", ".", "discover_glitter_apps", "(", ")", "try", ":", "glitter_app", "=", "self", ".", "glitter_apps", "[", "glitter_app_name", "]", ...
29.5
14.333333
def assert_page_source_contains(self, expected_value, failure_message='Expected page source to contain: "{}"'): """ Asserts that the page source contains the string passed in expected_value """ assertion = lambda: expected_value in self.driver_wrapper.page_source() self.webdriver...
[ "def", "assert_page_source_contains", "(", "self", ",", "expected_value", ",", "failure_message", "=", "'Expected page source to contain: \"{}\"'", ")", ":", "assertion", "=", "lambda", ":", "expected_value", "in", "self", ".", "driver_wrapper", ".", "page_source", "(",...
63.666667
33.333333
def read_samples_from_file(self): """ Load the audio samples from file into memory. If ``self.file_format`` is ``None`` or it is not ``("pcm_s16le", 1, self.rconf.sample_rate)``, the file will be first converted to a temporary PCM16 mono WAVE file. Audio data wil...
[ "def", "read_samples_from_file", "(", "self", ")", ":", "self", ".", "log", "(", "u\"Loading audio data...\"", ")", "# check the file can be read", "if", "not", "gf", ".", "file_can_be_read", "(", "self", ".", "file_path", ")", ":", "self", ".", "log_exc", "(", ...
48.367816
24.942529
def pipe(): """Return the optimum pipe implementation for the capabilities of the active system.""" try: from os import pipe return pipe() except: pipe = Pipe() return pipe.reader_fd, pipe.writer_fd
[ "def", "pipe", "(", ")", ":", "try", ":", "from", "os", "import", "pipe", "return", "pipe", "(", ")", "except", ":", "pipe", "=", "Pipe", "(", ")", "return", "pipe", ".", "reader_fd", ",", "pipe", ".", "writer_fd" ]
24.3
21.8
def adjoint(self): """Adjoint of the linear operator. Note that this implementation uses an approximation that is only valid for small displacements. """ # TODO allow users to select what method to use here. div_op = Divergence(domain=self.displacement.space, method='for...
[ "def", "adjoint", "(", "self", ")", ":", "# TODO allow users to select what method to use here.", "div_op", "=", "Divergence", "(", "domain", "=", "self", ".", "displacement", ".", "space", ",", "method", "=", "'forward'", ",", "pad_mode", "=", "'symmetric'", ")",...
38.461538
16.538462
def _set_family_view(self, session): """Sets the underlying family view to match current view""" if self._family_view == COMPARATIVE: try: session.use_comparative_family_view() except AttributeError: pass else: try: ...
[ "def", "_set_family_view", "(", "self", ",", "session", ")", ":", "if", "self", ".", "_family_view", "==", "COMPARATIVE", ":", "try", ":", "session", ".", "use_comparative_family_view", "(", ")", "except", "AttributeError", ":", "pass", "else", ":", "try", "...
33.5
13.083333
def execute(func, handler, args, kwargs): """ Wrap the handler ``_execute`` method to trace incoming requests, extracting the context from the headers, if available. """ tracing = handler.settings.get('opentracing_tracing') with tracer_stack_context(): if tracing._trace_all: ...
[ "def", "execute", "(", "func", ",", "handler", ",", "args", ",", "kwargs", ")", ":", "tracing", "=", "handler", ".", "settings", ".", "get", "(", "'opentracing_tracing'", ")", "with", "tracer_stack_context", "(", ")", ":", "if", "tracing", ".", "_trace_all...
35.615385
16.384615
def resume(self, campaign_id): """ Resume an RSS-Driven campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` """ self.campaign_id = campaign_id return self._mc_client._post(url=self._build_path(campaign_id, 'actions/res...
[ "def", "resume", "(", "self", ",", "campaign_id", ")", ":", "self", ".", "campaign_id", "=", "campaign_id", "return", "self", ".", "_mc_client", ".", "_post", "(", "url", "=", "self", ".", "_build_path", "(", "campaign_id", ",", "'actions/resume'", ")", ")...
35.333333
13.777778
def transform(self, maps): """ This function transforms from spherical to cartesian spins. Parameters ---------- maps : a mapping object Examples -------- Convert a dict of numpy.array: >>> import numpy >>> from pycbc import transforms >...
[ "def", "transform", "(", "self", ",", "maps", ")", ":", "a", ",", "az", ",", "po", "=", "self", ".", "_inputs", "data", "=", "coordinates", ".", "spherical_to_cartesian", "(", "maps", "[", "a", "]", ",", "maps", "[", "az", "]", ",", "maps", "[", ...
39.035714
26.035714
def add_tileset(self, tileset): """ Add a tileset to the map :param tileset: TiledTileset """ assert (isinstance(tileset, TiledTileset)) self.tilesets.append(tileset)
[ "def", "add_tileset", "(", "self", ",", "tileset", ")", ":", "assert", "(", "isinstance", "(", "tileset", ",", "TiledTileset", ")", ")", "self", ".", "tilesets", ".", "append", "(", "tileset", ")" ]
28.714286
9.428571
def to_glyphs_master_user_data(self, ufo, master): """Set the GSFontMaster userData from the UFO master-specific lib data.""" target_user_data = master.userData for key, value in ufo.lib.items(): if _user_data_has_no_special_meaning(key): target_user_data[key] = value # Save UFO dat...
[ "def", "to_glyphs_master_user_data", "(", "self", ",", "ufo", ",", "master", ")", ":", "target_user_data", "=", "master", ".", "userData", "for", "key", ",", "value", "in", "ufo", ".", "lib", ".", "items", "(", ")", ":", "if", "_user_data_has_no_special_mean...
40.1875
14.3125
def reset_logformat(logger: logging.Logger, fmt: str, datefmt: str = '%Y-%m-%d %H:%M:%S') -> None: """ Create a new formatter and apply it to the logger. :func:`logging.basicConfig` won't reset the formatter if another module has called it, so always set the form...
[ "def", "reset_logformat", "(", "logger", ":", "logging", ".", "Logger", ",", "fmt", ":", "str", ",", "datefmt", ":", "str", "=", "'%Y-%m-%d %H:%M:%S'", ")", "->", "None", ":", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "formatter", "=", "...
36.714286
15.47619
def findTargetNS(self, node): """Return the defined target namespace uri for the given node.""" attrget = self.getAttr attrkey = (self.NS_XMLNS, 'xmlns') DOCUMENT_NODE = node.DOCUMENT_NODE ELEMENT_NODE = node.ELEMENT_NODE while 1: if node.nodeType != ELEMENT_N...
[ "def", "findTargetNS", "(", "self", ",", "node", ")", ":", "attrget", "=", "self", ".", "getAttr", "attrkey", "=", "(", "self", ".", "NS_XMLNS", ",", "'xmlns'", ")", "DOCUMENT_NODE", "=", "node", ".", "DOCUMENT_NODE", "ELEMENT_NODE", "=", "node", ".", "E...
41.3125
10
def useKeyID(self, keyID): """ Use the given API key config specified by `keyID` during subsequent API calls :param str keyID: an index into the 'keys' maintained in this config """ if keyID not in self._data['keys']: raise ConfigException('keyID does not exi...
[ "def", "useKeyID", "(", "self", ",", "keyID", ")", ":", "if", "keyID", "not", "in", "self", ".", "_data", "[", "'keys'", "]", ":", "raise", "ConfigException", "(", "'keyID does not exist: %s'", "%", "keyID", ")", "self", ".", "_keyID", "=", "keyID" ]
35.5
19.3
def get_reliabledictionary_schema(client, application_name, service_name, dictionary_name, output_file=None): """Query Schema information for existing reliable dictionaries. Query Schema information existing reliable dictionaries for given application and service. :param application_name: Name of the appl...
[ "def", "get_reliabledictionary_schema", "(", "client", ",", "application_name", ",", "service_name", ",", "dictionary_name", ",", "output_file", "=", "None", ")", ":", "cluster", "=", "Cluster", ".", "from_sfclient", "(", "client", ")", "dictionary", "=", "cluster...
43.4
25.32
def tf_combined_loss(self, states, internals, actions, terminal, reward, next_states, next_internals, update, reference=None): """ Combines Q-loss and demo loss. """ q_model_loss = self.fn_loss( states=states, internals=internals, actions=actions, ...
[ "def", "tf_combined_loss", "(", "self", ",", "states", ",", "internals", ",", "actions", ",", "terminal", ",", "reward", ",", "next_states", ",", "next_internals", ",", "update", ",", "reference", "=", "None", ")", ":", "q_model_loss", "=", "self", ".", "f...
30.296296
15.851852
def rect( self, x: int, y: int, width: int, height: int, clear: bool, bg_blend: int = tcod.constants.BKGND_DEFAULT, ) -> None: """Draw a the background color on a rect optionally clearing the text. If `clear` is True the affected tiles are cha...
[ "def", "rect", "(", "self", ",", "x", ":", "int", ",", "y", ":", "int", ",", "width", ":", "int", ",", "height", ":", "int", ",", "clear", ":", "bool", ",", "bg_blend", ":", "int", "=", "tcod", ".", "constants", ".", "BKGND_DEFAULT", ",", ")", ...
36.484848
22.757576
def ctype_for_encoding(self, encoding): """Return ctypes type for an encoded Objective-C type.""" if encoding in self.typecodes: return self.typecodes[encoding] elif encoding[0:1] == b'^' and encoding[1:] in self.typecodes: return POINTER(self.typecodes[encoding[1:]]) ...
[ "def", "ctype_for_encoding", "(", "self", ",", "encoding", ")", ":", "if", "encoding", "in", "self", ".", "typecodes", ":", "return", "self", ".", "typecodes", "[", "encoding", "]", "elif", "encoding", "[", "0", ":", "1", "]", "==", "b'^'", "and", "enc...
53
16.8125
def find_node_api_version(self, node_pyxb): """Find the highest API major version supported by node.""" max_major = 0 for s in node_pyxb.services.service: max_major = max(max_major, int(s.version[1:])) return max_major
[ "def", "find_node_api_version", "(", "self", ",", "node_pyxb", ")", ":", "max_major", "=", "0", "for", "s", "in", "node_pyxb", ".", "services", ".", "service", ":", "max_major", "=", "max", "(", "max_major", ",", "int", "(", "s", ".", "version", "[", "...
42.833333
10
def copy_security(source, target, obj_type='file', copy_owner=True, copy_group=True, copy_dacl=True, copy_sacl=True): r''' Copy the security descriptor of the Source to the Target. You can specify a s...
[ "def", "copy_security", "(", "source", ",", "target", ",", "obj_type", "=", "'file'", ",", "copy_owner", "=", "True", ",", "copy_group", "=", "True", ",", "copy_dacl", "=", "True", ",", "copy_sacl", "=", "True", ")", ":", "obj_dacl", "=", "dacl", "(", ...
35.060241
20.674699
def dup_idx(arr): """Return the indices of all duplicated array elements. Parameters ---------- arr : array-like object An array-like object Returns ------- idx : NumPy array An array containing the indices of the duplicated elements Examples -------- >>> from ...
[ "def", "dup_idx", "(", "arr", ")", ":", "_", ",", "b", "=", "np", ".", "unique", "(", "arr", ",", "return_inverse", "=", "True", ")", "return", "np", ".", "nonzero", "(", "np", ".", "logical_or", ".", "reduce", "(", "b", "[", ":", ",", "np", "....
24.107143
19.25
def tokenize(self, data, *args, **kwargs): """Invoke the lexer on an input string an return the list of tokens. This is relatively inefficient and should only be used for testing/debugging as it slurps up all tokens into one list. Args: data: The input to be tokenized. ...
[ "def", "tokenize", "(", "self", ",", "data", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "lexer", ".", "input", "(", "data", ")", "tokens", "=", "list", "(", ")", "while", "True", ":", "token", "=", "self", ".", "lexer", "...
33.588235
13.529412
def surfacemass(self,R,log=False): """ NAME: surfacemass PURPOSE: return the surface density profile at this R INPUT: R - Galactocentric radius (/ro) log - if True, return the log (default: False) OUTPUT: Sigma(R) HIS...
[ "def", "surfacemass", "(", "self", ",", "R", ",", "log", "=", "False", ")", ":", "if", "log", ":", "return", "-", "R", "/", "self", ".", "_params", "[", "0", "]", "else", ":", "return", "sc", ".", "exp", "(", "-", "R", "/", "self", ".", "_par...
26.611111
14.944444
def _setStyle(node, styleMap): u"""Sets the style attribute of a node to the dictionary ``styleMap``.""" fixedStyle = ';'.join([prop + ':' + styleMap[prop] for prop in styleMap]) if fixedStyle != '': node.setAttribute('style', fixedStyle) elif node.getAttribute('style'): node.removeAttri...
[ "def", "_setStyle", "(", "node", ",", "styleMap", ")", ":", "fixedStyle", "=", "';'", ".", "join", "(", "[", "prop", "+", "':'", "+", "styleMap", "[", "prop", "]", "for", "prop", "in", "styleMap", "]", ")", "if", "fixedStyle", "!=", "''", ":", "nod...
42.75
12.625
def _read_deref(ctx: ReaderContext) -> LispForm: """Read a derefed form from the input stream.""" start = ctx.reader.advance() assert start == "@" next_form = _read_next_consuming_comment(ctx) return llist.l(_DEREF, next_form)
[ "def", "_read_deref", "(", "ctx", ":", "ReaderContext", ")", "->", "LispForm", ":", "start", "=", "ctx", ".", "reader", ".", "advance", "(", ")", "assert", "start", "==", "\"@\"", "next_form", "=", "_read_next_consuming_comment", "(", "ctx", ")", "return", ...
40.166667
7.5
def _save(self, stateName, path): """save into 'stateName' to pyz-path""" print('saving...') state = {'session': dict(self.opts), 'dialogs': self.dialogs.saveState()} self.sigSave.emit(state) self.saveThread.prepare(stateName, path, self.tmp_dir_session...
[ "def", "_save", "(", "self", ",", "stateName", ",", "path", ")", ":", "print", "(", "'saving...'", ")", "state", "=", "{", "'session'", ":", "dict", "(", "self", ".", "opts", ")", ",", "'dialogs'", ":", "self", ".", "dialogs", ".", "saveState", "(", ...
31.047619
16.857143
def is_attacked_by(self, color: Color, square: Square) -> bool: """ Checks if the given side attacks the given square. Pinned pieces still count as attackers. Pawns that can be captured en passant are **not** considered attacked. """ return bool(self.attackers_mask(color...
[ "def", "is_attacked_by", "(", "self", ",", "color", ":", "Color", ",", "square", ":", "Square", ")", "->", "bool", ":", "return", "bool", "(", "self", ".", "attackers_mask", "(", "color", ",", "square", ")", ")" ]
40.375
17.625
def main(): """ Print lines of input along with output. """ source_lines = (line.rstrip() for line in sys.stdin) console = InteractiveInterpreter() console.runsource('import turicreate') source = '' try: while True: source = source_lines.next() more = cons...
[ "def", "main", "(", ")", ":", "source_lines", "=", "(", "line", ".", "rstrip", "(", ")", "for", "line", "in", "sys", ".", "stdin", ")", "console", "=", "InteractiveInterpreter", "(", ")", "console", ".", "runsource", "(", "'import turicreate'", ")", "sou...
30.666667
11.238095
def get_xpath(stmt, qualified=False, prefix_to_module=False): """Gets the XPath of the statement. Unless qualified=True, does not include prefixes unless the prefix changes mid-XPath. qualified will add a prefix to each node. prefix_to_module will resolve prefixes to module names instead. F...
[ "def", "get_xpath", "(", "stmt", ",", "qualified", "=", "False", ",", "prefix_to_module", "=", "False", ")", ":", "return", "mk_path_str", "(", "stmt", ",", "with_prefixes", "=", "qualified", ",", "prefix_onchange", "=", "True", ",", "prefix_to_module", "=", ...
35.285714
19.571429
def reduce(self, others): """ Reduces others into this one by concatenating all the others onto this one and returning the result. Does not modify self, instead, makes a copy and returns that. :param others: The other AudioSegment objects to append to this one. :returns: The con...
[ "def", "reduce", "(", "self", ",", "others", ")", ":", "ret", "=", "AudioSegment", "(", "self", ".", "seg", ",", "self", ".", "name", ")", "selfdata", "=", "[", "self", ".", "seg", ".", "_data", "]", "otherdata", "=", "[", "o", ".", "seg", ".", ...
38.928571
20.5
def _include_module(self, module, mn): """ See if a module should be included or excluded based upon included_packages and excluded_packages. As some packages have the following format: scipy.special.specfun scipy.linalg Where the top-level package name is just a prefi...
[ "def", "_include_module", "(", "self", ",", "module", ",", "mn", ")", ":", "if", "mn", "in", "self", ".", "topology", ".", "include_packages", ":", "_debug", ".", "debug", "(", "\"_include_module:explicit using __include_packages: module=%s\"", ",", "mn", ")", "...
45.055556
26.277778
def _height_is_big_enough(image, height): """Check that the image height is superior to `height`""" if height > image.size[1]: raise ImageSizeError(image.size[1], height)
[ "def", "_height_is_big_enough", "(", "image", ",", "height", ")", ":", "if", "height", ">", "image", ".", "size", "[", "1", "]", ":", "raise", "ImageSizeError", "(", "image", ".", "size", "[", "1", "]", ",", "height", ")" ]
45.75
5.5
def average_cq(seq, efficiency=1.0): """Given a set of Cq values, return the Cq value that represents the average expression level of the input. The intent is to average the expression levels of the samples, since the average of Cq values is not biologically meaningful. :param iterable seq: A sequ...
[ "def", "average_cq", "(", "seq", ",", "efficiency", "=", "1.0", ")", ":", "denominator", "=", "sum", "(", "[", "pow", "(", "2.0", "*", "efficiency", ",", "-", "Ci", ")", "for", "Ci", "in", "seq", "]", ")", "return", "log", "(", "len", "(", "seq",...
47.933333
22.266667
def calc_neg_log_likelihood_and_neg_gradient(self, params): """ Calculates and returns the negative of the log-likelihood and the negative of the gradient. This function is used as the objective function in scipy.optimize.minimize. """ neg_log_likelihood = -1 * self.conve...
[ "def", "calc_neg_log_likelihood_and_neg_gradient", "(", "self", ",", "params", ")", ":", "neg_log_likelihood", "=", "-", "1", "*", "self", ".", "convenience_calc_log_likelihood", "(", "params", ")", "neg_gradient", "=", "-", "1", "*", "self", ".", "convenience_cal...
42.692308
19.461538
def add_track(self, *args, **kwargs): """ Add a track to a position. Parameters ---------- track_type: string The type of track to add (e.g. "heatmap", "line") position: string One of 'top', 'bottom', 'center', 'left', 'right' tileset: hgf...
[ "def", "add_track", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "new_track", "=", "Track", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "tracks", "=", "self", ".", "tracks", "+", "[", "new_track", "]" ]
35
15.285714
def render_category(slug): """Template tag to render a category with all it's entries.""" try: category = EntryCategory.objects.get(slug=slug) except EntryCategory.DoesNotExist: pass else: return {'category': category} return {}
[ "def", "render_category", "(", "slug", ")", ":", "try", ":", "category", "=", "EntryCategory", ".", "objects", ".", "get", "(", "slug", "=", "slug", ")", "except", "EntryCategory", ".", "DoesNotExist", ":", "pass", "else", ":", "return", "{", "'category'",...
29.333333
16.888889
def get_key_params_from_user(gpg_key_param_list): """Displays parameter entry dialog and returns parameter dict Parameters ---------- gpg_key_param_list: List of 2-tuples \tContains GPG key generation parameters but not name_real """ params = [[_('Real name'), 'name_real']] vals = [...
[ "def", "get_key_params_from_user", "(", "gpg_key_param_list", ")", ":", "params", "=", "[", "[", "_", "(", "'Real name'", ")", ",", "'name_real'", "]", "]", "vals", "=", "[", "\"\"", "]", "*", "len", "(", "params", ")", "while", "\"\"", "in", "vals", "...
26.142857
22.904762
def get_monomers(self, ligands=True): """Retrieves all the `Monomers` from the AMPAL object. Parameters ---------- ligands : bool, optional If true, will include ligand `Monomers`. """ if ligands and self.ligands: monomers = self._monomers + self....
[ "def", "get_monomers", "(", "self", ",", "ligands", "=", "True", ")", ":", "if", "ligands", "and", "self", ".", "ligands", ":", "monomers", "=", "self", ".", "_monomers", "+", "self", ".", "ligands", ".", "_monomers", "else", ":", "monomers", "=", "sel...
31.307692
13.384615
def remove_tmp_prefix_from_file_path(file_path): """ Remove tmp prefix from file path or url. """ path, filename = os.path.split(file_path) return os.path.join(path, remove_tmp_prefix_from_filename(filename)).replace('\\', '/')
[ "def", "remove_tmp_prefix_from_file_path", "(", "file_path", ")", ":", "path", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "file_path", ")", "return", "os", ".", "path", ".", "join", "(", "path", ",", "remove_tmp_prefix_from_filename", "(", "...
40.333333
11.333333
def get_paths(self, key): "Like `gets`, but include the paths, like `get_path` for all matches." result_list = [] if key in self.keys(): result_list.append(((key,), self[key])) for sub_key, v in self.items(): if isinstance(v, self.__class__): sub_r...
[ "def", "get_paths", "(", "self", ",", "key", ")", ":", "result_list", "=", "[", "]", "if", "key", "in", "self", ".", "keys", "(", ")", ":", "result_list", ".", "append", "(", "(", "(", "key", ",", ")", ",", "self", "[", "key", "]", ")", ")", ...
44.214286
13.357143
async def get_pairwise(self, pairwise_filt: str = None) -> dict: """ Return dict mapping each pairwise DID of interest in wallet to its pairwise info, or, for no filter specified, mapping them all. If wallet has no such item, return empty dict. :param pairwise_filt: remote DID of intere...
[ "async", "def", "get_pairwise", "(", "self", ",", "pairwise_filt", ":", "str", "=", "None", ")", "->", "dict", ":", "LOGGER", ".", "debug", "(", "'Wallet.get_pairwise >>> pairwise_filt: %s'", ",", "pairwise_filt", ")", "if", "not", "self", ".", "handle", ":", ...
45.826087
30.869565
def _from_center_cartesian( self, x: float, y: float, z: float) -> Point: """ Specifies an arbitrary point relative to the center of the well based on percentages of the radius in each axis. For example, to specify the back-right corner of a well at 1/4 of the well depth from...
[ "def", "_from_center_cartesian", "(", "self", ",", "x", ":", "float", ",", "y", ":", "float", ",", "z", ":", "float", ")", "->", "Point", ":", "center", "=", "self", ".", "center", "(", ")", "if", "self", ".", "_shape", "is", "WellShape", ".", "REC...
41.058824
20.411765
def get_stats(self, obj, stat_name): """ Send CLI command that returns list of integer counters. :param obj: requested object. :param stat_name: statistics command name. :return: list of counters. :rtype: list(int) """ return [int(v) for v in self.send_command_re...
[ "def", "get_stats", "(", "self", ",", "obj", ",", "stat_name", ")", ":", "return", "[", "int", "(", "v", ")", "for", "v", "in", "self", ".", "send_command_return", "(", "obj", ",", "stat_name", ",", "'?'", ")", ".", "split", "(", ")", "]" ]
38.444444
13.777778
def check_object( state, index, missing_msg=None, expand_msg=None, typestr="variable" ): """Check object existence (and equality) Check whether an object is defined in the student's process, and zoom in on its value in both student and solution process to inspect quality (with has_equal_value(). I...
[ "def", "check_object", "(", "state", ",", "index", ",", "missing_msg", "=", "None", ",", "expand_msg", "=", "None", ",", "typestr", "=", "\"variable\"", ")", ":", "# Only do the assertion if PYTHONWHAT_V2_ONLY is set to '1'", "if", "v2_only", "(", ")", ":", "extra...
42.903955
33.451977
def _get_info(self, item, check_not_on_or_after=True): """ Get session information about a subject gotten from a specified IdP/AA. :param item: Information stored :return: The session information as a dictionary """ timestamp = item["timestamp"] if check_not_on_...
[ "def", "_get_info", "(", "self", ",", "item", ",", "check_not_on_or_after", "=", "True", ")", ":", "timestamp", "=", "item", "[", "\"timestamp\"", "]", "if", "check_not_on_or_after", "and", "not", "time_util", ".", "not_on_or_after", "(", "timestamp", ")", ":"...
30
18.25
def create(vm_): ''' Create a single VM from a data dict ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'nov...
[ "def", "create", "(", "vm_", ")", ":", "try", ":", "# Check for required profile parameters before sending any API calls.", "if", "vm_", "[", "'profile'", "]", "and", "config", ".", "is_profile_configured", "(", "__opts__", ",", "__active_provider_name__", "or", "'nova'...
38.076389
22.3125
def add_adjustment(self, adjustment): """ Create a new Gift Card Adjustment """ resource = self.post("adjustments", adjustment.encode()) return GiftCardAdjustment(GiftCard.format.decode(resource.body))
[ "def", "add_adjustment", "(", "self", ",", "adjustment", ")", ":", "resource", "=", "self", ".", "post", "(", "\"adjustments\"", ",", "adjustment", ".", "encode", "(", ")", ")", "return", "GiftCardAdjustment", "(", "GiftCard", ".", "format", ".", "decode", ...
39.333333
10
def print_projects(projects=None): """ Print a list of projects registered for that experiment. Args: exp: The experiment to print all projects for. """ grouped_by = {} if not projects: print( "Your selection didn't include any projects for this experiment.") ...
[ "def", "print_projects", "(", "projects", "=", "None", ")", ":", "grouped_by", "=", "{", "}", "if", "not", "projects", ":", "print", "(", "\"Your selection didn't include any projects for this experiment.\"", ")", "return", "for", "name", "in", "projects", ":", "p...
31.510638
19.510638
def getquery(query): 'Performs a query and get the results.' try: conn = connection.cursor() conn.execute(query) data = conn.fetchall() conn.close() except: data = list() return data
[ "def", "getquery", "(", "query", ")", ":", "try", ":", "conn", "=", "connection", ".", "cursor", "(", ")", "conn", ".", "execute", "(", "query", ")", "data", "=", "conn", ".", "fetchall", "(", ")", "conn", ".", "close", "(", ")", "except", ":", "...
20.666667
19.333333
def evaluateRforces(Pot,R,z,phi=None,t=0.,v=None): """ NAME: evaluateRforce PURPOSE: convenience function to evaluate a possible sum of potentials INPUT: Pot - a potential or list of potentials R - cylindrical Galactocentric distance (can be Quantity) z - distan...
[ "def", "evaluateRforces", "(", "Pot", ",", "R", ",", "z", ",", "phi", "=", "None", ",", "t", "=", "0.", ",", "v", "=", "None", ")", ":", "return", "_evaluateRforces", "(", "Pot", ",", "R", ",", "z", ",", "phi", "=", "phi", ",", "t", "=", "t",...
21.777778
29.388889
def load_data(self, *args, **kwargs): """ Collects positional and keyword arguments into `data` and applies units. :return: data """ # get positional argument names from parameters and apply them to args # update data with additional kwargs argpos = { ...
[ "def", "load_data", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# get positional argument names from parameters and apply them to args", "# update data with additional kwargs", "argpos", "=", "{", "v", "[", "'extras'", "]", "[", "'argpos'", "]",...
35.125
19.75
def set_window_geometry(geometry): """Set window geometry. Parameters ========== geometry : tuple (4 integers) or None x, y, dx, dy values employed to set the Qt backend geometry. """ if geometry is not None: x_geom, y_geom, dx_geom, dy_geom = geometry mngr = plt.get_c...
[ "def", "set_window_geometry", "(", "geometry", ")", ":", "if", "geometry", "is", "not", "None", ":", "x_geom", ",", "y_geom", ",", "dx_geom", ",", "dy_geom", "=", "geometry", "mngr", "=", "plt", ".", "get_current_fig_manager", "(", ")", "if", "'window'", "...
27.05
18.35
def _load_config(self): """Load the workflow stage config from the database.""" pb_key = SchedulingObject.get_key(PB_KEY, self._pb_id) stages = DB.get_hash_value(pb_key, 'workflow_stages') stages = ast.literal_eval(stages) return stages[self._index]
[ "def", "_load_config", "(", "self", ")", ":", "pb_key", "=", "SchedulingObject", ".", "get_key", "(", "PB_KEY", ",", "self", ".", "_pb_id", ")", "stages", "=", "DB", ".", "get_hash_value", "(", "pb_key", ",", "'workflow_stages'", ")", "stages", "=", "ast",...
47.333333
11.166667
def wr_xlsx(fout_xlsx, data_xlsx, **kws): """Write a spreadsheet into a xlsx file.""" from goatools.wr_tbl_class import WrXlsx # optional keyword args: fld2col_widths hdrs prt_if sort_by fld2fmt prt_flds items_str = kws.get("items", "items") if "items" not in kws else kws["items"] if data_xlsx: ...
[ "def", "wr_xlsx", "(", "fout_xlsx", ",", "data_xlsx", ",", "*", "*", "kws", ")", ":", "from", "goatools", ".", "wr_tbl_class", "import", "WrXlsx", "# optional keyword args: fld2col_widths hdrs prt_if sort_by fld2fmt prt_flds", "items_str", "=", "kws", ".", "get", "(",...
46.318182
17.090909
def mouserightclick(self, window_name, object_name): """ Mouse right click on an object. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, ...
[ "def", "mouserightclick", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "if", "not", "object_handle", ".", "AXEnabled", ":", "raise", "LdtpServ...
41.772727
17.227273
def topDownCompute(self, encoded): """ See the function description in base.py """ # Get/generate the topDown mapping table topDownMappingM = self._getTopDownMapping() # See which "category" we match the closest. category = topDownMappingM.rightVecProd(encoded).argmax() # Return that buck...
[ "def", "topDownCompute", "(", "self", ",", "encoded", ")", ":", "# Get/generate the topDown mapping table", "topDownMappingM", "=", "self", ".", "_getTopDownMapping", "(", ")", "# See which \"category\" we match the closest.", "category", "=", "topDownMappingM", ".", "right...
29.833333
14.833333
def collapse_initials(name): """Remove the space between initials, eg T. A. --> T.A.""" if len(name.split(".")) > 1: name = re.sub(r'([A-Z]\.)[\s\-]+(?=[A-Z]\.)', r'\1', name) return name
[ "def", "collapse_initials", "(", "name", ")", ":", "if", "len", "(", "name", ".", "split", "(", "\".\"", ")", ")", ">", "1", ":", "name", "=", "re", ".", "sub", "(", "r'([A-Z]\\.)[\\s\\-]+(?=[A-Z]\\.)'", ",", "r'\\1'", ",", "name", ")", "return", "name...
40.6
14.2
def _parse_normalizations(self, normalizations): """Returns a list of parsed normalizations. Iterates over a list of normalizations, removing those not correctly defined. It also transform complex items to have a common format (list of tuples and strings). Args: nor...
[ "def", "_parse_normalizations", "(", "self", ",", "normalizations", ")", ":", "parsed_normalizations", "=", "[", "]", "if", "isinstance", "(", "normalizations", ",", "list", ")", ":", "for", "item", "in", "normalizations", ":", "normalization", "=", "self", "....
35.666667
21.083333
def bernstein(n, t): """returns a list of the Bernstein basis polynomials b_{i, n} evaluated at t, for i =0...n""" t1 = 1-t return [n_choose_k(n, k) * t1**(n-k) * t**k for k in range(n+1)]
[ "def", "bernstein", "(", "n", ",", "t", ")", ":", "t1", "=", "1", "-", "t", "return", "[", "n_choose_k", "(", "n", ",", "k", ")", "*", "t1", "**", "(", "n", "-", "k", ")", "*", "t", "**", "k", "for", "k", "in", "range", "(", "n", "+", "...
40
15.2
def apply(): """Monkey patching rope See [1], [2], [3], [4] and [5] in module docstring.""" from spyder.utils.programs import is_module_installed if is_module_installed('rope', '<0.9.4'): import rope raise ImportError("rope %s can't be patched" % rope.VERSION) # [1] Patchi...
[ "def", "apply", "(", ")", ":", "from", "spyder", ".", "utils", ".", "programs", "import", "is_module_installed", "if", "is_module_installed", "(", "'rope'", ",", "'<0.9.4'", ")", ":", "import", "rope", "raise", "ImportError", "(", "\"rope %s can't be patched\"", ...
46.214286
19.021978
def create_box_comments(self, box_key, message, **kwargs): '''Creates a comments in a box with the provided attributes. Args: box_key key for box message message string kwargs {} see StreakComment object for more information return (status code, comment dict) ''' uri = '/'.join([ self....
[ "def", "create_box_comments", "(", "self", ",", "box_key", ",", "message", ",", "*", "*", "kwargs", ")", ":", "uri", "=", "'/'", ".", "join", "(", "[", "self", ".", "api_uri", ",", "self", ".", "boxes_suffix", ",", "box_key", ",", "self", ".", "comme...
25.259259
20.592593
def to(self, new_unit): """ Conversion to a new_unit. Right now, only supports 1 to 1 mapping of units of each type. Args: new_unit: New unit type. Returns: A FloatWithUnit object in the new units. Example usage: >>> e = Energy(1.1, "eV"...
[ "def", "to", "(", "self", ",", "new_unit", ")", ":", "return", "FloatWithUnit", "(", "self", "*", "self", ".", "unit", ".", "get_conversion_factor", "(", "new_unit", ")", ",", "unit_type", "=", "self", ".", "_unit_type", ",", "unit", "=", "new_unit", ")"...
26.285714
17.52381
def _warn_silly_options(cls, args): '''Print warnings about any options that may be silly.''' if 'page-requisites' in args.span_hosts_allow \ and not args.page_requisites: _logger.warning( _('Spanning hosts is allowed for page requisites, ' '...
[ "def", "_warn_silly_options", "(", "cls", ",", "args", ")", ":", "if", "'page-requisites'", "in", "args", ".", "span_hosts_allow", "and", "not", "args", ".", "page_requisites", ":", "_logger", ".", "warning", "(", "_", "(", "'Spanning hosts is allowed for page req...
40.8
19.52
def validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs): """Ensure the client is authorized to use the grant type requested. It will allow any of the four grant types (`authorization_code`, `password`, `client_credentials`, `refresh_tok...
[ "def", "validate_grant_type", "(", "self", ",", "client_id", ",", "grant_type", ",", "client", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_usergetter", "is", "None", "and", "grant_type", "==", "'password'", "...
39.72973
21.297297
def add_files(self, repo, files): """ Add files to the repo """ rootdir = repo.rootdir for f in files: relativepath = f['relativepath'] sourcepath = f['localfullpath'] if sourcepath is None: # This can happen if the relative pat...
[ "def", "add_files", "(", "self", ",", "repo", ",", "files", ")", ":", "rootdir", "=", "repo", ".", "rootdir", "for", "f", "in", "files", ":", "relativepath", "=", "f", "[", "'relativepath'", "]", "sourcepath", "=", "f", "[", "'localfullpath'", "]", "if...
36
11.272727
def tai(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0, jd=None): """Build a `Time` from a TAI calendar date. Supply the International Atomic Time (TAI) as a proleptic Gregorian calendar date: >>> t = ts.tai(2014, 1, 18, 1, 35, 37.5) >>> t.tai ...
[ "def", "tai", "(", "self", ",", "year", "=", "None", ",", "month", "=", "1", ",", "day", "=", "1", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0.0", ",", "jd", "=", "None", ")", ":", "if", "jd", "is", "not", "None",...
30.454545
19.545455
def median_interval(data, alpha=_alpha): """ Median including bayesian credible interval. """ q = [100*alpha/2., 50, 100*(1-alpha/2.)] lo,med,hi = np.percentile(data,q) return interval(med,lo,hi)
[ "def", "median_interval", "(", "data", ",", "alpha", "=", "_alpha", ")", ":", "q", "=", "[", "100", "*", "alpha", "/", "2.", ",", "50", ",", "100", "*", "(", "1", "-", "alpha", "/", "2.", ")", "]", "lo", ",", "med", ",", "hi", "=", "np", "....
30.428571
3.571429
def _compute(self, left_on, right_on): """Compare the data on the left and right. :meth:`BaseCompareFeature._compute` and :meth:`BaseCompareFeature.compute` differ on the accepted arguments. `_compute` accepts indexed data while `compute` accepts the record pairs and the DataFra...
[ "def", "_compute", "(", "self", ",", "left_on", ",", "right_on", ")", ":", "result", "=", "self", ".", "_compute_vectorized", "(", "*", "tuple", "(", "left_on", "+", "right_on", ")", ")", "return", "result" ]
35.24
18.48
def _updateTargetFromNode(self): """ Applies the configuration to its target axis """ if self.axisNumber == X_AXIS: xMode, yMode = self.configValue, None else: xMode, yMode = None, self.configValue self.plotItem.setLogMode(x=xMode, y=yMode)
[ "def", "_updateTargetFromNode", "(", "self", ")", ":", "if", "self", ".", "axisNumber", "==", "X_AXIS", ":", "xMode", ",", "yMode", "=", "self", ".", "configValue", ",", "None", "else", ":", "xMode", ",", "yMode", "=", "None", ",", "self", ".", "config...
33
11.777778
def draw(self, X, y, **kwargs): """Called from the fit method, this method creates a scatter plot that draws each instance as a class or target colored point, whose location is determined by the feature data set. If y is not None, then it draws a scatter plot where each class is in a ...
[ "def", "draw", "(", "self", ",", "X", ",", "y", ",", "*", "*", "kwargs", ")", ":", "nan_locs", "=", "self", ".", "get_nan_locs", "(", ")", "if", "y", "is", "None", ":", "x_", ",", "y_", "=", "list", "(", "zip", "(", "*", "nan_locs", ")", ")",...
42.785714
18.285714
def get_state_map(meta_graph, state_ops, unsupported_state_ops, get_tensor_by_name): """Returns a map from tensor names to tensors that hold the state.""" state_map = {} for node in meta_graph.graph_def.node: if node.op in state_ops: tensor_name = node.name + ":0" tensor = get_te...
[ "def", "get_state_map", "(", "meta_graph", ",", "state_ops", ",", "unsupported_state_ops", ",", "get_tensor_by_name", ")", ":", "state_map", "=", "{", "}", "for", "node", "in", "meta_graph", ".", "graph_def", ".", "node", ":", "if", "node", ".", "op", "in", ...
42.625
10.8125
def getPrice(self): """The function obtains the analysis' price without VAT and without member discount :return: the price (without VAT or Member Discount) in decimal format """ analysis_request = self.aq_parent client = analysis_request.aq_parent if client.getBul...
[ "def", "getPrice", "(", "self", ")", ":", "analysis_request", "=", "self", ".", "aq_parent", "client", "=", "analysis_request", ".", "aq_parent", "if", "client", ".", "getBulkDiscount", "(", ")", ":", "price", "=", "self", ".", "getBulkPrice", "(", ")", "e...
37.416667
11.916667
def _long_from_raw(thehash): """Fold to a long, a digest supplied as a string.""" hashnum = 0 for h in thehash: hashnum <<= 8 hashnum |= ord(bytes([h])) return hashnum
[ "def", "_long_from_raw", "(", "thehash", ")", ":", "hashnum", "=", "0", "for", "h", "in", "thehash", ":", "hashnum", "<<=", "8", "hashnum", "|=", "ord", "(", "bytes", "(", "[", "h", "]", ")", ")", "return", "hashnum" ]
27.571429
14.714286
def sys_info(fname=None, overwrite=False): """Get relevant system and debugging information Parameters ---------- fname : str | None Filename to dump info to. Use None to simply print. overwrite : bool If True, overwrite file (if it exists). Returns ------- out : str ...
[ "def", "sys_info", "(", "fname", "=", "None", ",", "overwrite", "=", "False", ")", ":", "if", "fname", "is", "not", "None", "and", "op", ".", "isfile", "(", "fname", ")", "and", "not", "overwrite", ":", "raise", "IOError", "(", "'file exists, use overwri...
37.566038
18.037736
def BBI(Series, N1, N2, N3, N4): '多空指标' bbi = (MA(Series, N1) + MA(Series, N2) + MA(Series, N3) + MA(Series, N4)) / 4 DICT = {'BBI': bbi} VAR = pd.DataFrame(DICT) return VAR
[ "def", "BBI", "(", "Series", ",", "N1", ",", "N2", ",", "N3", ",", "N4", ")", ":", "bbi", "=", "(", "MA", "(", "Series", ",", "N1", ")", "+", "MA", "(", "Series", ",", "N2", ")", "+", "MA", "(", "Series", ",", "N3", ")", "+", "MA", "(", ...
24.75
18
def update_media_assetfile(access_token, parent_asset_id, asset_id, content_length, name): '''Update Media Service Asset File. Args: access_token (str): A valid Azure authentication token. parent_asset_id (str): A Media Service Asset Parent Asset ID. asset_id (str): A Media Service Asse...
[ "def", "update_media_assetfile", "(", "access_token", ",", "parent_asset_id", ",", "asset_id", ",", "content_length", ",", "name", ")", ":", "path", "=", "'/Files'", "full_path", "=", "''", ".", "join", "(", "[", "path", ",", "\"('\"", ",", "asset_id", ",", ...
38.4
22.32
def _str2datetime(self, datetime_str): """ Parse datetime from string. If there's no template matches your string, Please go https://github.com/MacHu-GWU/rolex-project/issues submit your datetime string. I 'll update templates ASAP. This method is faster than :meth:`dat...
[ "def", "_str2datetime", "(", "self", ",", "datetime_str", ")", ":", "# try default datetime template", "try", ":", "a_datetime", "=", "datetime", ".", "strptime", "(", "datetime_str", ",", "self", ".", "_default_datetime_template", ")", "return", "a_datetime", "exce...
30.425532
18.765957
def getBaseUrl(self): '''Return a file: URL that probably points to the basedir. This is used as a halfway sane default when the base URL is not provided; not perfect, but should work in most cases.''' components = util.splitpath(os.path.abspath(self.basepath)) url = '/'.join([u...
[ "def", "getBaseUrl", "(", "self", ")", ":", "components", "=", "util", ".", "splitpath", "(", "os", ".", "path", ".", "abspath", "(", "self", ".", "basepath", ")", ")", "url", "=", "'/'", ".", "join", "(", "[", "url_quote", "(", "component", ",", "...
50.5
26
def get_alert(self, alert): """ Recieves a day as an argument and returns the prediction for that alert if is available. If not, function will return None. """ if alert > self.alerts_count() or self.alerts_count() is None: return None else: return ...
[ "def", "get_alert", "(", "self", ",", "alert", ")", ":", "if", "alert", ">", "self", ".", "alerts_count", "(", ")", "or", "self", ".", "alerts_count", "(", ")", "is", "None", ":", "return", "None", "else", ":", "return", "self", ".", "get", "(", ")...
36.777778
16.333333
def constant_compare(a, b): """ Compares two byte strings in constant time to see if they are equal :param a: The first byte string :param b: The second byte string :return: A boolean if the two byte strings are equal """ if not isinstance(a, byte_cls): ra...
[ "def", "constant_compare", "(", "a", ",", "b", ")", ":", "if", "not", "isinstance", "(", "a", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n a must be a byte string, not %s\n '''", ",", "type_name", "(", "...
20.926829
19.804878
def update(self): """ Update the content of the `iana-domains-db` file. """ if not PyFunceble.CONFIGURATION["quiet"]: # * The quiet mode is not activated. # We print on screen what we are doing. print("Update of iana-domains-db", end=" ") # ...
[ "def", "update", "(", "self", ")", ":", "if", "not", "PyFunceble", ".", "CONFIGURATION", "[", "\"quiet\"", "]", ":", "# * The quiet mode is not activated.", "# We print on screen what we are doing.", "print", "(", "\"Update of iana-domains-db\"", ",", "end", "=", "\" \"...
35.538462
21.076923
def remote_image_request(self, image_url, params=None): """ Send an image for classification. The imagewill be retrieved from the URL specified. The params parameter is optional. On success this method will immediately return a job information. Its status will initially ...
[ "def", "remote_image_request", "(", "self", ",", "image_url", ",", "params", "=", "None", ")", ":", "data", "=", "self", ".", "_init_data", "(", "params", ")", "data", "[", "'image_request[remote_image_url]'", "]", "=", "image_url", "response", "=", "requests"...
50.521739
21.73913
def prepare_working_directory(job, submission_path, validator_path): ''' Based on two downloaded files in the working directory, the student submission and the validation package, the working directory is prepared. We unpack student submission first, so that teacher files overwrite them in case...
[ "def", "prepare_working_directory", "(", "job", ",", "submission_path", ",", "validator_path", ")", ":", "# Safeguard for fail-fast in disk full scenarios on the executor", "dusage", "=", "shutil", ".", "disk_usage", "(", "job", ".", "working_dir", ")", "if", "dusage", ...
46.160494
24.975309
def get_repository_form_for_update(self, repository_id=None): """Gets the repository form for updating an existing repository. A new repository form should be requested for each update transaction. arg: repository_id (osid.id.Id): the ``Id`` of the ``Repository`` ...
[ "def", "get_repository_form_for_update", "(", "self", ",", "repository_id", "=", "None", ")", ":", "# Implemented from awsosid template for -", "# osid.resource.BinAdminSession.get_bin_form_for_update_template", "if", "not", "self", ".", "_can", "(", "'update'", ")", ":", "...
44.636364
21.409091
def _getSyntaxByFirstLine(self, firstLine): """Get syntax by first line of the file """ for pattern, xmlFileName in self._firstLineToXmlFileName.items(): if fnmatch.fnmatch(firstLine, pattern): return self._getSyntaxByXmlFileName(xmlFileName) else: ...
[ "def", "_getSyntaxByFirstLine", "(", "self", ",", "firstLine", ")", ":", "for", "pattern", ",", "xmlFileName", "in", "self", ".", "_firstLineToXmlFileName", ".", "items", "(", ")", ":", "if", "fnmatch", ".", "fnmatch", "(", "firstLine", ",", "pattern", ")", ...
44.75
14.25
def build_block(self): """ Assembles the candidate block into it's finalized form for broadcast. """ header_bytes = self.block_header.SerializeToString() block = Block(header=header_bytes, header_signature=self._header_signature) block.batches.extend...
[ "def", "build_block", "(", "self", ")", ":", "header_bytes", "=", "self", ".", "block_header", ".", "SerializeToString", "(", ")", "block", "=", "Block", "(", "header", "=", "header_bytes", ",", "header_signature", "=", "self", ".", "_header_signature", ")", ...
38.555556
13.444444
def UpdateFlow(self, client_id, flow_id, flow_obj=db.Database.unchanged, flow_state=db.Database.unchanged, client_crash_info=db.Database.unchanged, pending_termination=db.Database.unchanged, processing...
[ "def", "UpdateFlow", "(", "self", ",", "client_id", ",", "flow_id", ",", "flow_obj", "=", "db", ".", "Database", ".", "unchanged", ",", "flow_state", "=", "db", ".", "Database", ".", "unchanged", ",", "client_crash_info", "=", "db", ".", "Database", ".", ...
39.852941
14.058824
def _run_pass(self): """Read lines from a file and performs a callback against them""" while True: try: data = self._file.read(4096) except IOError, e: if e.errno == errno.ESTALE: self.active = False return F...
[ "def", "_run_pass", "(", "self", ")", ":", "while", "True", ":", "try", ":", "data", "=", "self", ".", "_file", ".", "read", "(", "4096", ")", "except", "IOError", ",", "e", ":", "if", "e", ".", "errno", "==", "errno", ".", "ESTALE", ":", "self",...
35.95
18.425
def getOutputElementCount(self, name): """ Returns the size of the output array """ if name in ["activeCells", "learnableCells", "sensoryAssociatedCells"]: return self.cellCount * self.moduleCount else: raise Exception("Invalid output name specified: " + name)
[ "def", "getOutputElementCount", "(", "self", ",", "name", ")", ":", "if", "name", "in", "[", "\"activeCells\"", ",", "\"learnableCells\"", ",", "\"sensoryAssociatedCells\"", "]", ":", "return", "self", ".", "cellCount", "*", "self", ".", "moduleCount", "else", ...
35.625
12.125
def get_default_config_help(self): """ Return help text for collector configuration. """ config_help = super(MemoryLxcCollector, self).get_default_config_help() config_help.update({ "sys_path": "Defaults to '/sys/fs/cgroup/lxc'", }) return config_help
[ "def", "get_default_config_help", "(", "self", ")", ":", "config_help", "=", "super", "(", "MemoryLxcCollector", ",", "self", ")", ".", "get_default_config_help", "(", ")", "config_help", ".", "update", "(", "{", "\"sys_path\"", ":", "\"Defaults to '/sys/fs/cgroup/l...
34.555556
14.777778