text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def check_integrity(sakefile, settings): """ Checks the format of the sakefile dictionary to ensure it conforms to specification Args: A dictionary that is the parsed Sakefile (from sake.py) The setting dictionary (for print functions) Returns: True if the Sakefile is confor...
[ "def", "check_integrity", "(", "sakefile", ",", "settings", ")", ":", "sprint", "=", "settings", "[", "\"sprint\"", "]", "error", "=", "settings", "[", "\"error\"", "]", "sprint", "(", "\"Call to check_integrity issued\"", ",", "level", "=", "\"verbose\"", ")", ...
39.4
16.44
def find_binary(self, binary): """ Scan and return the first path to a binary that we can find """ if os.path.exists(binary): return binary # Extract out the filename if we were given a full path binary_name = os.path.basename(binary) # Gather $PATH ...
[ "def", "find_binary", "(", "self", ",", "binary", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "binary", ")", ":", "return", "binary", "# Extract out the filename if we were given a full path", "binary_name", "=", "os", ".", "path", ".", "basename", ...
26.794118
16.852941
def get_as_local_path(path, overwrite, progress=0, httpuser=None, httppassword=None): """ Automatically handle local and remote URLs, files and directories path: Either a local directory, file or remote URL. If a URL is given it will be fetched. If this is a zip it will be autom...
[ "def", "get_as_local_path", "(", "path", ",", "overwrite", ",", "progress", "=", "0", ",", "httpuser", "=", "None", ",", "httppassword", "=", "None", ")", ":", "m", "=", "re", ".", "match", "(", "'([A-Za-z]+)://'", ",", "path", ")", "if", "m", ":", "...
40.321429
17.571429
def from_srt(cls, file): """Reads captions from a file in SubRip format.""" parser = SRTParser().read(file) return cls(file=file, captions=parser.captions)
[ "def", "from_srt", "(", "cls", ",", "file", ")", ":", "parser", "=", "SRTParser", "(", ")", ".", "read", "(", "file", ")", "return", "cls", "(", "file", "=", "file", ",", "captions", "=", "parser", ".", "captions", ")" ]
44
8
def __copyfile(source, destination): """Copy data and mode bits ("cp source destination"). The destination may be a directory. Args: source (str): Source file (file to copy). destination (str): Destination file or directory (where to copy). Returns: bool: True if the operation...
[ "def", "__copyfile", "(", "source", ",", "destination", ")", ":", "logger", ".", "info", "(", "\"copyfile: %s -> %s\"", "%", "(", "source", ",", "destination", ")", ")", "try", ":", "__create_destdir", "(", "destination", ")", "shutil", ".", "copy", "(", "...
30.181818
20.363636
def _geodetic_to_cartesian(cls, lat, lon, alt): """Conversion from latitude, longitude and altitude coordinates to cartesian with respect to an ellipsoid Args: lat (float): Latitude in radians lon (float): Longitude in radians alt (float): Altitude to sea lev...
[ "def", "_geodetic_to_cartesian", "(", "cls", ",", "lat", ",", "lon", ",", "alt", ")", ":", "C", "=", "Earth", ".", "r", "/", "np", ".", "sqrt", "(", "1", "-", "(", "Earth", ".", "e", "*", "np", ".", "sin", "(", "lat", ")", ")", "**", "2", "...
34.913043
15.304348
def _can_compute(self, _id, persistence): """ Return true if this feature stored, or is unstored, but can be computed from stored dependencies """ if self.store and self._stored(_id, persistence): return True if self.is_root: return False ...
[ "def", "_can_compute", "(", "self", ",", "_id", ",", "persistence", ")", ":", "if", "self", ".", "store", "and", "self", ".", "_stored", "(", "_id", ",", "persistence", ")", ":", "return", "True", "if", "self", ".", "is_root", ":", "return", "False", ...
30.384615
19.153846
def get_plugin(self, method): """ Return plugin object if CLI option is activated and method exists @param method: name of plugin's method we're calling @type method: string @returns: list of plugins with `method` """ all_plugins = [] for entry_point in...
[ "def", "get_plugin", "(", "self", ",", "method", ")", ":", "all_plugins", "=", "[", "]", "for", "entry_point", "in", "pkg_resources", ".", "iter_entry_points", "(", "'yolk.plugins'", ")", ":", "plugin_obj", "=", "entry_point", ".", "load", "(", ")", "plugin"...
34.772727
17.045455
def get_constituents(self, index_ticker, date=None, only_list=False): """ Get a list of all constituents of a given index. index_ticker - Datastream ticker for index date - date for which list should be retrieved (if None then list of present constitue...
[ "def", "get_constituents", "(", "self", ",", "index_ticker", ",", "date", "=", "None", ",", "only_list", "=", "False", ")", ":", "if", "date", "is", "not", "None", ":", "str_date", "=", "pd", ".", "to_datetime", "(", "date", ")", ".", "strftime", "(", ...
51.32
24.72
def _init_client(self, from_archive=False): """Init client""" return KitsuneClient(self.url, self.archive, from_archive)
[ "def", "_init_client", "(", "self", ",", "from_archive", "=", "False", ")", ":", "return", "KitsuneClient", "(", "self", ".", "url", ",", "self", ".", "archive", ",", "from_archive", ")" ]
33.5
17.25
def ColorWithLightness(self, lightness): '''Create a new instance based on this one with a new lightness value. Parameters: :lightness: The lightness of the new color [0...1]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ColorWithLightness(0.25) (0.5,...
[ "def", "ColorWithLightness", "(", "self", ",", "lightness", ")", ":", "h", ",", "s", ",", "l", "=", "self", ".", "__hsl", "return", "Color", "(", "(", "h", ",", "s", ",", "lightness", ")", ",", "'hsl'", ",", "self", ".", "__a", ",", "self", ".", ...
27.944444
24.5
def paintEvent(self, event): """ Overloads the paint event to handle painting pointers for the popup \ mode. :param event | <QPaintEvent> """ # use the base technique for the dialog mode if self.currentMode() == XPopupWidget.Mode.Dialog: ...
[ "def", "paintEvent", "(", "self", ",", "event", ")", ":", "# use the base technique for the dialog mode\r", "if", "self", ".", "currentMode", "(", ")", "==", "XPopupWidget", ".", "Mode", ".", "Dialog", ":", "super", "(", "XPopupWidget", ",", "self", ")", ".", ...
36.545455
15.181818
def _receive_all(socket, num_bytes): """Reads `num_bytes` bytes from the specified socket. :param socket: open socket instance :param num_bytes: number of bytes to read :return: received data """ buffer = '' buffer_size = 0 bytes_left = num_bytes while buffer_size < num_bytes: ...
[ "def", "_receive_all", "(", "socket", ",", "num_bytes", ")", ":", "buffer", "=", "''", "buffer_size", "=", "0", "bytes_left", "=", "num_bytes", "while", "buffer_size", "<", "num_bytes", ":", "data", "=", "socket", ".", "recv", "(", "bytes_left", ")", "delt...
24.263158
15.421053
def MGMT_ACTIVE_SET(self, sAddr='', xCommissioningSessionId=None, listActiveTimestamp=None, listChannelMask=None, xExtendedPanId=None, sNetworkName=None, sPSKc=None, listSecurityPolicy=None, xChannel=None, sMeshLocalPrefix=None, xMasterKey=None, xPanId=None, xTmfPort=None...
[ "def", "MGMT_ACTIVE_SET", "(", "self", ",", "sAddr", "=", "''", ",", "xCommissioningSessionId", "=", "None", ",", "listActiveTimestamp", "=", "None", ",", "listChannelMask", "=", "None", ",", "xExtendedPanId", "=", "None", ",", "sNetworkName", "=", "None", ","...
41.166667
24.410256
def GetPlugins(cls): """Retrieves the registered plugins. Yields: tuple[str, type]: name and class of the plugin. """ for plugin_name, plugin_class in iter(cls._plugin_classes.items()): yield plugin_name, plugin_class
[ "def", "GetPlugins", "(", "cls", ")", ":", "for", "plugin_name", ",", "plugin_class", "in", "iter", "(", "cls", ".", "_plugin_classes", ".", "items", "(", ")", ")", ":", "yield", "plugin_name", ",", "plugin_class" ]
29.875
17
def execute(filename, formatted_name): """Renames a file based on the name generated using metadata. :param str filename: absolute path and filename of original file :param str formatted_name: absolute path and new filename """ if os.path.isfile(formatted_name): # If the destination exists...
[ "def", "execute", "(", "filename", ",", "formatted_name", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "formatted_name", ")", ":", "# If the destination exists, skip rename unless overwrite enabled", "if", "not", "cfg", ".", "CONF", ".", "overwrite_file_en...
39.235294
18.411765
def formfield_for_dbfield(self, db_field, **kwargs): ''' Offer grading choices from the assignment definition as potential form field values for 'grading'. When no object is given in the form, the this is a new manual submission ''' if db_field.name == "grading": ...
[ "def", "formfield_for_dbfield", "(", "self", ",", "db_field", ",", "*", "*", "kwargs", ")", ":", "if", "db_field", ".", "name", "==", "\"grading\"", ":", "submurl", "=", "kwargs", "[", "'request'", "]", ".", "path", "try", ":", "# Does not work on new submis...
56.6
26.866667
def append_transition(self, symbol, targetset): """Appends a transition""" if symbol in self.transitions: return self.transitions[symbol] = targetset
[ "def", "append_transition", "(", "self", ",", "symbol", ",", "targetset", ")", ":", "if", "symbol", "in", "self", ".", "transitions", ":", "return", "self", ".", "transitions", "[", "symbol", "]", "=", "targetset" ]
36.2
7
def get(img, light=False): """Get colorscheme.""" if not shutil.which("schemer2"): logging.error("Schemer2 wasn't found on your system.") logging.error("Try another backend. (wal --backend)") sys.exit(1) cols = [col.decode('UTF-8') for col in gen_colors(img)] return adjust(cols,...
[ "def", "get", "(", "img", ",", "light", "=", "False", ")", ":", "if", "not", "shutil", ".", "which", "(", "\"schemer2\"", ")", ":", "logging", ".", "error", "(", "\"Schemer2 wasn't found on your system.\"", ")", "logging", ".", "error", "(", "\"Try another b...
35.444444
16.777778
def output(value, address): ''' int, str -> TxOut accepts base58 or bech32 addresses ''' script = addr.to_output_script(address) value = utils.i2le_padded(value, 8) return tb._make_output(value, script)
[ "def", "output", "(", "value", ",", "address", ")", ":", "script", "=", "addr", ".", "to_output_script", "(", "address", ")", "value", "=", "utils", ".", "i2le_padded", "(", "value", ",", "8", ")", "return", "tb", ".", "_make_output", "(", "value", ","...
27.875
13.125
def get_program_type_by_slug(self, slug): """ Get a program type by its slug. Arguments: slug (str): The slug to identify the program type. Returns: dict: A program type object. """ return self._load_data( self.PROGRAM_TYPES_ENDPOINT...
[ "def", "get_program_type_by_slug", "(", "self", ",", "slug", ")", ":", "return", "self", ".", "_load_data", "(", "self", ".", "PROGRAM_TYPES_ENDPOINT", ",", "resource_id", "=", "slug", ",", "default", "=", "None", ",", ")" ]
23.25
16
def check(self, var): """Return True if the variable matches this type, and False otherwise.""" return isinstance(var, tuple) and all(_check_type(t, self._element_type) for t in var)
[ "def", "check", "(", "self", ",", "var", ")", ":", "return", "isinstance", "(", "var", ",", "tuple", ")", "and", "all", "(", "_check_type", "(", "t", ",", "self", ".", "_element_type", ")", "for", "t", "in", "var", ")" ]
65.333333
24.333333
def filter_collections(self, model, context=None): """ Filter collections Runs filters on collection properties changing them in place. :param model: object or dict :param context: object, dict or None :return: None """ if model is None: retur...
[ "def", "filter_collections", "(", "self", ",", "model", ",", "context", "=", "None", ")", ":", "if", "model", "is", "None", ":", "return", "for", "property_name", "in", "self", ".", "collections", ":", "prop", "=", "self", ".", "collections", "[", "prope...
31.84
14.32
def prepare(self): """ Preparatory checks for whether this Executor can go ahead and (try to) build its targets. """ for s in self.get_all_sources(): if s.missing(): msg = "Source `%s' not found, needed by target `%s'." raise SCons.Erro...
[ "def", "prepare", "(", "self", ")", ":", "for", "s", "in", "self", ".", "get_all_sources", "(", ")", ":", "if", "s", ".", "missing", "(", ")", ":", "msg", "=", "\"Source `%s' not found, needed by target `%s'.\"", "raise", "SCons", ".", "Errors", ".", "Stop...
40.333333
14.777778
def token(cls: Type[XHXType], sha_hash: str) -> XHXType: """ Return XHX instance from sha_hash :param sha_hash: SHA256 hash :return: """ xhx = cls() xhx.sha_hash = sha_hash return xhx
[ "def", "token", "(", "cls", ":", "Type", "[", "XHXType", "]", ",", "sha_hash", ":", "str", ")", "->", "XHXType", ":", "xhx", "=", "cls", "(", ")", "xhx", ".", "sha_hash", "=", "sha_hash", "return", "xhx" ]
23.9
13.7
def user(self, username): """ Returns the :class:`~plexapi.myplex.MyPlexUser` that matches the email or username specified. Parameters: username (str): Username, email or id of the user to return. """ for user in self.users(): # Home users don't have emai...
[ "def", "user", "(", "self", ",", "username", ")", ":", "for", "user", "in", "self", ".", "users", "(", ")", ":", "# Home users don't have email, username etc.", "if", "username", ".", "lower", "(", ")", "==", "user", ".", "title", ".", "lower", "(", ")",...
40.875
21.75
def from_short_lines_text(self, text: str): """ Famous example from Hávamál 77 >>> text = "Deyr fé,\\ndeyja frændr,\\ndeyr sjalfr it sama,\\nek veit einn,\\nat aldrei deyr:\\ndómr um dauðan hvern." >>> lj = Ljoodhhaattr() >>> lj.from_short_lines_text(text) >>> [sl.text fo...
[ "def", "from_short_lines_text", "(", "self", ",", "text", ":", "str", ")", ":", "Metre", ".", "from_short_lines_text", "(", "self", ",", "text", ")", "lines", "=", "[", "line", "for", "line", "in", "text", ".", "split", "(", "\"\\n\"", ")", "if", "line...
58.526316
31.578947
def get_bounding_boxes(df_shapes, shape_i_columns): ''' Return a `pandas.DataFrame` indexed by `shape_i_columns` (i.e., each row corresponds to a single shape/polygon), containing the following columns: - `width`: The width of the widest part of the shape. - `height`: The height of the tallest pa...
[ "def", "get_bounding_boxes", "(", "df_shapes", ",", "shape_i_columns", ")", ":", "xy_groups", "=", "df_shapes", ".", "groupby", "(", "shape_i_columns", ")", "[", "[", "'x'", ",", "'y'", "]", "]", "xy_min", "=", "xy_groups", ".", "agg", "(", "'min'", ")", ...
40.785714
25.071429
def reqMktDepth(self, id, contract, numRows, mktDepthOptions): """reqMktDepth(EClient self, TickerId id, Contract contract, int numRows, TagValueListSPtr const & mktDepthOptions)""" return _swigibpy.EClient_reqMktDepth(self, id, contract, numRows, mktDepthOptions)
[ "def", "reqMktDepth", "(", "self", ",", "id", ",", "contract", ",", "numRows", ",", "mktDepthOptions", ")", ":", "return", "_swigibpy", ".", "EClient_reqMktDepth", "(", "self", ",", "id", ",", "contract", ",", "numRows", ",", "mktDepthOptions", ")" ]
92.666667
24
def convert(self, name): "translate gui2py attribute name from pythoncard legacy code" new_name = PYTHONCARD_PROPERTY_MAP.get(name) if new_name: print "WARNING: property %s should be %s (%s)" % (name, new_name, self.obj.name) return new_name else: retu...
[ "def", "convert", "(", "self", ",", "name", ")", ":", "new_name", "=", "PYTHONCARD_PROPERTY_MAP", ".", "get", "(", "name", ")", "if", "new_name", ":", "print", "\"WARNING: property %s should be %s (%s)\"", "%", "(", "name", ",", "new_name", ",", "self", ".", ...
40
23.25
def reward_wall(self): """ Add a wall collision reward """ if not 'wall' in self.mode: return mode = self.mode['wall'] if mode and mode and self.__test_cond(mode): self.logger.debug("Wall {x}/{y}'".format(x=self.bumped_x, y=self.bumped_y)) ...
[ "def", "reward_wall", "(", "self", ")", ":", "if", "not", "'wall'", "in", "self", ".", "mode", ":", "return", "mode", "=", "self", ".", "mode", "[", "'wall'", "]", "if", "mode", "and", "mode", "and", "self", ".", "__test_cond", "(", "mode", ")", ":...
36.416667
17.583333
def _start_print(self): """Print the start message with or without newline depending on the self._start_no_nl variable. """ if self._start_no_nl: sys.stdout.write(self._start_msg) sys.stdout.flush() else: print(self._start_msg)
[ "def", "_start_print", "(", "self", ")", ":", "if", "self", ".", "_start_no_nl", ":", "sys", ".", "stdout", ".", "write", "(", "self", ".", "_start_msg", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "else", ":", "print", "(", "self", ".", "_s...
32.777778
9
def delete(self, *clauses, **filters): """Delete rows from the table. Keyword arguments can be used to add column-based filters. The filter criterion will always be equality: :: table.delete(place='Berlin') If no arguments are given, all records are deleted. ...
[ "def", "delete", "(", "self", ",", "*", "clauses", ",", "*", "*", "filters", ")", ":", "if", "not", "self", ".", "exists", ":", "return", "False", "clause", "=", "self", ".", "_args_to_clause", "(", "filters", ",", "clauses", "=", "clauses", ")", "st...
32.705882
17
def save_composition(self, composition_form, *args, **kwargs): """Pass through to provider CompositionAdminSession.update_composition""" # Implemented from kitosid template for - # osid.resource.ResourceAdminSession.update_resource if composition_form.is_for_update(): return ...
[ "def", "save_composition", "(", "self", ",", "composition_form", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Implemented from kitosid template for -", "# osid.resource.ResourceAdminSession.update_resource", "if", "composition_form", ".", "is_for_update", "(", ...
57.875
19.5
def _interpret_response(self, response, payload, expected_status): # type: (Response, dict, Container[int]) -> dict """ Interprets the HTTP response from the node. :param response: The response object received from :py:meth:`_send_http_request`. :param p...
[ "def", "_interpret_response", "(", "self", ",", "response", ",", "payload", ",", "expected_status", ")", ":", "# type: (Response, dict, Container[int]) -> dict", "raw_content", "=", "response", ".", "text", "if", "not", "raw_content", ":", "raise", "with_context", "("...
30.078652
17.876404
def set_title(self, index, title): """Sets the title of a container page. Parameters ---------- index : int Index of the container page title : unicode New title """ # JSON dictionaries have string keys, so we convert index to a string ...
[ "def", "set_title", "(", "self", ",", "index", ",", "title", ")", ":", "# JSON dictionaries have string keys, so we convert index to a string", "index", "=", "unicode_type", "(", "int", "(", "index", ")", ")", "self", ".", "_titles", "[", "index", "]", "=", "tit...
29.642857
14
def open_file(self, title="Open File", initialDir="~", fileTypes="*|All Files", rememberAs=None, **kwargs): """ Show an Open File dialog Usage: C{dialog.open_file(title="Open File", initialDir="~", fileTypes="*|All Files", rememberAs=None, **kwargs)} @param title: windo...
[ "def", "open_file", "(", "self", ",", "title", "=", "\"Open File\"", ",", "initialDir", "=", "\"~\"", ",", "fileTypes", "=", "\"*|All Files\"", ",", "rememberAs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "rememberAs", "is", "not", "None", ":...
55.117647
31
def rotate_crop(centerij, sz, angle, img=None, mode='constant', **kwargs): """ rotate and crop if no img, then return crop function :param centerij: :param sz: :param angle: :param img: [h,w,d] :param mode: padding option :return: cropped image or function """ # crop enough s...
[ "def", "rotate_crop", "(", "centerij", ",", "sz", ",", "angle", ",", "img", "=", "None", ",", "mode", "=", "'constant'", ",", "*", "*", "kwargs", ")", ":", "# crop enough size ( 2 * sqrt(sum(sz^2) )", "# rotate", "from", "skimage", "import", "transform", "sz",...
33.804878
21.073171
def add_linguistic_processor(self, layer, my_lp): """ Adds a linguistic processor to the header @type my_lp: L{Clp} @param my_lp: linguistic processor object @type layer: string @param layer: the layer to which the processor is related to """ if self.heade...
[ "def", "add_linguistic_processor", "(", "self", ",", "layer", ",", "my_lp", ")", ":", "if", "self", ".", "header", "is", "None", ":", "self", ".", "header", "=", "CHeader", "(", "type", "=", "self", ".", "type", ")", "self", ".", "root", ".", "insert...
40.166667
10.833333
def register_model(self, key, *models, **kwargs): """ Register a cache_group with this manager. Use this method to register more simple groups where all models share the same parameters. Any arguments are treated as models that you would like to register. Any k...
[ "def", "register_model", "(", "self", ",", "key", ",", "*", "models", ",", "*", "*", "kwargs", ")", ":", "cache_group", "=", "CacheGroup", "(", "key", ")", "for", "model", "in", "models", ":", "cache_group", ".", "register", "(", "model", ",", "*", "...
31.227273
18.863636
def main(argv=sys.argv[1:]): """Parses the command line comments.""" usage = 'usage: %prog [options] FILE\n\n' + __doc__ parser = OptionParser(usage) # options parser.add_option("-f", "--force", action='store_true', default=False, help="make changes even ...
[ "def", "main", "(", "argv", "=", "sys", ".", "argv", "[", "1", ":", "]", ")", ":", "usage", "=", "'usage: %prog [options] FILE\\n\\n'", "+", "__doc__", "parser", "=", "OptionParser", "(", "usage", ")", "# options", "parser", ".", "add_option", "(", "\"-f\"...
47.098039
24.098039
def _add_mixing_variable_names_to_individual_vars(self): """ Ensure that the model objects mixing variables are added to its list of individual variables. """ assert isinstance(self.ind_var_names, list) # Note that if one estimates a mixed logit model, then the mixing ...
[ "def", "_add_mixing_variable_names_to_individual_vars", "(", "self", ")", ":", "assert", "isinstance", "(", "self", ".", "ind_var_names", ",", "list", ")", "# Note that if one estimates a mixed logit model, then the mixing", "# variables will be added to individual vars. And if one e...
51.222222
22.888889
def delete_file(self, sass_filename, sass_fileurl): """ Delete a *.css file, but only if it has been generated through a SASS/SCSS file. """ if self.use_static_root: destpath = os.path.join(self.static_root, os.path.splitext(sass_fileurl)[0] + '.css') else: ...
[ "def", "delete_file", "(", "self", ",", "sass_filename", ",", "sass_fileurl", ")", ":", "if", "self", ".", "use_static_root", ":", "destpath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "static_root", ",", "os", ".", "path", ".", "splitext", ...
45.615385
18.384615
def read_flash(self, addr=0xFF, page=0x00): """Read back a flash page from the Crazyflie and return it""" buff = bytearray() page_size = self.targets[addr].page_size for i in range(0, int(math.ceil(page_size / 25.0))): pk = None retry_counter = 5 whi...
[ "def", "read_flash", "(", "self", ",", "addr", "=", "0xFF", ",", "page", "=", "0x00", ")", ":", "buff", "=", "bytearray", "(", ")", "page_size", "=", "self", ".", "targets", "[", "addr", "]", ".", "page_size", "for", "i", "in", "range", "(", "0", ...
35.884615
15.615385
def verify(value, msg): """ C-style validator Keyword arguments: value -- dictionary to validate (required) msg -- the protobuf schema to validate against (required) Returns: True: If valid input False: If invalid input """ return bool(value) and \ converts_t...
[ "def", "verify", "(", "value", ",", "msg", ")", ":", "return", "bool", "(", "value", ")", "and", "converts_to_proto", "(", "value", ",", "msg", ")", "and", "successfuly_encodes", "(", "msg", ")", "and", "special_typechecking", "(", "value", ",", "msg", "...
26
14.5
def update_board_chart(self, chart, team_context, board, name): """UpdateBoardChart. Update a board chart :param :class:`<BoardChart> <azure.devops.v5_0.work.models.BoardChart>` chart: :param :class:`<TeamContext> <azure.devops.v5_0.work.models.TeamContext>` team_context: The team contex...
[ "def", "update_board_chart", "(", "self", ",", "chart", ",", "team_context", ",", "board", ",", "name", ")", ":", "project", "=", "None", "team", "=", "None", "if", "team_context", "is", "not", "None", ":", "if", "team_context", ".", "project_id", ":", "...
48.162162
20.405405
def critic(self, real_pred, input): "Create some `fake_pred` with the generator from `input` and compare them to `real_pred` in `self.loss_funcD`." fake = self.gan_model.generator(input.requires_grad_(False)).requires_grad_(True) fake_pred = self.gan_model.critic(fake) return self.loss_f...
[ "def", "critic", "(", "self", ",", "real_pred", ",", "input", ")", ":", "fake", "=", "self", ".", "gan_model", ".", "generator", "(", "input", ".", "requires_grad_", "(", "False", ")", ")", ".", "requires_grad_", "(", "True", ")", "fake_pred", "=", "se...
68.4
30.4
def sequence_to_graph(G, seq, color='black'): """ Automatically construct graph given a sequence of characters. """ for x in seq: if x.endswith("_1"): # Mutation G.node(x, color=color, width="0.1", shape="circle", label="") else: G.node(x, color=color) for a,...
[ "def", "sequence_to_graph", "(", "G", ",", "seq", ",", "color", "=", "'black'", ")", ":", "for", "x", "in", "seq", ":", "if", "x", ".", "endswith", "(", "\"_1\"", ")", ":", "# Mutation", "G", ".", "node", "(", "x", ",", "color", "=", "color", ","...
33.090909
12.363636
def _remote_file_exists(self, path): """ Determine if `path` exists by directly invoking os.path.exists() in the target user account. """ LOG.debug('_remote_file_exists(%r)', path) return self._connection.get_chain().call( ansible_mitogen.target.file_exists, ...
[ "def", "_remote_file_exists", "(", "self", ",", "path", ")", ":", "LOG", ".", "debug", "(", "'_remote_file_exists(%r)'", ",", "path", ")", "return", "self", ".", "_connection", ".", "get_chain", "(", ")", ".", "call", "(", "ansible_mitogen", ".", "target", ...
35.6
11.6
def set_pwm_freq(self, freq_hz): """Set the PWM frequency to the provided value in hertz.""" prescaleval = 25000000.0 # 25MHz prescaleval /= 4096.0 # 12-bit prescaleval /= float(freq_hz) prescaleval -= 1.0 logger.debug('Setting PWM frequency to {0} Hz'.format(fre...
[ "def", "set_pwm_freq", "(", "self", ",", "freq_hz", ")", ":", "prescaleval", "=", "25000000.0", "# 25MHz", "prescaleval", "/=", "4096.0", "# 12-bit", "prescaleval", "/=", "float", "(", "freq_hz", ")", "prescaleval", "-=", "1.0", "logger", ".", "debug", "(", ...
47.176471
10.411765
def concatenate(vars, axis=-1): """ A utility function of concatenate. """ from deepy.core.neural_var import NeuralVariable if isinstance(vars[0], NeuralVariable): concat_var = Concatenate(axis=axis).compute(*vars) if axis == -1 or axis == vars[0].tensor.ndim - 1: concat_...
[ "def", "concatenate", "(", "vars", ",", "axis", "=", "-", "1", ")", ":", "from", "deepy", ".", "core", ".", "neural_var", "import", "NeuralVariable", "if", "isinstance", "(", "vars", "[", "0", "]", ",", "NeuralVariable", ")", ":", "concat_var", "=", "C...
36.833333
12.5
def _is_valid_api_url(self, url): """Callback for is_valid_api_url.""" # Check response is a JSON with ok: 1 data = {} try: r = requests.get(url, proxies=self.proxy_servers) content = to_text_string(r.content, encoding='utf-8') data = json.loads(conten...
[ "def", "_is_valid_api_url", "(", "self", ",", "url", ")", ":", "# Check response is a JSON with ok: 1", "data", "=", "{", "}", "try", ":", "r", "=", "requests", ".", "get", "(", "url", ",", "proxies", "=", "self", ".", "proxy_servers", ")", "content", "=",...
35.166667
13.666667
def get_dependencies(self, id, **kwargs): """ Get the direct dependencies of the specified configuration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the re...
[ "def", "get_dependencies", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "get_dependencies_with_http_inf...
41.448276
15.241379
def listdir( self, folder_id='0', type_filter=None, offset=None, limit=None, **listdir_kwz ): '''Return a list of objects in the specified folder_id. limit is passed to the API, so might be used as optimization. None means "fetch all items, with several requests, if necessary". type_filter can be set to ...
[ "def", "listdir", "(", "self", ",", "folder_id", "=", "'0'", ",", "type_filter", "=", "None", ",", "offset", "=", "None", ",", "limit", "=", "None", ",", "*", "*", "listdir_kwz", ")", ":", "res", "=", "yield", "super", "(", "txBox", ",", "self", ")...
50.761905
18
def _ParseArgs(self, args, known_only): """Helper function to do the main argument parsing. This function goes through args and does the bulk of the flag parsing. It will find the corresponding flag in our flag dictionary, and call its .parse() method on the flag value. Args: args: List of s...
[ "def", "_ParseArgs", "(", "self", ",", "args", ",", "known_only", ")", ":", "unknown_flags", ",", "unparsed_args", ",", "undefok", "=", "[", "]", ",", "[", "]", ",", "set", "(", ")", "flag_dict", "=", "self", ".", "FlagDict", "(", ")", "args", "=", ...
29.387097
20.182796
def load_scheduler_plugins(self): """Refresh the list of available schedulers Returns: `list` of :obj:`BaseScheduler` """ if not self.scheduler_plugins: for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.schedulers']['plugins']: cls = entry...
[ "def", "load_scheduler_plugins", "(", "self", ")", ":", "if", "not", "self", ".", "scheduler_plugins", ":", "for", "entry_point", "in", "CINQ_PLUGINS", "[", "'cloud_inquisitor.plugins.schedulers'", "]", "[", "'plugins'", "]", ":", "cls", "=", "entry_point", ".", ...
48.5
22.928571
def _SetUnknownFlag(self, name, value): """Returns value if setting flag |name| to |value| returned True. Args: name: Name of the flag to set. value: Value to set. Returns: Flag value on successful call. Raises: UnrecognizedFlagError IllegalFlagValueError """ set...
[ "def", "_SetUnknownFlag", "(", "self", ",", "name", ",", "value", ")", ":", "setter", "=", "self", ".", "__dict__", "[", "'__set_unknown'", "]", "if", "setter", ":", "try", ":", "setter", "(", "name", ",", "value", ")", "return", "value", "except", "("...
29.6
19.68
def res_to_url(resource, action): """Convert resource.action to (url, HTTP_METHOD)""" i = action.find("_") if i < 0: url = "/" + resource httpmethod = action else: url = "/%s/%s" % (resource, action[i + 1:]) httpmethod = action[:i] return url, httpmethod.upper()
[ "def", "res_to_url", "(", "resource", ",", "action", ")", ":", "i", "=", "action", ".", "find", "(", "\"_\"", ")", "if", "i", "<", "0", ":", "url", "=", "\"/\"", "+", "resource", "httpmethod", "=", "action", "else", ":", "url", "=", "\"/%s/%s\"", "...
30.5
13.2
def select_options(self, options_prefix): """ Select options from this selection, that are started with the specified prefix :param options_prefix: name prefix of options that should be selected :return: WConfigSelection """ return WConfigSelection( self.config(), self.section(), self.option_prefix() + op...
[ "def", "select_options", "(", "self", ",", "options_prefix", ")", ":", "return", "WConfigSelection", "(", "self", ".", "config", "(", ")", ",", "self", ".", "section", "(", ")", ",", "self", ".", "option_prefix", "(", ")", "+", "options_prefix", ")" ]
36.444444
18.555556
def to_gds(self, multiplier): """ Convert this object to a GDSII element. Parameters ---------- multiplier : number A number that multiplies all dimensions written in the GDSII element. Returns ------- out : string The...
[ "def", "to_gds", "(", "self", ",", "multiplier", ")", ":", "name", "=", "self", ".", "ref_cell", ".", "name", "if", "len", "(", "name", ")", "%", "2", "!=", "0", ":", "name", "=", "name", "+", "'\\0'", "data", "=", "struct", ".", "pack", "(", "...
39.785714
17.785714
def blocking_delete(self, meta=None, index_fields=None): """ Deletes and waits till the backend properly update indexes for just deleted object. meta (dict): JSON serializable meta data for logging of save operation. {'lorem': 'ipsum', 'dolar': 5} index_fields (list): Tuple l...
[ "def", "blocking_delete", "(", "self", ",", "meta", "=", "None", ",", "index_fields", "=", "None", ")", ":", "self", ".", "delete", "(", "meta", "=", "meta", ",", "index_fields", "=", "index_fields", ")", "while", "self", ".", "objects", ".", "filter", ...
53.083333
20.083333
def set_broadcast_layout(self, broadcast_id, layout_type, stylesheet=None): """ Use this method to change the layout type of a live streaming broadcast :param String broadcast_id: The ID of the broadcast that will be updated :param String layout_type: The layout type for the broadcast....
[ "def", "set_broadcast_layout", "(", "self", ",", "broadcast_id", ",", "layout_type", ",", "stylesheet", "=", "None", ")", ":", "payload", "=", "{", "'type'", ":", "layout_type", ",", "}", "if", "layout_type", "==", "'custom'", ":", "if", "stylesheet", "is", ...
39.487179
23.641026
def on_while(self, node): # ('test', 'body', 'orelse') """While blocks.""" while self.run(node.test): self._interrupt = None for tnode in node.body: self.run(tnode) if self._interrupt is not None: break if isinsta...
[ "def", "on_while", "(", "self", ",", "node", ")", ":", "# ('test', 'body', 'orelse')", "while", "self", ".", "run", "(", "node", ".", "test", ")", ":", "self", ".", "_interrupt", "=", "None", "for", "tnode", "in", "node", ".", "body", ":", "self", ".",...
34
10.5
def union(self, other, left_name="LEFT", right_name="RIGHT"): """ *Wrapper of* ``UNION`` The UNION operation is used to integrate homogeneous or heterogeneous samples of two datasets within a single dataset; for each sample of either one of the input datasets, a sample is create...
[ "def", "union", "(", "self", ",", "other", ",", "left_name", "=", "\"LEFT\"", ",", "right_name", "=", "\"RIGHT\"", ")", ":", "if", "not", "isinstance", "(", "left_name", ",", "str", ")", "or", "not", "isinstance", "(", "right_name", ",", "str", ")", ":...
47.12
26.36
def cli(ctx, hostname, username, password, config_dir, https): """Command-line interface for interacting with a WVA device""" ctx.is_root = True ctx.user_values_entered = False ctx.config_dir = os.path.abspath(os.path.expanduser(config_dir)) ctx.config = load_config(ctx) ctx.hostname = hostname ...
[ "def", "cli", "(", "ctx", ",", "hostname", ",", "username", ",", "password", ",", "config_dir", ",", "https", ")", ":", "ctx", ".", "is_root", "=", "True", "ctx", ".", "user_values_entered", "=", "False", "ctx", ".", "config_dir", "=", "os", ".", "path...
38.642857
18.214286
def _redraw(self): """ Render the command line again. (Not thread safe!) (From other threads, or if unsure, use :meth:`.CommandLineInterface.invalidate`.) """ # Only draw when no sub application was started. if self._is_running and self._sub_cli is None: self....
[ "def", "_redraw", "(", "self", ")", ":", "# Only draw when no sub application was started.", "if", "self", ".", "_is_running", "and", "self", ".", "_sub_cli", "is", "None", ":", "self", ".", "render_counter", "+=", "1", "self", ".", "renderer", ".", "render", ...
39.166667
17.5
def to_utf8(datas): """ Force utf8 string entries in the given datas """ res = datas if isinstance(datas, dict): res = {} for key, value in datas.items(): key = to_utf8(key) value = to_utf8(value) res[key] = value elif isinstance(datas, (list,...
[ "def", "to_utf8", "(", "datas", ")", ":", "res", "=", "datas", "if", "isinstance", "(", "datas", ",", "dict", ")", ":", "res", "=", "{", "}", "for", "key", ",", "value", "in", "datas", ".", "items", "(", ")", ":", "key", "=", "to_utf8", "(", "k...
22.904762
14.904762
def establish_connection(self, width=None, height=None): """Establish SSH connection to the network device Timeout will generate a NetMikoTimeoutException Authentication failure will generate a NetMikoAuthenticationException width and height are needed for Fortinet paging setting. ...
[ "def", "establish_connection", "(", "self", ",", "width", "=", "None", ",", "height", "=", "None", ")", ":", "if", "self", ".", "protocol", "==", "\"telnet\"", ":", "self", ".", "remote_conn", "=", "telnetlib", ".", "Telnet", "(", "self", ".", "host", ...
41.761905
22.238095
async def undo_check_in(self): """ Undo the check in for this participant |methcoro| Warning: |unstable| Raises: APIException """ res = await self.connection('POST', 'tournaments/{}/participants/{}/undo_check_in'.format(self._tournament_id, sel...
[ "async", "def", "undo_check_in", "(", "self", ")", ":", "res", "=", "await", "self", ".", "connection", "(", "'POST'", ",", "'tournaments/{}/participants/{}/undo_check_in'", ".", "format", "(", "self", ".", "_tournament_id", ",", "self", ".", "_id", ")", ")", ...
25.071429
26.285714
def write_traceback(logger=None, exc_info=None): """ Write the latest traceback to the log. This should be used inside an C{except} block. For example: try: dostuff() except: write_traceback(logger) Or you can pass the result of C{sys.exc_info()} to the C{e...
[ "def", "write_traceback", "(", "logger", "=", "None", ",", "exc_info", "=", "None", ")", ":", "if", "exc_info", "is", "None", ":", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "typ", ",", "exception", ",", "tb", "=", "exc_info", "traceback", "=",...
29.842105
19.526316
def get_airport_weather(self, iata, page=1, limit=100): """Retrieve the weather at an airport Given the IATA code of an airport, this method returns the weather information. Args: iata (str): The IATA code for an airport, e.g. HYD page (int): Optional page number; for u...
[ "def", "get_airport_weather", "(", "self", ",", "iata", ",", "page", "=", "1", ",", "limit", "=", "100", ")", ":", "url", "=", "AIRPORT_DATA_BASE", ".", "format", "(", "iata", ",", "str", "(", "self", ".", "AUTH_TOKEN", ")", ",", "page", ",", "limit"...
38.709677
24.387097
def options(self, request, tag): """ Render each of the options of the wrapped L{ChoiceParameter} instance. """ option = tag.patternGenerator('option') return tag[[ OptionView(index, o, option()) for (index, o) in enumerate(self.par...
[ "def", "options", "(", "self", ",", "request", ",", "tag", ")", ":", "option", "=", "tag", ".", "patternGenerator", "(", "'option'", ")", "return", "tag", "[", "[", "OptionView", "(", "index", ",", "o", ",", "option", "(", ")", ")", "for", "(", "in...
36.555556
11.444444
def _pre_mongod_server_start(server, options_override=None): """ Does necessary work before starting a server 1- An efficiency step for arbiters running with --no-journal * there is a lock file ==> * server must not have exited cleanly from last run, and does not know how to auto-...
[ "def", "_pre_mongod_server_start", "(", "server", ",", "options_override", "=", "None", ")", ":", "lock_file_path", "=", "server", ".", "get_lock_file_path", "(", ")", "no_journal", "=", "(", "server", ".", "get_cmd_option", "(", "\"nojournal\"", ")", "or", "(",...
43.483871
20.903226
def next(self): """A `next` that caches the returned results. Together with the slightly different `__iter__`, these cursors can be iterated over more than once.""" if self.__tailable: return PymongoCursor.next(self) try: ret = PymongoCursor.next(self) ...
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "__tailable", ":", "return", "PymongoCursor", ".", "next", "(", "self", ")", "try", ":", "ret", "=", "PymongoCursor", ".", "next", "(", "self", ")", "except", "StopIteration", ":", "self", ".", ...
34.230769
13
def init(opts): ''' This function gets called when the proxy starts up. For panos devices, a determination is made on the connection type and the appropriate connection details that must be cached. ''' if 'host' not in opts['proxy']: log.critical('No \'host\' key found in pillar for this...
[ "def", "init", "(", "opts", ")", ":", "if", "'host'", "not", "in", "opts", "[", "'proxy'", "]", ":", "log", ".", "critical", "(", "'No \\'host\\' key found in pillar for this proxy.'", ")", "return", "False", "if", "'apikey'", "not", "in", "opts", "[", "'pro...
43.215686
20.901961
def configure(self, argv=('',), **kwargs): """Configures TensorBoard behavior via flags. This method will populate the "flags" property with an argparse.Namespace representing flag values parsed from the provided argv list, overridden by explicit flags from remaining keyword arguments. Args: ...
[ "def", "configure", "(", "self", ",", "argv", "=", "(", "''", ",", ")", ",", "*", "*", "kwargs", ")", ":", "parser", "=", "argparse_flags", ".", "ArgumentParser", "(", "prog", "=", "'tensorboard'", ",", "description", "=", "(", "'TensorBoard is a suite of ...
41.647059
19.372549
def account_weight(self, account): """ Returns the voting weight for **account** :param account: Account to get voting weight for :type account: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.account_weight( ... account="xrb_3e3j5tkog48pnny9dmfzj1r16p...
[ "def", "account_weight", "(", "self", ",", "account", ")", ":", "account", "=", "self", ".", "_process_value", "(", "account", ",", "'account'", ")", "payload", "=", "{", "\"account\"", ":", "account", "}", "resp", "=", "self", ".", "call", "(", "'accoun...
24.434783
22.695652
async def convert_local(path, to_type): ''' Given an absolute path to a local file, convert to a given to_type ''' # Now find path between types typed_foreign_res = TypedLocalResource(path) original_ts = typed_foreign_res.typestring conversion_path = singletons.converter_graph.find_path( ...
[ "async", "def", "convert_local", "(", "path", ",", "to_type", ")", ":", "# Now find path between types", "typed_foreign_res", "=", "TypedLocalResource", "(", "path", ")", "original_ts", "=", "typed_foreign_res", ".", "typestring", "conversion_path", "=", "singletons", ...
42.043478
18.478261
def palindromic_substrings_iter(s): """ A slightly more Pythonic approach with a recursive generator """ if not s: yield [] return for i in range(len(s), 0, -1): sub = s[:i] if sub == sub[::-1]: for rest in palindromic_substrings_iter(s[i:]): ...
[ "def", "palindromic_substrings_iter", "(", "s", ")", ":", "if", "not", "s", ":", "yield", "[", "]", "return", "for", "i", "in", "range", "(", "len", "(", "s", ")", ",", "0", ",", "-", "1", ")", ":", "sub", "=", "s", "[", ":", "i", "]", "if", ...
27.5
14.166667
def get_class_module(module_name: str, class_name: str) -> Optional[str]: """ Get a sub-module of the given module which has the given class. This method wraps `utils.reflection.find_class_module method` with the following behavior: - raise error when multiple sub-modules with different classes with t...
[ "def", "get_class_module", "(", "module_name", ":", "str", ",", "class_name", ":", "str", ")", "->", "Optional", "[", "str", "]", ":", "matched_modules", ",", "erroneous_modules", "=", "find_class_module", "(", "module_name", ",", "class_name", ")", "for", "su...
47.135135
26.972973
def add_child(self, node): """! @brief Link a child node onto this object.""" node._parent = self self._children.append(node)
[ "def", "add_child", "(", "self", ",", "node", ")", ":", "node", ".", "_parent", "=", "self", "self", ".", "_children", ".", "append", "(", "node", ")" ]
36.5
8
def move_to_output_dir(work_dir, output_dir, uuid=None, files=list()): """ Moves files from work_dir to output_dir Input1: Working directory Input2: Output directory Input3: UUID to be preprended onto file name Input4: list of file names to be moved from working dir to output dir """ fo...
[ "def", "move_to_output_dir", "(", "work_dir", ",", "output_dir", ",", "uuid", "=", "None", ",", "files", "=", "list", "(", ")", ")", ":", "for", "fname", "in", "files", ":", "if", "uuid", "is", "None", ":", "shutil", ".", "move", "(", "os", ".", "p...
40.071429
22.357143
def junos_cli(command, format=None, dev_timeout=None, dest=None, **kwargs): ''' .. versionadded:: 2019.2.0 Execute a CLI command and return the output in the specified format. command The command to execute on the Junos CLI. format: ``text`` Format in which to get the CLI output (...
[ "def", "junos_cli", "(", "command", ",", "format", "=", "None", ",", "dev_timeout", "=", "None", ",", "dest", "=", "None", ",", "*", "*", "kwargs", ")", ":", "prep", "=", "_junos_prep_fun", "(", "napalm_device", ")", "# pylint: disable=undefined-variable", "...
31.5
24.970588
def get_stat(path, filename): ''' get stat ''' return os.stat(os.path.join(path, filename))
[ "def", "get_stat", "(", "path", ",", "filename", ")", ":", "return", "os", ".", "stat", "(", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", ")" ]
31
13
def push(self, path, name, tag=None): '''push an image to Singularity Registry path: should correspond to an absolte image path (or derive it) name: should be the complete uri that the user has requested to push. tag: should correspond with an image tag. This is provided to mirror Docker ''' ...
[ "def", "push", "(", "self", ",", "path", ",", "name", ",", "tag", "=", "None", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "bot", ".", "debug", "(", "\"PUSH %s\"", "%", "path", ")", "if", "not", "os", ".", "path"...
37
23.08
def strobogrammatic_in_range(low, high): """ :type low: str :type high: str :rtype: int """ res = [] count = 0 low_len = len(low) high_len = len(high) for i in range(low_len, high_len + 1): res.extend(helper2(i, i)) for perm in res: if len(perm) == low_len and...
[ "def", "strobogrammatic_in_range", "(", "low", ",", "high", ")", ":", "res", "=", "[", "]", "count", "=", "0", "low_len", "=", "len", "(", "low", ")", "high_len", "=", "len", "(", "high", ")", "for", "i", "in", "range", "(", "low_len", ",", "high_l...
24.05
16.65
def all_actions(self): """ Генератор, возвращающий все события """ count = self.get_count_action() page = 1 while True: # не цикл for, потому как не уверен, что всё норм будет с API actions = self.get_action_list(page=page) for action in actions: ...
[ "def", "all_actions", "(", "self", ")", ":", "count", "=", "self", ".", "get_count_action", "(", ")", "page", "=", "1", "while", "True", ":", "# не цикл for, потому как не уверен, что всё норм будет с API", "actions", "=", "self", ".", "get_action_list", "(", "pag...
40.083333
18.416667
def compute_from_text(self,text,beta=0.001): """ m.compute_from_text(,text,beta=0.001) -- Compute a matrix values from a text string of ambiguity codes. Use Motif_from_text utility instead to build motifs on the fly. """ prevlett = {'B':...
[ "def", "compute_from_text", "(", "self", ",", "text", ",", "beta", "=", "0.001", ")", ":", "prevlett", "=", "{", "'B'", ":", "'A'", ",", "'D'", ":", "'C'", ",", "'V'", ":", "'T'", ",", "'H'", ":", "'G'", "}", "countmat", "=", "[", "]", "text", ...
42.655172
13.551724
def send(self, from_, to, subject, text='', html='', cc=[], bcc=[], headers={}, attachments=[]): """ Send an email. """ if isinstance(to, string_types): raise TypeError('"to" parameter must be enumerable') if text == '' and html == '': raise V...
[ "def", "send", "(", "self", ",", "from_", ",", "to", ",", "subject", ",", "text", "=", "''", ",", "html", "=", "''", ",", "cc", "=", "[", "]", ",", "bcc", "=", "[", "]", ",", "headers", "=", "{", "}", ",", "attachments", "=", "[", "]", ")",...
36.3
15.3
def sep_inserter(iterable, sep): """ Insert '' between numbers in an iterable. Parameters ---------- iterable sep : str The string character to be inserted between adjacent numeric objects. Yields ------ The values of *iterable* in order, with *sep* inserted where adjacent ...
[ "def", "sep_inserter", "(", "iterable", ",", "sep", ")", ":", "try", ":", "# Get the first element. A StopIteration indicates an empty iterable.", "# Since we are controlling the types of the input, 'type' is used", "# instead of 'isinstance' for the small speed advantage it offers.", "typ...
31.674419
21.906977
def com_google_fonts_check_name_subfamilyname(ttFont, style_with_spaces, familyname_with_spaces): """ Check name table: FONT_SUBFAMILY_NAME entries. """ from fontbakery.utils import name_entry_id failed = False for name...
[ "def", "com_google_fonts_check_name_subfamilyname", "(", "ttFont", ",", "style_with_spaces", ",", "familyname_with_spaces", ")", ":", "from", "fontbakery", ".", "utils", "import", "name_entry_id", "failed", "=", "False", "for", "name", "in", "ttFont", "[", "'name'", ...
39.307692
17.717949
def _maybe_decompress_body(self): """Attempt to decompress the message body passed in using the named compression module, if specified. :rtype: bytes """ if self.content_encoding: if self.content_encoding in self._CODEC_MAP.keys(): module_name = self...
[ "def", "_maybe_decompress_body", "(", "self", ")", ":", "if", "self", ".", "content_encoding", ":", "if", "self", ".", "content_encoding", "in", "self", ".", "_CODEC_MAP", ".", "keys", "(", ")", ":", "module_name", "=", "self", ".", "_CODEC_MAP", "[", "sel...
42.625
17.25
def findAllExceptions(pathToCheck): """ Find patterns of exceptions in a file or folder. @param patternFinder: a visitor for pattern checking and save results @return: patterns of special functions and classes """ finder = PatternFinder() if os.path.isfile(pathToCheck): with open(pa...
[ "def", "findAllExceptions", "(", "pathToCheck", ")", ":", "finder", "=", "PatternFinder", "(", ")", "if", "os", ".", "path", ".", "isfile", "(", "pathToCheck", ")", ":", "with", "open", "(", "pathToCheck", ")", "as", "f", ":", "findPatternsInFile", "(", ...
38.35
12.75
def addresses(self): """ Return 3-tuple with (address, network, nicid) :return: address related information of interface as 3-tuple list :rtype: list """ addresses = [] for i in self.all_interfaces: if isinstance(i, VlanInterface): for...
[ "def", "addresses", "(", "self", ")", ":", "addresses", "=", "[", "]", "for", "i", "in", "self", ".", "all_interfaces", ":", "if", "isinstance", "(", "i", ",", "VlanInterface", ")", ":", "for", "v", "in", "i", ".", "interfaces", ":", "addresses", "."...
34.4
17.2
def get(self, block_number: BlockNumber) -> str: """Given a block number returns the hex representation of the blockhash""" if block_number in self.mapping: return self.mapping[block_number] block_hash = self.web3.eth.getBlock(block_number)['hash'] block_hash = block_hash.he...
[ "def", "get", "(", "self", ",", "block_number", ":", "BlockNumber", ")", "->", "str", ":", "if", "block_number", "in", "self", ".", "mapping", ":", "return", "self", ".", "mapping", "[", "block_number", "]", "block_hash", "=", "self", ".", "web3", ".", ...
43.222222
11.444444
def as_data_frame(self, use_pandas=True, header=True): """ Obtain the dataset as a python-local object. :param bool use_pandas: If True (default) then return the H2OFrame as a pandas DataFrame (requires that the ``pandas`` library was installed). If False, then return the contents o...
[ "def", "as_data_frame", "(", "self", ",", "use_pandas", "=", "True", ",", "header", "=", "True", ")", ":", "if", "can_use_pandas", "(", ")", "and", "use_pandas", ":", "import", "pandas", "return", "pandas", ".", "read_csv", "(", "StringIO", "(", "self", ...
52.5
30.45
def get_mean_and_stddevs(self, sctx, rctx, dctx, imt, stddev_types): """ Returns the mean and standard deviations """ # Return Distance Tables imls = self._return_tables(rctx.mag, imt, "IMLs") # Get distance vector for the given magnitude idx = numpy.searchsorted(...
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sctx", ",", "rctx", ",", "dctx", ",", "imt", ",", "stddev_types", ")", ":", "# Return Distance Tables", "imls", "=", "self", ".", "_return_tables", "(", "rctx", ".", "mag", ",", "imt", ",", "\"IMLs\"", ")",...
41.076923
13.230769
def load(self, patterns, dirs, ignore=None): """ Load objects from the filesystem into the ``paths`` dictionary. """ for path in self.find_files(patterns=patterns, dirs=dirs, ignore=ignore): data = self.read_file(path=path) if data: self.paths[pat...
[ "def", "load", "(", "self", ",", "patterns", ",", "dirs", ",", "ignore", "=", "None", ")", ":", "for", "path", "in", "self", ".", "find_files", "(", "patterns", "=", "patterns", ",", "dirs", "=", "dirs", ",", "ignore", "=", "ignore", ")", ":", "dat...
35.666667
15.666667
def _update_classifier(self, data, labels, w, classes): """Update the classifier parameters theta and bias Parameters ---------- data : list of 2D arrays, element i has shape=[voxels_i, samples_i] Each element in the list contains the fMRI data of one subject for ...
[ "def", "_update_classifier", "(", "self", ",", "data", ",", "labels", ",", "w", ",", "classes", ")", ":", "# Stack the data and labels for training the classifier", "data_stacked", ",", "labels_stacked", ",", "weights", "=", "SSSRM", ".", "_stack_list", "(", "data",...
34.188406
23.217391
def set_verbosity(self, verbose=False, print_func=None): """Switch on/off verbose mode Parameters ---------- verbose : bool switch on/off verbose mode print_func : function A function that computes statistics of initialized arrays. Takes an `N...
[ "def", "set_verbosity", "(", "self", ",", "verbose", "=", "False", ",", "print_func", "=", "None", ")", ":", "self", ".", "_verbose", "=", "verbose", "if", "print_func", "is", "None", ":", "def", "asum_stat", "(", "x", ")", ":", "\"\"\"returns |x|/size(x),...
36.8
14.95