text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _ee_decode(self, msg): """EE: Entry/exit timer report.""" return {'area': int(msg[4:5])-1, 'is_exit': msg[5:6] == '0', 'timer1': int(msg[6:9]), 'timer2': int(msg[9:12]), 'armed_status': msg[12:13]}
[ "def", "_ee_decode", "(", "self", ",", "msg", ")", ":", "return", "{", "'area'", ":", "int", "(", "msg", "[", "4", ":", "5", "]", ")", "-", "1", ",", "'is_exit'", ":", "msg", "[", "5", ":", "6", "]", "==", "'0'", ",", "'timer1'", ":", "int", ...
49
0.008032
def delete_alias(self, addressid, data): """Delete alias address""" return self.api_call( ENDPOINTS['aliases']['delete'], dict(addressid=addressid), body=data)
[ "def", "delete_alias", "(", "self", ",", "addressid", ",", "data", ")", ":", "return", "self", ".", "api_call", "(", "ENDPOINTS", "[", "'aliases'", "]", "[", "'delete'", "]", ",", "dict", "(", "addressid", "=", "addressid", ")", ",", "body", "=", "data...
34.333333
0.009479
def _compile_target(self, vt): """'Compiles' a python target. 'Compiling' means forming an isolated chroot of its sources and transitive deps and then attempting to import each of the target's sources in the case of a python library or else the entry point in the case of a python binary. For a lib...
[ "def", "_compile_target", "(", "self", ",", "vt", ")", ":", "target", "=", "vt", ".", "target", "with", "self", ".", "context", ".", "new_workunit", "(", "name", "=", "target", ".", "address", ".", "spec", ")", ":", "modules", "=", "self", ".", "_get...
47.235294
0.014334
def gen_submodule_names(package): """Walk package and yield names of all submodules :type package: package :param package: The package to get submodule names of :returns: Iterator that yields names of all submodules of ``package`` :rtype: Iterator that yields ``str`` """ for importer, modn...
[ "def", "gen_submodule_names", "(", "package", ")", ":", "for", "importer", ",", "modname", ",", "ispkg", "in", "pkgutil", ".", "walk_packages", "(", "path", "=", "package", ".", "__path__", ",", "prefix", "=", "package", ".", "__name__", "+", "'.'", ",", ...
36.384615
0.002062
def _make_weirdness_regex(): """ Creates a list of regexes that match 'weird' character sequences. The more matches there are, the weirder the text is. """ groups = [] # Match diacritical marks, except when they modify a non-cased letter or # another mark. # # You wouldn't put a dia...
[ "def", "_make_weirdness_regex", "(", ")", ":", "groups", "=", "[", "]", "# Match diacritical marks, except when they modify a non-cased letter or", "# another mark.", "#", "# You wouldn't put a diacritical mark on a digit or a space, for example.", "# You might put it on a Latin letter, bu...
39.677419
0.000397
def isVisible(self, instance, mode='view', default="visible", field=None): """decide if a field is visible in a given mode -> 'state'. """ # Emulate Products.Archetypes.Widget.TypesWidget#isVisible first vis_dic = getattr(aq_base(self), 'visible', _marker) state = default if vis_dic is _marker: ...
[ "def", "isVisible", "(", "self", ",", "instance", ",", "mode", "=", "'view'", ",", "default", "=", "\"visible\"", ",", "field", "=", "None", ")", ":", "# Emulate Products.Archetypes.Widget.TypesWidget#isVisible first", "vis_dic", "=", "getattr", "(", "aq_base", "(...
38.297297
0.001376
def CB(self): ''' Vertices C and B, list. ''' try: return self._CB except AttributeError: pass self._CB = [self.C, self.B] return self._CB
[ "def", "CB", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_CB", "except", "AttributeError", ":", "pass", "self", ".", "_CB", "=", "[", "self", ".", "C", ",", "self", ".", "B", "]", "return", "self", ".", "_CB" ]
19
0.009132
def p_duration_conversion(self, p): 'duration : duration IN DURATION_UNIT' logger.debug('duration = duration %s in duration unit %s', p[1], p[3]) p[0] = '{0: {1}}'.format(p[1], p[3])
[ "def", "p_duration_conversion", "(", "self", ",", "p", ")", ":", "logger", ".", "debug", "(", "'duration = duration %s in duration unit %s'", ",", "p", "[", "1", "]", ",", "p", "[", "3", "]", ")", "p", "[", "0", "]", "=", "'{0: {1}}'", ".", "format", "...
50.75
0.009709
def fetch(self, limit, offset=0): """Not currently fully supported, but we can use this to allow them to set a limit in a chainable method""" self.limit = limit self.offset = offset return self
[ "def", "fetch", "(", "self", ",", "limit", ",", "offset", "=", "0", ")", ":", "self", ".", "limit", "=", "limit", "self", ".", "offset", "=", "offset", "return", "self" ]
38
0.008584
def encoding_for(source_path, encoding='automatic', fallback_encoding=None): """ The encoding used by the text file stored in ``source_path``. The algorithm used is: * If ``encoding`` is ``'automatic``, attempt the following: 1. Check BOM for UTF-8, UTF-16 and UTF-32. 2. Look for XML prolo...
[ "def", "encoding_for", "(", "source_path", ",", "encoding", "=", "'automatic'", ",", "fallback_encoding", "=", "None", ")", ":", "assert", "encoding", "is", "not", "None", "if", "encoding", "==", "'automatic'", ":", "with", "open", "(", "source_path", ",", "...
43.278481
0.00143
def secure_filename(filename): r"""Pass it a filename and it will return a secure version of it. This filename can then safely be stored on a regular file system and passed to :func:`os.path.join`. The filename returned is an ASCII only string for maximum portability. On windows systems the funct...
[ "def", "secure_filename", "(", "filename", ")", ":", "if", "isinstance", "(", "filename", ",", "text_type", ")", ":", "from", "unicodedata", "import", "normalize", "filename", "=", "normalize", "(", "\"NFKD\"", ",", "filename", ")", ".", "encode", "(", "\"as...
35.125
0.001154
def __extract_location_coordinates(self, image_size, color_segment): """! @brief Extracts coordinates of specified image segment. @param[in] image_size (list): Image size presented as a [width x height]. @param[in] color_segment (list): Image segment whose coordinates shoul...
[ "def", "__extract_location_coordinates", "(", "self", ",", "image_size", ",", "color_segment", ")", ":", "coordinates", "=", "[", "]", "for", "index", "in", "color_segment", ":", "y", "=", "floor", "(", "index", "/", "image_size", "[", "0", "]", ")", "x", ...
36.166667
0.020958
def reload(self, *fields, **kwargs): """Reloads all attributes from the database. :param fields: (optional) args list of fields to reload :param max_depth: (optional) depth of dereferencing to follow .. versionadded:: 0.1.2 .. versionchanged:: 0.6 Now chainable .. versio...
[ "def", "reload", "(", "self", ",", "*", "fields", ",", "*", "*", "kwargs", ")", ":", "max_depth", "=", "1", "if", "fields", "and", "isinstance", "(", "fields", "[", "0", "]", ",", "int", ")", ":", "max_depth", "=", "fields", "[", "0", "]", "field...
39.891304
0.001596
def get_organizations(self, page=None): """Get organizations""" opts = {} if page: opts['page'] = page return self.api_call(ENDPOINTS['organizations']['list'], **opts)
[ "def", "get_organizations", "(", "self", ",", "page", "=", "None", ")", ":", "opts", "=", "{", "}", "if", "page", ":", "opts", "[", "'page'", "]", "=", "page", "return", "self", ".", "api_call", "(", "ENDPOINTS", "[", "'organizations'", "]", "[", "'l...
34.333333
0.009479
def on_status_withheld(self, status_id, user_id, countries): """Called when a status is withheld""" logger.info('Status %s withheld for user %s', status_id, user_id) return True
[ "def", "on_status_withheld", "(", "self", ",", "status_id", ",", "user_id", ",", "countries", ")", ":", "logger", ".", "info", "(", "'Status %s withheld for user %s'", ",", "status_id", ",", "user_id", ")", "return", "True" ]
49.5
0.00995
def parse(inp, format=None, encoding='utf-8', force_types=True): """Parse input from file-like object, unicode string or byte string. Args: inp: file-like object, unicode string or byte string with the markup format: explicitly override the guessed `inp` markup format encoding: `inp` en...
[ "def", "parse", "(", "inp", ",", "format", "=", "None", ",", "encoding", "=", "'utf-8'", ",", "force_types", "=", "True", ")", ":", "proper_inp", "=", "inp", "if", "hasattr", "(", "inp", ",", "'read'", ")", ":", "proper_inp", "=", "inp", ".", "read",...
35.690476
0.001299
def _build_state_value(request_handler, user): """Composes the value for the 'state' parameter. Packs the current request URI and an XSRF token into an opaque string that can be passed to the authentication server via the 'state' parameter. Args: request_handler: webapp.RequestHandler, The req...
[ "def", "_build_state_value", "(", "request_handler", ",", "user", ")", ":", "uri", "=", "request_handler", ".", "request", ".", "url", "token", "=", "xsrfutil", ".", "generate_token", "(", "xsrf_secret_key", "(", ")", ",", "user", ".", "user_id", "(", ")", ...
36.882353
0.001555
def Kweq_1981(T, rho_w): r'''Calculates equilibrium constant for OH- and H+ in water, according to [1]_. Second most recent formulation. .. math:: \log_{10} K_w= A + B/T + C/T^2 + D/T^3 + (E+F/T+G/T^2)\log_{10} \rho_w Parameters ---------- T : float Temperature of fluid [K] ...
[ "def", "Kweq_1981", "(", "T", ",", "rho_w", ")", ":", "rho_w", "=", "rho_w", "/", "1000.", "A", "=", "-", "4.098", "B", "=", "-", "3245.2", "C", "=", "2.2362E5", "D", "=", "-", "3.984E7", "E", "=", "13.957", "F", "=", "-", "1262.3", "G", "=", ...
23.807692
0.001552
def get_residual_load_from_pypsa_network(pypsa_network): """ Calculates residual load in MW in MV grid and underlying LV grids. Parameters ---------- pypsa_network : :pypsa:`pypsa.Network<network>` The `PyPSA network <https://www.pypsa.org/doc/components.html#network>`_ container, ...
[ "def", "get_residual_load_from_pypsa_network", "(", "pypsa_network", ")", ":", "residual_load", "=", "pypsa_network", ".", "loads_t", ".", "p_set", ".", "sum", "(", "axis", "=", "1", ")", "-", "(", "pypsa_network", ".", "generators_t", ".", "p_set", ".", "loc"...
36.653846
0.002045
def _change_splitlevel(self, ttype, value): """Get the new split level (increase, decrease or remain equal)""" # parenthesis increase/decrease a level if ttype is T.Punctuation and value == '(': return 1 elif ttype is T.Punctuation and value == ')': return -1 ...
[ "def", "_change_splitlevel", "(", "self", ",", "ttype", ",", "value", ")", ":", "# parenthesis increase/decrease a level", "if", "ttype", "is", "T", ".", "Punctuation", "and", "value", "==", "'('", ":", "return", "1", "elif", "ttype", "is", "T", ".", "Punctu...
35.27451
0.001622
def _connect(self): "Create a Unix domain socket connection" sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.settimeout(self.socket_timeout) sock.connect(self.path) return sock
[ "def", "_connect", "(", "self", ")", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_UNIX", ",", "socket", ".", "SOCK_STREAM", ")", "sock", ".", "settimeout", "(", "self", ".", "socket_timeout", ")", "sock", ".", "connect", "(", "sel...
37.5
0.008696
def propagate(self, assumptions=[], phase_saving=0): """ Propagate a given set of assumption literals. """ if self.maplesat: if self.use_timer: start_time = time.clock() # saving default SIGINT handler def_sigint_handler = signal...
[ "def", "propagate", "(", "self", ",", "assumptions", "=", "[", "]", ",", "phase_saving", "=", "0", ")", ":", "if", "self", ".", "maplesat", ":", "if", "self", ".", "use_timer", ":", "start_time", "=", "time", ".", "clock", "(", ")", "# saving default S...
34.909091
0.008872
def newStruct(field_name_list): """ Create a ctype structure class based on USB standard field naming (type-prefixed). """ field_list = [] append = field_list.append for field in field_name_list: type_prefix = '' for char in field: if not char.islower(): ...
[ "def", "newStruct", "(", "field_name_list", ")", ":", "field_list", "=", "[", "]", "append", "=", "field_list", ".", "append", "for", "field", "in", "field_name_list", ":", "type_prefix", "=", "''", "for", "char", "in", "field", ":", "if", "not", "char", ...
33.833333
0.001198
def lint(relative_path_to_file, contents, linter_functions, **kwargs): r"""Actually lints some file contents. relative_path_to_file should contain the relative path to the file being linted from the root source directory. Contents should be a raw string with \n's. """ ...
[ "def", "lint", "(", "relative_path_to_file", ",", "contents", ",", "linter_functions", ",", "*", "*", "kwargs", ")", ":", "lines", "=", "contents", ".", "splitlines", "(", "True", ")", "errors", "=", "list", "(", ")", "for", "(", "code", ",", "info", "...
34
0.001244
def encode(self, word, max_length=4, zero_pad=True): """Return the Phonex code for a word. Parameters ---------- word : str The word to transform max_length : int The length of the code returned (defaults to 4) zero_pad : bool Pad the ...
[ "def", "encode", "(", "self", ",", "word", ",", "max_length", "=", "4", ",", "zero_pad", "=", "True", ")", ":", "name", "=", "unicode_normalize", "(", "'NFKD'", ",", "text_type", "(", "word", ".", "upper", "(", ")", ")", ")", "name", "=", "name", "...
30.601695
0.001878
def parse_gc_content(self): """parses and plots GC content and genome GC content files""" # Find and parse GC content: for f in self.find_log_files('homer/GCcontent', filehandles=True): # Get the s_name from the parent directory s_name = os.path.basename(f['root']) ...
[ "def", "parse_gc_content", "(", "self", ")", ":", "# Find and parse GC content:", "for", "f", "in", "self", ".", "find_log_files", "(", "'homer/GCcontent'", ",", "filehandles", "=", "True", ")", ":", "# Get the s_name from the parent directory", "s_name", "=", "os", ...
51
0.010753
def headers_to_include_from_request(curr_request): ''' Define headers that needs to be included from the current request. ''' return { h: v for h, v in curr_request.META.items() if h in _settings.HEADERS_TO_INCLUDE}
[ "def", "headers_to_include_from_request", "(", "curr_request", ")", ":", "return", "{", "h", ":", "v", "for", "h", ",", "v", "in", "curr_request", ".", "META", ".", "items", "(", ")", "if", "h", "in", "_settings", ".", "HEADERS_TO_INCLUDE", "}" ]
39.666667
0.00823
def zero_state(self, batch_size): """ Initial state of the network """ return torch.zeros(batch_size, self.state_dim, dtype=torch.float32)
[ "def", "zero_state", "(", "self", ",", "batch_size", ")", ":", "return", "torch", ".", "zeros", "(", "batch_size", ",", "self", ".", "state_dim", ",", "dtype", "=", "torch", ".", "float32", ")" ]
50.666667
0.012987
def adjust_fit(dst_w, dst_h, img_w, img_h): """ given a x and y of dest, determine the ratio and return an (x,y,w,h) for a fitted image (note x or y could be neg). >>> adjust_fit(4,3,5,5) (0.5, 0, 3.0, 3.0) >>> adjust_fit(8,6,5,5) (1.0, 0, 6.0, 6.0) >>> adjust_fit(4,3,5,2) (0, 0.6999...
[ "def", "adjust_fit", "(", "dst_w", ",", "dst_h", ",", "img_w", ",", "img_h", ")", ":", "dst_w", "=", "float", "(", "dst_w", ")", "dst_h", "=", "float", "(", "dst_h", ")", "img_w", "=", "float", "(", "img_w", ")", "img_h", "=", "float", "(", "img_h"...
25.685714
0.001072
def set_key_callback(window, cbfun): """ Sets the key callback. Wrapper for: GLFWkeyfun glfwSetKeyCallback(GLFWwindow* window, GLFWkeyfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_a...
[ "def", "set_key_callback", "(", "window", ",", "cbfun", ")", ":", "window_addr", "=", "ctypes", ".", "cast", "(", "ctypes", ".", "pointer", "(", "window", ")", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_long", ")", ")", ".", "contents", ".",...
35.380952
0.001311
def set_cursor(self, value): """Changes the grid cursor cell. Parameters ---------- value: 2-tuple or 3-tuple of String \trow, col, tab or row, col for target cursor position """ shape = self.grid.code_array.shape if len(value) == 3: self....
[ "def", "set_cursor", "(", "self", ",", "value", ")", ":", "shape", "=", "self", ".", "grid", ".", "code_array", ".", "shape", "if", "len", "(", "value", ")", "==", "3", ":", "self", ".", "grid", ".", "_last_selected_cell", "=", "row", ",", "col", "...
36.25
0.002015
def _wait_ready(self, timeout_sec=1): """Wait until the PN532 is ready to receive commands. At most wait timeout_sec seconds for the PN532 to be ready. If the PN532 is ready before the timeout is exceeded then True will be returned, otherwise False is returned when the timeout is excee...
[ "def", "_wait_ready", "(", "self", ",", "timeout_sec", "=", "1", ")", ":", "start", "=", "time", ".", "time", "(", ")", "# Send a SPI status read command and read response.", "self", ".", "_gpio", ".", "set_low", "(", "self", ".", "_cs", ")", "self", ".", ...
46.125
0.00177
def get_plugin_actions(self): """Return a list of actions related to plugin.""" create_client_action = create_action( self, _("New console (default settings)"), icon=ima.icon('ipython_console'),...
[ "def", "get_plugin_actions", "(", "self", ")", ":", "create_client_action", "=", "create_action", "(", "self", ",", "_", "(", "\"New console (default settings)\"", ")", ",", "icon", "=", "ima", ".", "icon", "(", "'ipython_console'", ")", ",", "triggered", "=", ...
51.4
0.001485
def _checkCanIndex(self): ''' _checkCanIndex - Check if we CAN index (if all fields are indexable). Also checks the right-most field for "hashIndex" - if it needs to hash we will hash. ''' # NOTE: We can't just check the right-most field. For types like pickle that don't support indexing, they don't # ...
[ "def", "_checkCanIndex", "(", "self", ")", ":", "# NOTE: We can't just check the right-most field. For types like pickle that don't support indexing, they don't", "# support it because python2 and python3 have different results for pickle.dumps on the same object.", "# So if we have a field chai...
42.176471
0.025921
def _order_antisense_column(cov_file, min_reads): """ Move counts to score columns in bed file """ new_cov = op.join(op.dirname(cov_file), 'feat_antisense.txt') with open(cov_file) as in_handle: with open(new_cov, 'w') as out_handle: print("name\tantisense", file=out_handle, end=...
[ "def", "_order_antisense_column", "(", "cov_file", ",", "min_reads", ")", ":", "new_cov", "=", "op", ".", "join", "(", "op", ".", "dirname", "(", "cov_file", ")", ",", "'feat_antisense.txt'", ")", "with", "open", "(", "cov_file", ")", "as", "in_handle", ":...
42.692308
0.001764
def _get_f2rx(self, C, r_x, r_1, r_2): """ Defines the f2 scaling coefficient defined in equation 10 """ drx = (r_x - r_1) / (r_2 - r_1) return self.CONSTS["h4"] + (C["h5"] * drx) + (C["h6"] * (drx ** 2.))
[ "def", "_get_f2rx", "(", "self", ",", "C", ",", "r_x", ",", "r_1", ",", "r_2", ")", ":", "drx", "=", "(", "r_x", "-", "r_1", ")", "/", "(", "r_2", "-", "r_1", ")", "return", "self", ".", "CONSTS", "[", "\"h4\"", "]", "+", "(", "C", "[", "\"...
40
0.008163
def apply_givens(Q, v, k): """Apply the first k Givens rotations in Q to v. Parameters ---------- Q : list list of consecutive 2x2 Givens rotations v : array vector to apply the rotations to k : int number of rotations to apply. Returns ------- v is changed ...
[ "def", "apply_givens", "(", "Q", ",", "v", ",", "k", ")", ":", "for", "j", "in", "range", "(", "k", ")", ":", "Qloc", "=", "Q", "[", "j", "]", "v", "[", "j", ":", "j", "+", "2", "]", "=", "np", ".", "dot", "(", "Qloc", ",", "v", "[", ...
22.769231
0.001621
def flush(bank, key=None): ''' Remove the key from the cache bank with all the key content. ''' if key is None: c_key = bank else: c_key = '{0}/{1}'.format(bank, key) try: return api.kv.delete(c_key, recurse=key is None) except Exception as exc: raise SaltCach...
[ "def", "flush", "(", "bank", ",", "key", "=", "None", ")", ":", "if", "key", "is", "None", ":", "c_key", "=", "bank", "else", ":", "c_key", "=", "'{0}/{1}'", ".", "format", "(", "bank", ",", "key", ")", "try", ":", "return", "api", ".", "kv", "...
26.9375
0.002242
def add_wrapper_regex(opts_dict): """ Adds the regular expression for the specified wrapper to opts_dict. It is assumed the dictionary has the keys 'open' and 'close' The regular expression will match the following, in order: 1. The wrapper 'open' pattern 2. Followed by any amount of white spa...
[ "def", "add_wrapper_regex", "(", "opts_dict", ")", ":", "opn", "=", "re", ".", "escape", "(", "opts_dict", "[", "'open'", "]", ")", "close", "=", "re", ".", "escape", "(", "opts_dict", "[", "'close'", "]", ")", "p", "=", "opn", "# The opening pattern", ...
36.485714
0.002288
def set_path(self, path): '''Sets the listitem's path''' self._path = path return self._listitem.setPath(path)
[ "def", "set_path", "(", "self", ",", "path", ")", ":", "self", ".", "_path", "=", "path", "return", "self", ".", "_listitem", ".", "setPath", "(", "path", ")" ]
32.75
0.014925
def getDisplayName(self): """Provides a name for display purpose respecting the alias""" if self.alias == "": return self.name return self.name + " as " + self.alias
[ "def", "getDisplayName", "(", "self", ")", ":", "if", "self", ".", "alias", "==", "\"\"", ":", "return", "self", ".", "name", "return", "self", ".", "name", "+", "\" as \"", "+", "self", ".", "alias" ]
39.4
0.00995
def get_policies_by_id(profile_manager, policy_ids): ''' Returns a list of policies with the specified ids. profile_manager Reference to the profile manager. policy_ids List of policy ids to retrieve. ''' try: return profile_manager.RetrieveContent(policy_ids) excep...
[ "def", "get_policies_by_id", "(", "profile_manager", ",", "policy_ids", ")", ":", "try", ":", "return", "profile_manager", ".", "RetrieveContent", "(", "policy_ids", ")", "except", "vim", ".", "fault", ".", "NoPermission", "as", "exc", ":", "log", ".", "except...
32
0.001379
def _key_from_filepath(self, filename, klass, password): """ Attempt to derive a `.PKey` from given string path ``filename``: - If ``filename`` appears to be a cert, the matching private key is loaded. - Otherwise, the filename is assumed to be a private key, and the ...
[ "def", "_key_from_filepath", "(", "self", ",", "filename", ",", "klass", ",", "password", ")", ":", "cert_suffix", "=", "\"-cert.pub\"", "# Assume privkey, not cert, by default", "if", "filename", ".", "endswith", "(", "cert_suffix", ")", ":", "key_path", "=", "fi...
44.193548
0.001429
def read_firmware_file(file_path): """ Reads a firmware file into a dequeue for processing. :param file_path: Path to the firmware file :type file_path: string :returns: deque """ data_queue = deque() with open(file_path) as firmware_handle: for line in firmware_handle: ...
[ "def", "read_firmware_file", "(", "file_path", ")", ":", "data_queue", "=", "deque", "(", ")", "with", "open", "(", "file_path", ")", "as", "firmware_handle", ":", "for", "line", "in", "firmware_handle", ":", "line", "=", "line", ".", "rstrip", "(", ")", ...
24.722222
0.002165
def add_field(self, key, field): """Add a field to the Payload. :API: public :param string key: The key for the field. Fields can be accessed using attribute access as well as `get_field` using `key`. :param PayloadField field: A PayloadField instance. None is an allowable value for `field`,...
[ "def", "add_field", "(", "self", ",", "key", ",", "field", ")", ":", "if", "key", "in", "self", ".", "_fields", ":", "raise", "PayloadFieldAlreadyDefinedError", "(", "'Key {key} is already set on this payload. The existing field was {existing_field}.'", "' Tried to set new ...
39.818182
0.008919
def getScoringVector(self, profile): """ Returns the scoring vector [m-1,m-2,m-3,...,0] where m is the number of candidates in the election profile. This function is called by getCandScoresMap() which is implemented in the parent class. :ivar Profile profile: A Profile object th...
[ "def", "getScoringVector", "(", "self", ",", "profile", ")", ":", "scoringVector", "=", "[", "]", "score", "=", "profile", ".", "numCands", "-", "1", "for", "i", "in", "range", "(", "0", ",", "profile", ".", "numCands", ")", ":", "scoringVector", ".", ...
36.933333
0.008803
def _tta_only(learn:Learner, ds_type:DatasetType=DatasetType.Valid, scale:float=1.35) -> Iterator[List[Tensor]]: "Computes the outputs for several augmented inputs for TTA" dl = learn.dl(ds_type) ds = dl.dataset old = ds.tfms augm_tfm = [o for o in learn.data.train_ds.tfms if o.tfm not in ...
[ "def", "_tta_only", "(", "learn", ":", "Learner", ",", "ds_type", ":", "DatasetType", "=", "DatasetType", ".", "Valid", ",", "scale", ":", "float", "=", "1.35", ")", "->", "Iterator", "[", "List", "[", "Tensor", "]", "]", ":", "dl", "=", "learn", "."...
44.052632
0.022222
def leaky_relu(attrs, inputs, proto_obj): """Leaky Relu function""" if 'alpha' in attrs: new_attrs = translation_utils._fix_attribute_names(attrs, {'alpha' : 'slope'}) else: new_attrs = translation_utils._add_extra_attributes(attrs, {'slope': 0.01}) return 'LeakyReLU', new_attrs, inputs
[ "def", "leaky_relu", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "if", "'alpha'", "in", "attrs", ":", "new_attrs", "=", "translation_utils", ".", "_fix_attribute_names", "(", "attrs", ",", "{", "'alpha'", ":", "'slope'", "}", ")", "else", ":",...
44.714286
0.012539
def set_cpu_affinity(n, process_ids, actual=not Conf.TESTING): """ Sets the cpu affinity for the supplied processes. Requires the optional psutil module. :param int n: affinity :param list process_ids: a list of pids :param bool actual: Test workaround for Travis not supporting cpu affinity ...
[ "def", "set_cpu_affinity", "(", "n", ",", "process_ids", ",", "actual", "=", "not", "Conf", ".", "TESTING", ")", ":", "# check if we have the psutil module", "if", "not", "psutil", ":", "logger", ".", "warning", "(", "'Skipping cpu affinity because psutil was not foun...
39.028571
0.001429
def _method_scope(input_layer, name): """Creates a nested set of name and id scopes and avoids repeats.""" global _in_method_scope # pylint: disable=protected-access with input_layer.g.as_default(), \ scopes.var_and_name_scope( None if _in_method_scope else input_layer._scope), \ scope...
[ "def", "_method_scope", "(", "input_layer", ",", "name", ")", ":", "global", "_in_method_scope", "# pylint: disable=protected-access", "with", "input_layer", ".", "g", ".", "as_default", "(", ")", ",", "scopes", ".", "var_and_name_scope", "(", "None", "if", "_in_m...
39.916667
0.010204
def blocks_from_ops(ops): """ Group a list of :class:`Op` and :class:`Label` instances by label. Everytime a label is found, a new :class:`Block` is created. The resulting blocks are returned as a dictionary to easily access the target block of a jump operation. The keys of this dictionary will be ...
[ "def", "blocks_from_ops", "(", "ops", ")", ":", "blocks", "=", "{", "}", "current_block", "=", "blocks", "[", "None", "]", "=", "Block", "(", ")", "for", "op", "in", "ops", ":", "if", "isinstance", "(", "op", ",", "Label", ")", ":", "next_block", "...
35.392857
0.000982
def example_df(): """Create an example dataframe.""" country_names = ['Germany', 'France', 'Indonesia', 'Ireland', 'Spain', 'Vatican'] population = [82521653, 66991000, 255461700, 4761865, 46549045, None...
[ "def", "example_df", "(", ")", ":", "country_names", "=", "[", "'Germany'", ",", "'France'", ",", "'Indonesia'", ",", "'Ireland'", ",", "'Spain'", ",", "'Vatican'", "]", "population", "=", "[", "82521653", ",", "66991000", ",", "255461700", ",", "4761865", ...
39.869565
0.001065
def states(): """ Get a dictionary of Backpage city names mapped to their respective states. Returns: dictionary of Backpage city names mapped to their states """ states = {} fname = pkg_resources.resource_filename(__name__, 'resources/City_State_Pairs.csv') with open(fname, 'rU') as csvfile: rea...
[ "def", "states", "(", ")", ":", "states", "=", "{", "}", "fname", "=", "pkg_resources", ".", "resource_filename", "(", "__name__", ",", "'resources/City_State_Pairs.csv'", ")", "with", "open", "(", "fname", ",", "'rU'", ")", "as", "csvfile", ":", "reader", ...
27.866667
0.023148
def is_text_file(filepath, blocksize=2**14): """ Uses heuristics to guess whether the given file is text or binary, by reading a single block of bytes from the file. If more than some abound of the chars in the block are non-text, or there are NUL ('\x00') bytes in the block, assume this...
[ "def", "is_text_file", "(", "filepath", ",", "blocksize", "=", "2", "**", "14", ")", ":", "with", "open", "(", "filepath", ",", "\"rb\"", ")", "as", "fileobj", ":", "block", "=", "fileobj", ".", "read", "(", "blocksize", ")", "if", "b'\\x00'", "in", ...
46.315789
0.002227
def rpc_get_all_names( self, offset, count, **con_info ): """ Get all unexpired names, paginated Return {'status': true, 'names': [...]} on success Return {'error': ...} on error """ if not check_offset(offset): return {'error': 'invalid offset', 'http_status'...
[ "def", "rpc_get_all_names", "(", "self", ",", "offset", ",", "count", ",", "*", "*", "con_info", ")", ":", "if", "not", "check_offset", "(", "offset", ")", ":", "return", "{", "'error'", ":", "'invalid offset'", ",", "'http_status'", ":", "400", "}", "if...
34.714286
0.013351
def get(self, request, *args, **kwargs): """ Return a :class:`.django.http.JsonResponse`. Example:: { 'results': [ { 'text': "foo", 'id': 123 } ], ...
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "widget", "=", "self", ".", "get_widget_or_404", "(", ")", "self", ".", "term", "=", "kwargs", ".", "get", "(", "'term'", ",", "request", ...
27.612903
0.002257
def get(self, name: str, default: np.ndarray) -> np.ndarray: """ Return the value for a named attribute if it exists, else default. Default has to be a numpy array of correct size. """ if name in self: return self[name] else: if not isinstance(default, np.ndarray): raise ValueError(f"Default must...
[ "def", "get", "(", "self", ",", "name", ":", "str", ",", "default", ":", "np", ".", "ndarray", ")", "->", "np", ".", "ndarray", ":", "if", "name", "in", "self", ":", "return", "self", "[", "name", "]", "else", ":", "if", "not", "isinstance", "(",...
35.9375
0.027119
def read_element_tag(fd, endian): """Read data element tag: type and number of bytes. If tag is of the Small Data Element (SDE) type the element data is also returned. """ data = fd.read(8) mtpn = unpack(endian, 'I', data[:4]) # The most significant two bytes of mtpn will always be 0, # ...
[ "def", "read_element_tag", "(", "fd", ",", "endian", ")", ":", "data", "=", "fd", ".", "read", "(", "8", ")", "mtpn", "=", "unpack", "(", "endian", ",", "'I'", ",", "data", "[", ":", "4", "]", ")", "# The most significant two bytes of mtpn will always be 0...
35.227273
0.001256
def _referer(self, extension): """ Return the referer for the given extension. :param extension: A valid domain extension. :type extension: str :return: The whois server to use to get the WHOIS record. :rtype: str """ # We get the a copy of the page. ...
[ "def", "_referer", "(", "self", ",", "extension", ")", ":", "# We get the a copy of the page.", "iana_record", "=", "self", ".", "lookup", ".", "whois", "(", "PyFunceble", ".", "CONFIGURATION", "[", "\"iana_whois_server\"", "]", ",", "\"hello.%s\"", "%", "extensio...
30.717391
0.002058
def dragend(self, event): """ Handles the end of a drag action. """ x_range = [self.begin_drag.x//self.col_width, event.x//self.col_width] y_range = [self.begin_drag.y//self.row_height, event.y//self.row_height] # Check bounds for i in range(2)...
[ "def", "dragend", "(", "self", ",", "event", ")", ":", "x_range", "=", "[", "self", ".", "begin_drag", ".", "x", "//", "self", ".", "col_width", ",", "event", ".", "x", "//", "self", ".", "col_width", "]", "y_range", "=", "[", "self", ".", "begin_d...
35.84
0.002174
def revoke_handler(self, f): """Access/refresh token revoke decorator. Any return value by the decorated function will get discarded as defined in [`RFC7009`_]. You can control the access method with the standard flask routing mechanism, as per [`RFC7009`_] it is recommended to...
[ "def", "revoke_handler", "(", "self", ",", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "server", "=", "self", ".", "server", "token", "=", "request", ".", "values", ".", "ge...
34.806452
0.001803
def _find_sub_controllers(self, remainder, request): ''' Identifies the correct controller to route to by analyzing the request URI. ''' # need either a get_one or get to parse args method = None for name in ('get_one', 'get'): if hasattr(self, name): ...
[ "def", "_find_sub_controllers", "(", "self", ",", "remainder", ",", "request", ")", ":", "# need either a get_one or get to parse args", "method", "=", "None", "for", "name", "in", "(", "'get_one'", ",", "'get'", ")", ":", "if", "hasattr", "(", "self", ",", "n...
38.5
0.001267
def branch_length_to_years(self): ''' This function sets branch length to reflect the date differences between parent and child nodes measured in years. Should only be called after :py:meth:`timetree.ClockTree.convert_dates` has been called. Returns ------- None ...
[ "def", "branch_length_to_years", "(", "self", ")", ":", "self", ".", "logger", "(", "'ClockTree.branch_length_to_years: setting node positions in units of years'", ",", "2", ")", "if", "not", "hasattr", "(", "self", ".", "tree", ".", "root", ",", "'numdate'", ")", ...
44.944444
0.008475
def diff_array(self, features, force=True, func=None, array_kwargs=dict(), cache=None): """ Scales the control and IP data to million mapped reads, then subtracts scaled control from scaled IP, applies `func(diffed)` to the diffed array, and finally sets `self.diffed_a...
[ "def", "diff_array", "(", "self", ",", "features", ",", "force", "=", "True", ",", "func", "=", "None", ",", "array_kwargs", "=", "dict", "(", ")", ",", "cache", "=", "None", ")", ":", "self", ".", "features", "=", "list", "(", "features", ")", "se...
47.888889
0.001819
def packageProject(self, dir=os.getcwd(), configuration='Shipping', extraArgs=[]): """ Packages a build of the Unreal project in the specified directory, using common packaging options """ # Verify that the specified build configuration is valid if configuration not in self.validBuildConfigurations(): r...
[ "def", "packageProject", "(", "self", ",", "dir", "=", "os", ".", "getcwd", "(", ")", ",", "configuration", "=", "'Shipping'", ",", "extraArgs", "=", "[", "]", ")", ":", "# Verify that the specified build configuration is valid", "if", "configuration", "not", "i...
40.704545
0.033261
def get_ns_command(self, cmd_name): """ Retrieves the name space and the command associated to the given command name. :param cmd_name: The given command name :return: A 2-tuple (name space, command) :raise ValueError: Unknown command name """ namespace, ...
[ "def", "get_ns_command", "(", "self", ",", "cmd_name", ")", ":", "namespace", ",", "command", "=", "_split_ns_command", "(", "cmd_name", ")", "if", "not", "namespace", ":", "# Name space not given, look for the command", "spaces", "=", "self", ".", "__find_command_n...
36.2
0.001537
def unflatten_list(flat_dict, separator='_'): """ Unflattens a dictionary, first assuming no lists exist and then tries to identify lists and replaces them This is probably not very efficient and has not been tested extensively Feel free to add test cases or rewrite the logic Issues that stand o...
[ "def", "unflatten_list", "(", "flat_dict", ",", "separator", "=", "'_'", ")", ":", "_unflatten_asserts", "(", "flat_dict", ",", "separator", ")", "# First unflatten the dictionary assuming no lists exist", "unflattened_dict", "=", "unflatten", "(", "flat_dict", ",", "se...
44.44898
0.000449
def prepare_new_dataset(): """prepare_new_dataset Prepare a new ``MLPrepare`` record and dataset files on disk. """ parser = argparse.ArgumentParser( description=( "Python client to Prepare a dataset")) parser.add_argument( "-u", help="username", requir...
[ "def", "prepare_new_dataset", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "(", "\"Python client to Prepare a dataset\"", ")", ")", "parser", ".", "add_argument", "(", "\"-u\"", ",", "help", "=", "\"username\"", ",", ...
26.394531
0.000143
def download_url(url:str, dest:str, overwrite:bool=False, pbar:ProgressBar=None, show_progress=True, chunk_size=1024*1024, timeout=4, retries=5)->None: "Download `url` to `dest` unless it exists and not `overwrite`." if os.path.exists(dest) and not overwrite: return s = requests.Session() ...
[ "def", "download_url", "(", "url", ":", "str", ",", "dest", ":", "str", ",", "overwrite", ":", "bool", "=", "False", ",", "pbar", ":", "ProgressBar", "=", "None", ",", "show_progress", "=", "True", ",", "chunk_size", "=", "1024", "*", "1024", ",", "t...
48.21875
0.015883
def _extract_packages(self): """ Extract a package in a new directory. """ if not hasattr(self, "retrieved_packages_unpacked"): self.retrieved_packages_unpacked = [self.package_name] for path in self.retrieved_packages_unpacked: package_name = basename(pat...
[ "def", "_extract_packages", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"retrieved_packages_unpacked\"", ")", ":", "self", ".", "retrieved_packages_unpacked", "=", "[", "self", ".", "package_name", "]", "for", "path", "in", "self", ".", ...
47.586207
0.002131
def parse_error(self, exception=ParseError, *args): """ Creates a generic "parse error" at the current position. """ return self._src.parse_error(exception, *args)
[ "def", "parse_error", "(", "self", ",", "exception", "=", "ParseError", ",", "*", "args", ")", ":", "return", "self", ".", "_src", ".", "parse_error", "(", "exception", ",", "*", "args", ")" ]
38.2
0.010256
def aot40_vegetation(df, nb_an): """ Calcul de l'AOT40 du 1er mai au 31 juillet *AOT40 : AOT 40 ( exprimé en micro g/m³ par heure ) signifie la somme des différences entre les concentrations horaires supérieures à 40 parties par milliard ( 40 ppb soit 80 micro g/m³ ), durant une période donnée en ...
[ "def", "aot40_vegetation", "(", "df", ",", "nb_an", ")", ":", "return", "_aot", "(", "df", ".", "tshift", "(", "1", ")", ",", "nb_an", "=", "nb_an", ",", "limite", "=", "80", ",", "mois_debut", "=", "5", ",", "mois_fin", "=", "7", ",", "heure_debut...
40.652174
0.00209
def add_relation(self, relation): """ Parameters ---------- relation : etree.Element etree representation of a <relation> element A <relation> always has a type attribute and inherits its ID from its parent element. In the case of a non-expletive ...
[ "def", "add_relation", "(", "self", ",", "relation", ")", ":", "if", "self", ".", "ignore_relations", "is", "False", ":", "parent_node_id", "=", "self", ".", "get_parent_id", "(", "relation", ")", "reltype", "=", "relation", ".", "attrib", "[", "'type'", "...
42.913043
0.000991
def apply_handler_to_root_log(handler: logging.Handler, remove_existing: bool = False) -> None: """ Applies a handler to all logs, optionally removing existing handlers. Should ONLY be called from the ``if __name__ == 'main'`` script; see https://docs.python.org/3.4/howto/...
[ "def", "apply_handler_to_root_log", "(", "handler", ":", "logging", ".", "Handler", ",", "remove_existing", ":", "bool", "=", "False", ")", "->", "None", ":", "rootlog", "=", "logging", ".", "getLogger", "(", ")", "if", "remove_existing", ":", "rootlog", "."...
36.111111
0.001499
def parse_coordinate(string_rep, unit): """ Parse a single coordinate """ # explicit radian ('r') value if string_rep[-1] == 'r': return coordinates.Angle(string_rep[:-1], unit=u.rad) # explicit image ('i') and physical ('p') pixels elif string_rep[-1]...
[ "def", "parse_coordinate", "(", "string_rep", ",", "unit", ")", ":", "# explicit radian ('r') value", "if", "string_rep", "[", "-", "1", "]", "==", "'r'", ":", "return", "coordinates", ".", "Angle", "(", "string_rep", "[", ":", "-", "1", "]", ",", "unit", ...
43.193548
0.001461
def rm_alias(alias): ''' Remove an entry from the aliases file CLI Example: .. code-block:: bash salt '*' aliases.rm_alias alias ''' if not get_target(alias): return True lines = __parse_aliases() out = [] for (line_alias, line_target, line_comment) in lines: ...
[ "def", "rm_alias", "(", "alias", ")", ":", "if", "not", "get_target", "(", "alias", ")", ":", "return", "True", "lines", "=", "__parse_aliases", "(", ")", "out", "=", "[", "]", "for", "(", "line_alias", ",", "line_target", ",", "line_comment", ")", "in...
20.857143
0.002183
def feed(self, data): """Feed the parser with a chunk of data. Apropriate methods of `handler` will be called whenever something interesting is found. :Parameters: - `data`: the chunk of data to parse. :Types: - `data`: `str`""" with self.lock: ...
[ "def", "feed", "(", "self", ",", "data", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "in_use", ":", "raise", "StreamParseError", "(", "\"StreamReader.feed() is not reentrant!\"", ")", "self", ".", "in_use", "=", "True", "try", ":", "if",...
36.821429
0.00189
def places_autocomplete_query(client, input_text, offset=None, location=None, radius=None, language=None): """ Returns Place predictions given a textual search query, such as "pizza near New York", and optional geographic bounds. :param input_text: The text query on which ...
[ "def", "places_autocomplete_query", "(", "client", ",", "input_text", ",", "offset", "=", "None", ",", "location", "=", "None", ",", "radius", "=", "None", ",", "language", "=", "None", ")", ":", "return", "_autocomplete", "(", "client", ",", "\"query\"", ...
40.25
0.001733
def parse_call(self): """Parse a function call (like ``%foo{bar,baz}``) starting at ``pos``. Possibly appends a Call object to ``parts`` and update ``pos``. The character at ``pos`` must be ``%``. """ assert self.pos < len(self.string) assert self.string[self.pos] == FUN...
[ "def", "parse_call", "(", "self", ")", ":", "assert", "self", ".", "pos", "<", "len", "(", "self", ".", "string", ")", "assert", "self", ".", "string", "[", "self", ".", "pos", "]", "==", "FUNC_DELIM", "start_pos", "=", "self", ".", "pos", "self", ...
34.368421
0.001489
def validateField(cls, fieldName, value) : """checks if 'value' is valid for field 'fieldName'. If the validation is unsuccessful, raises a SchemaViolation or a ValidationError. for nested dicts ex: {address : { street: xxx} }, fieldName can take the form address.street """ try : ...
[ "def", "validateField", "(", "cls", ",", "fieldName", ",", "value", ")", ":", "try", ":", "valValue", "=", "Collection", ".", "validateField", "(", "fieldName", ",", "value", ")", "except", "SchemaViolation", "as", "e", ":", "if", "fieldName", "==", "\"_fr...
46.583333
0.014035
def haproxy(line): #TODO Handle all message formats ''' >>> import pprint >>> input_line1 = 'Apr 24 00:00:02 node haproxy[12298]: 1.1.1.1:48660 [24/Apr/2019:00:00:02.358] pre-staging~ pre-staging_doc/pre-staging_active 261/0/2/8/271 200 2406 - - ---- 4/4/0/1/0 0/0 {AAAAAA:AAAAA_AAAAA:AAAAA_AAAAA_AAAAA:3...
[ "def", "haproxy", "(", "line", ")", ":", "#TODO Handle all message formats", "_line", "=", "line", ".", "strip", "(", ")", ".", "split", "(", ")", "log", "=", "{", "}", "log", "[", "'client_server'", "]", "=", "_line", "[", "5", "]", ".", "split", "(...
36.657895
0.017476
def set_widgets(self): """Set widgets on the Extent tab.""" self.extent_dialog = ExtentSelectorDialog( self.parent.iface, self.parent.iface.mainWindow(), extent=self.parent.dock.extent.user_extent, crs=self.parent.dock.extent.crs) self.extent_dialo...
[ "def", "set_widgets", "(", "self", ")", ":", "self", ".", "extent_dialog", "=", "ExtentSelectorDialog", "(", "self", ".", "parent", ".", "iface", ",", "self", ".", "parent", ".", "iface", ".", "mainWindow", "(", ")", ",", "extent", "=", "self", ".", "p...
41.846154
0.001797
def generate_slug(value): "A copy of spectator.core.models.SluggedModelMixin._generate_slug()" alphabet = 'abcdefghijkmnopqrstuvwxyz23456789' salt = 'Django Spectator' if hasattr(settings, 'SPECTATOR_SLUG_ALPHABET'): alphabet = settings.SPECTATOR_SLUG_ALPHABET if hasattr(settings, 'SPECTAT...
[ "def", "generate_slug", "(", "value", ")", ":", "alphabet", "=", "'abcdefghijkmnopqrstuvwxyz23456789'", "salt", "=", "'Django Spectator'", "if", "hasattr", "(", "settings", ",", "'SPECTATOR_SLUG_ALPHABET'", ")", ":", "alphabet", "=", "settings", ".", "SPECTATOR_SLUG_A...
33.357143
0.002083
def fit(self, X, y): '''Fit the LFDA model. Parameters ---------- X : (n, d) array-like Input data. y : (n,) array-like Class labels, one per point of data. ''' X, y = self._prepare_inputs(X, y, ensure_min_samples=2) unique_classes, y = np.unique(y, return_inverse=True)...
[ "def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "X", ",", "y", "=", "self", ".", "_prepare_inputs", "(", "X", ",", "y", ",", "ensure_min_samples", "=", "2", ")", "unique_classes", ",", "y", "=", "np", ".", "unique", "(", "y", ",", "ret...
25.842857
0.015974
def _read_para_relay_hmac(self, code, cbit, clen, *, desc, length, version): """Read HIP RELAY_HMAC parameter. Structure of HIP RELAY_HMAC parameter [RFC 5770]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 ...
[ "def", "_read_para_relay_hmac", "(", "self", ",", "code", ",", "cbit", ",", "clen", ",", "*", ",", "desc", ",", "length", ",", "version", ")", ":", "_hmac", "=", "self", ".", "_read_fileng", "(", "clen", ")", "relay_hmac", "=", "dict", "(", "type", "...
44.555556
0.00183
def predicted_effects_for_variant( variant, transcript_id_whitelist=None, only_coding_changes=True): """ For a given variant, return its set of predicted effects. Optionally filter to transcripts where this variant results in a non-synonymous change to the protein sequence. ...
[ "def", "predicted_effects_for_variant", "(", "variant", ",", "transcript_id_whitelist", "=", "None", ",", "only_coding_changes", "=", "True", ")", ":", "effects", "=", "[", "]", "for", "transcript", "in", "variant", ".", "transcripts", ":", "if", "only_coding_chan...
32.538462
0.002295
def _create_err(self, errclass: str, *args) -> "Err": """ Create an error """ error = self._new_err(errclass, *args) self._add(error) return error
[ "def", "_create_err", "(", "self", ",", "errclass", ":", "str", ",", "*", "args", ")", "->", "\"Err\"", ":", "error", "=", "self", ".", "_new_err", "(", "errclass", ",", "*", "args", ")", "self", ".", "_add", "(", "error", ")", "return", "error" ]
26.857143
0.010309
def p_line_label_asm(p): """ line : LABEL asms NEWLINE """ p[0] = p[2] __DEBUG__("Declaring '%s%s' (value %04Xh) in %i" % (NAMESPACE, p[1], MEMORY.org, p.lineno(1))) MEMORY.declare_label(p[1], p.lineno(1))
[ "def", "p_line_label_asm", "(", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "2", "]", "__DEBUG__", "(", "\"Declaring '%s%s' (value %04Xh) in %i\"", "%", "(", "NAMESPACE", ",", "p", "[", "1", "]", ",", "MEMORY", ".", "org", ",", "p", ".", "linen...
36.666667
0.008889
def hessian(x, a): """ J'.J """ j = jac(x, a) return j.T.dot(j)
[ "def", "hessian", "(", "x", ",", "a", ")", ":", "j", "=", "jac", "(", "x", ",", "a", ")", "return", "j", ".", "T", ".", "dot", "(", "j", ")" ]
18
0.013333
def _properties_model_to_dict(properties): """ Convert properties model to dict. Args: properties: Properties model. Returns: dict: Converted model. """ result = {} for attr in properties.__dict__: value = getattr(properties, attr) if hasattr(value, '__modu...
[ "def", "_properties_model_to_dict", "(", "properties", ")", ":", "result", "=", "{", "}", "for", "attr", "in", "properties", ".", "__dict__", ":", "value", "=", "getattr", "(", "properties", ",", "attr", ")", "if", "hasattr", "(", "value", ",", "'__module_...
24.809524
0.001848
def shadow_calc(data): """计算上下影线 Arguments: data {DataStruct.slice} -- 输入的是一个行情切片 Returns: up_shadow {float} -- 上影线 down_shdow {float} -- 下影线 entity {float} -- 实体部分 date {str} -- 时间 code {str} -- 代码 """ up_shadow = abs(data.high - (max(data.open, da...
[ "def", "shadow_calc", "(", "data", ")", ":", "up_shadow", "=", "abs", "(", "data", ".", "high", "-", "(", "max", "(", "data", ".", "open", ",", "data", ".", "close", ")", ")", ")", "down_shadow", "=", "abs", "(", "data", ".", "low", "-", "(", "...
30.375
0.00133
def rewrite_uris(self, raw_uri, file_provider): """Accept a raw uri and return rewritten versions. This function returns a normalized URI and a docker path. The normalized URI may have minor alterations meant to disambiguate and prepare for use by shell utilities that may require a specific format. ...
[ "def", "rewrite_uris", "(", "self", ",", "raw_uri", ",", "file_provider", ")", ":", "if", "file_provider", "==", "job_model", ".", "P_GCS", ":", "normalized", ",", "docker_path", "=", "_gcs_uri_rewriter", "(", "raw_uri", ")", "elif", "file_provider", "==", "jo...
45.830189
0.002015
def addresses(self, fields=None): """ List of addresses associated with the postcode. Addresses are dict objects which look like the following:: { "uprn": "10033544614", "organisation_name": "BUCKINGHAM PALACE", "department_name": "", ...
[ "def", "addresses", "(", "self", ",", "fields", "=", "None", ")", ":", "if", "fields", "is", "None", ":", "fields", "=", "','", ".", "join", "(", "DEFAULT_ADDRESS_FIELDS", ")", "if", "getattr", "(", "self", ",", "'_addresses'", ",", "None", ")", "is", ...
34.825
0.001397
def expect(obj, strict=None, times=None, atleast=None, atmost=None, between=None): """Stub a function call, and set up an expected call count. Usage:: # Given `dog` is an instance of a `Dog` expect(dog, times=1).bark('Wuff').thenReturn('Miau') dog.bark('Wuff') dog.ba...
[ "def", "expect", "(", "obj", ",", "strict", "=", "None", ",", "times", "=", "None", ",", "atleast", "=", "None", ",", "atmost", "=", "None", ",", "between", "=", "None", ")", ":", "if", "strict", "is", "None", ":", "strict", "=", "True", "theMock",...
31.764706
0.000898
def default_search_factory(self, search, query_parser=None): """Parse query using elasticsearch DSL query. :param self: REST view. :param search: Elastic search DSL search instance. :returns: Tuple with search instance and URL arguments. """ def _default_parser(qstr=None): """Default pa...
[ "def", "default_search_factory", "(", "self", ",", "search", ",", "query_parser", "=", "None", ")", ":", "def", "_default_parser", "(", "qstr", "=", "None", ")", ":", "\"\"\"Default parser that uses the Q() from elasticsearch_dsl.\"\"\"", "if", "qstr", ":", "return", ...
33.694444
0.000801
async def jsk_in(self, ctx: commands.Context, channel: discord.TextChannel, *, command_string: str): """ Run a command as if it were in a different channel. """ alt_ctx = await copy_context_with(ctx, channel=channel, content=ctx.prefix + command_string) if alt_ctx.command is No...
[ "async", "def", "jsk_in", "(", "self", ",", "ctx", ":", "commands", ".", "Context", ",", "channel", ":", "discord", ".", "TextChannel", ",", "*", ",", "command_string", ":", "str", ")", ":", "alt_ctx", "=", "await", "copy_context_with", "(", "ctx", ",", ...
41
0.010846
def qteAbort(self, msgObj): """ Restore the original cursor position because the user hit abort. """ self.qteWidget.setCursorPosition(*self.cursorPosOrig) self.qteMain.qtesigAbort.disconnect(self.qteAbort)
[ "def", "qteAbort", "(", "self", ",", "msgObj", ")", ":", "self", ".", "qteWidget", ".", "setCursorPosition", "(", "*", "self", ".", "cursorPosOrig", ")", "self", ".", "qteMain", ".", "qtesigAbort", ".", "disconnect", "(", "self", ".", "qteAbort", ")" ]
40
0.008163
def add_source(self, url, *, note=''): """ Add a source URL from which data was collected """ new = {'url': url, 'note': note} self.sources.append(new)
[ "def", "add_source", "(", "self", ",", "url", ",", "*", ",", "note", "=", "''", ")", ":", "new", "=", "{", "'url'", ":", "url", ",", "'note'", ":", "note", "}", "self", ".", "sources", ".", "append", "(", "new", ")" ]
43
0.011429
def generate_config_index(defaults: Dict[str, str], base_dir=None) -> Dict[str, Path]: """ Determines where existing info can be found in the system, and creates a corresponding data dict that can be written to index.json in the baseDataDir. The information in the files de...
[ "def", "generate_config_index", "(", "defaults", ":", "Dict", "[", "str", ",", "str", "]", ",", "base_dir", "=", "None", ")", "->", "Dict", "[", "str", ",", "Path", "]", ":", "base", "=", "Path", "(", "base_dir", ")", "if", "base_dir", "else", "infer...
41.333333
0.000657
def apply(self, cls, originalMemberNameList, memberName, classNamingConvention, getter, setter): """ :type cls: type :type originalMemberNameList: list(str) :type memberName: str :type classNamingConvention: INamingConvention|None """ accessorDict = self._accessorDict(memberName, classNa...
[ "def", "apply", "(", "self", ",", "cls", ",", "originalMemberNameList", ",", "memberName", ",", "classNamingConvention", ",", "getter", ",", "setter", ")", ":", "accessorDict", "=", "self", ".", "_accessorDict", "(", "memberName", ",", "classNamingConvention", "...
48.909091
0.009124