text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def read(self, symbol, as_of=None, raw=False, **kwargs): # TODO: shall we block from_version from getting into super.read? """Read data for the named symbol. Returns a BitemporalItem object with a data and metdata element (as passed into write). Parameters ---------- sym...
[ "def", "read", "(", "self", ",", "symbol", ",", "as_of", "=", "None", ",", "raw", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# TODO: shall we block from_version from getting into super.read?", "item", "=", "self", ".", "_store", ".", "read", "(", "sym...
49.25
27.25
def _pprint(params, offset=0, printer=repr): """Pretty print the dictionary 'params' Parameters ---------- params: dict The dictionary to pretty print offset: int The offset in characters to add at the begin of each line. printer: The function to convert entries to str...
[ "def", "_pprint", "(", "params", ",", "offset", "=", "0", ",", "printer", "=", "repr", ")", ":", "# Do a multi-line justified repr:", "options", "=", "np", ".", "get_printoptions", "(", ")", "np", ".", "set_printoptions", "(", "precision", "=", "5", ",", "...
34.375
16.583333
def cmd_map(args): '''map command''' child = multiprocessing.Process(target=map_process, args=[args]) child.start()
[ "def", "cmd_map", "(", "args", ")", ":", "child", "=", "multiprocessing", ".", "Process", "(", "target", "=", "map_process", ",", "args", "=", "[", "args", "]", ")", "child", ".", "start", "(", ")" ]
31
23
def _get_curie_and_type_from_id(variant_id): """ Given a variant id, our best guess at its curie and type (snp, haplotype, etc) 'None' will be used for both curie and type for IDs that we can't process :param variant_id: :return: """ curie = None variant_...
[ "def", "_get_curie_and_type_from_id", "(", "variant_id", ")", ":", "curie", "=", "None", "variant_type", "=", "None", "# remove space before hyphens", "variant_id", "=", "re", ".", "sub", "(", "r' -'", ",", "'-'", ",", "variant_id", ")", ".", "strip", "(", ")"...
42.225
17.875
def get_nearest_edges(G, X, Y, method=None, dist=0.0001): """ Return the graph edges nearest to a list of points. Pass in points as separate vectors of X and Y coordinates. The 'kdtree' method is by far the fastest with large data sets, but only finds approximate nearest edges if working in unprojec...
[ "def", "get_nearest_edges", "(", "G", ",", "X", ",", "Y", ",", "method", "=", "None", ",", "dist", "=", "0.0001", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "if", "method", "is", "None", ":", "# calculate nearest edge one at a time for eac...
43.813008
28.853659
def plot_mesh( x, y, z, color=default_color, wireframe=True, surface=True, wrapx=False, wrapy=False, u=None, v=None, texture=None ): """Draws a 2d wireframe+surface in 3d: generalization of :any:`plot_wireframe` and :any:`plot_surface`. :param x: {x2d} :param y: {y2d} :param z: {z2d} :param col...
[ "def", "plot_mesh", "(", "x", ",", "y", ",", "z", ",", "color", "=", "default_color", ",", "wireframe", "=", "True", ",", "surface", "=", "True", ",", "wrapx", "=", "False", ",", "wrapy", "=", "False", ",", "u", "=", "None", ",", "v", "=", "None"...
29.913043
21.847826
def _set_axis_limits(self, which, lims, d, scale, reverse=False): """Private method for setting axis limits. Sets the axis limits on each axis for an individual plot. Args: which (str): The indicator of which part of the plots to adjust. This currently handles `x` a...
[ "def", "_set_axis_limits", "(", "self", ",", "which", ",", "lims", ",", "d", ",", "scale", ",", "reverse", "=", "False", ")", ":", "setattr", "(", "self", ".", "limits", ",", "which", "+", "'lims'", ",", "lims", ")", "setattr", "(", "self", ".", "l...
41.285714
24.47619
def D(self): r"""Differential operator (for gradient and divergence). Is computed by :func:`compute_differential_operator`. """ if self._D is None: self.logger.warning('The differential operator G.D is not ' 'available, we need to compute it. ...
[ "def", "D", "(", "self", ")", ":", "if", "self", ".", "_D", "is", "None", ":", "self", ".", "logger", ".", "warning", "(", "'The differential operator G.D is not '", "'available, we need to compute it. Explicitly '", "'call G.compute_differential_operator() '", "'once bef...
45.25
22.166667
def log_p(self,z): """ The unnormalized log posterior components (the quantity we want to approximate) RAO-BLACKWELLIZED! """ return np.array([self.log_p_blanket(i) for i in z])
[ "def", "log_p", "(", "self", ",", "z", ")", ":", "return", "np", ".", "array", "(", "[", "self", ".", "log_p_blanket", "(", "i", ")", "for", "i", "in", "z", "]", ")" ]
36.333333
17
def sgraph(N_clusters_max, file_name): """Runs METIS or hMETIS and returns the labels found by those (hyper-)graph partitioning algorithms. Parameters ---------- N_clusters_max : int file_name : string Returns ------- labels : array of shape (n_samples,) ...
[ "def", "sgraph", "(", "N_clusters_max", ",", "file_name", ")", ":", "if", "file_name", "==", "'DO_NOT_PROCESS'", ":", "return", "[", "]", "print", "(", "'\\n#'", ")", "k", "=", "str", "(", "N_clusters_max", ")", "out_name", "=", "file_name", "+", "'.part.'...
37.246154
21.907692
def set_glitch_filter(self, user_gpio, steady): """ Sets a glitch filter on a GPIO. Level changes on the GPIO are not reported unless the level has been stable for at least [*steady*] microseconds. The level is then reported. Level changes of less than [*steady*] micros...
[ "def", "set_glitch_filter", "(", "self", ",", "user_gpio", ",", "steady", ")", ":", "res", "=", "yield", "from", "self", ".", "_pigpio_aio_command", "(", "_PI_CMD_FG", ",", "user_gpio", ",", "steady", ")", "return", "_u2i", "(", "res", ")" ]
43.227273
16.136364
def substitute(self, text, subvars={}, checkmissing=None): '''substitute variables in a string''' if checkmissing is None: checkmissing = self.checkmissing while True: idx = text.find(self.start_var_token) if idx == -1: ret...
[ "def", "substitute", "(", "self", ",", "text", ",", "subvars", "=", "{", "}", ",", "checkmissing", "=", "None", ")", ":", "if", "checkmissing", "is", "None", ":", "checkmissing", "=", "self", ".", "checkmissing", "while", "True", ":", "idx", "=", "text...
38.8
18.228571
def push_external_commands(self, commands): """Send a HTTP request to the satellite (POST /r_un_external_commands) to send the external commands to the satellite :param results: Results list to send :type results: list :return: True on success, False on failure :rtype: b...
[ "def", "push_external_commands", "(", "self", ",", "commands", ")", ":", "logger", ".", "debug", "(", "\"Pushing %d external commands\"", ",", "len", "(", "commands", ")", ")", "return", "self", ".", "con", ".", "post", "(", "'_run_external_commands'", ",", "{...
43.545455
16
def get_scripts(self): """ Get the scripts at the path in sorted order as set in the module properties :return: a sorted list of scripts """ ret = list() for d in self.allpaths: scripts = filter(lambda x: x.startswith(self.prefix), os.listdir(d)) s...
[ "def", "get_scripts", "(", "self", ")", ":", "ret", "=", "list", "(", ")", "for", "d", "in", "self", ".", "allpaths", ":", "scripts", "=", "filter", "(", "lambda", "x", ":", "x", ".", "startswith", "(", "self", ".", "prefix", ")", ",", "os", ".",...
36.5
19.333333
def meanFracdet(map_fracdet, lon_population, lat_population, radius_population): """ Compute the mean fracdet within circular aperture (radius specified in decimal degrees) lon, lat, and radius are taken to be arrays of the same length """ nside_fracdet = healpy.npix2nside(len(map_fracdet)) map...
[ "def", "meanFracdet", "(", "map_fracdet", ",", "lon_population", ",", "lat_population", ",", "radius_population", ")", ":", "nside_fracdet", "=", "healpy", ".", "npix2nside", "(", "len", "(", "map_fracdet", ")", ")", "map_fracdet_zero", "=", "np", ".", "where", ...
67.875
38.375
def parse_map(cls, data, dist=None): """Parse a map of entry point groups""" if isinstance(data, dict): data = data.items() else: data = split_sections(data) maps = {} for group, lines in data: if group is None: if not lines: ...
[ "def", "parse_map", "(", "cls", ",", "data", ",", "dist", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "data", "=", "data", ".", "items", "(", ")", "else", ":", "data", "=", "split_sections", "(", "data", ")", "m...
36.117647
13.352941
def _plot2d(plotfunc): """ Decorator for common 2d plotting logic Also adds the 2d plot method to class _PlotMethods """ commondoc = """ Parameters ---------- darray : DataArray Must be 2 dimensional, unless creating faceted plots x : string, optional Coordinate for ...
[ "def", "_plot2d", "(", "plotfunc", ")", ":", "commondoc", "=", "\"\"\"\n Parameters\n ----------\n darray : DataArray\n Must be 2 dimensional, unless creating faceted plots\n x : string, optional\n Coordinate for x axis. If None use darray.dims[1]\n y : string, optional\...
46.003509
21.189474
def simplify(self): """ Simplify the content of a Composite merging any parts that can be and returning the new Composite as well as updating itself internally """ final_output = [] diff_last = None item_last = None for item in self._content: #...
[ "def", "simplify", "(", "self", ")", ":", "final_output", "=", "[", "]", "diff_last", "=", "None", "item_last", "=", "None", "for", "item", "in", "self", ".", "_content", ":", "# remove any undefined colors", "if", "hasattr", "(", "item", ".", "get", "(", ...
37.777778
16.444444
def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state, error): """Checks rules from the 'C++ style rules' section of cppguide.html. Most of these rules are hard to test (naming, comment style), but we do what we can. In particular we check for 2-space indents, line lengths,...
[ "def", "CheckStyle", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "file_extension", ",", "nesting_state", ",", "error", ")", ":", "# Don't use \"elided\" lines here, otherwise we can't check commented lines.", "# Don't want to use \"raw\" either, because we don't want ...
47.042735
19.376068
def _get_session(self, request): """ Authenticate the request dict :param dict request: request dict built from user input :raises SMCConnectionError: failure to connect :return: python requests session :rtype: requests.Session """ _session = requ...
[ "def", "_get_session", "(", "self", ",", "request", ")", ":", "_session", "=", "requests", ".", "session", "(", ")", "# empty session", "response", "=", "_session", ".", "post", "(", "*", "*", "request", ")", "logger", ".", "info", "(", "'Using SMC API ver...
36.631579
14
def register(self, new_outputs, *args, **kwargs): """ Register outputs and metadata. * ``initial_value`` - used in dynamic calculations * ``size`` - number of elements per timestep * ``uncertainty`` - in percent of nominal value * ``variance`` - dictionary of covariances...
[ "def", "register", "(", "self", ",", "new_outputs", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "zip", "(", "self", ".", "meta_names", ",", "args", ")", ")", "# call super method", "super", "(", "OutputRegistry", ...
44.272727
18.181818
def post_reply_groups(self, group_id, topic_id, entry_id, attachment=None, message=None): """ Post a reply. Add a reply to an entry in a discussion topic. Returns a json representation of the created reply (see documentation for 'replies' method) on success. ...
[ "def", "post_reply_groups", "(", "self", ",", "group_id", ",", "topic_id", ",", "entry_id", ",", "attachment", "=", "None", ",", "message", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH...
39.690476
24.428571
def drawBackground(self, painter, rect): """When an area of the window is exposed, we just copy out of the server-side, off-screen pixmap to that area. """ if not self.pixmap: return x1, y1, x2, y2 = rect.getCoords() width = x2 - x1 + 1 height = y2 - y...
[ "def", "drawBackground", "(", "self", ",", "painter", ",", "rect", ")", ":", "if", "not", "self", ".", "pixmap", ":", "return", "x1", ",", "y1", ",", "x2", ",", "y2", "=", "rect", ".", "getCoords", "(", ")", "width", "=", "x2", "-", "x1", "+", ...
35.769231
10.846154
def subSampleWholeColumn(spikeTrains, colIndices, cellsPerColumn, currentTS, timeWindow): """ Obtains subsample from matrix of spike trains by considering the cells in columns specified by colIndices. Thus, it returns a matrix of spike trains of cells within the same column. @param spikeTrains (array) arra...
[ "def", "subSampleWholeColumn", "(", "spikeTrains", ",", "colIndices", ",", "cellsPerColumn", ",", "currentTS", ",", "timeWindow", ")", ":", "numColumns", "=", "np", ".", "shape", "(", "colIndices", ")", "[", "0", "]", "numCells", "=", "numColumns", "*", "cel...
50.48
21.96
def run(connection): """ Parse arguments and start upload/download """ parser = argparse.ArgumentParser(description=""" Process database dumps. Either download of upload a dump file to the objectstore. downloads the latest dump and uploads with envronment and date into given container...
[ "def", "run", "(", "connection", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"\"\"\n Process database dumps.\n\n Either download of upload a dump file to the objectstore.\n\n downloads the latest dump and uploads with envronment and dat...
23.898551
19.115942
def get_dict_definition(self, dict, get_list=False): """Get the definition name of the given dict. Args: dict: dict to test. get_list: if set to true, return a list of definition that match the body. if False, only return the first. Returns: ...
[ "def", "get_dict_definition", "(", "self", ",", "dict", ",", "get_list", "=", "False", ")", ":", "list_def_candidate", "=", "[", "]", "for", "definition_name", "in", "self", ".", "specification", "[", "'definitions'", "]", ".", "keys", "(", ")", ":", "if",...
39.904762
19.809524
def gemfury(): """ Push to gem fury, a repo with private options """ # fury login # fury push dist/*.gz --as=YOUR_ACCT # fury push dist/*.whl --as=YOUR_ACCT cp = subprocess.run(("fury login --as={0}".format(GEM_FURY).split(" ")), stdout=subprocess.PIPE, stderr=subpro...
[ "def", "gemfury", "(", ")", ":", "# fury login", "# fury push dist/*.gz --as=YOUR_ACCT", "# fury push dist/*.whl --as=YOUR_ACCT", "cp", "=", "subprocess", ".", "run", "(", "(", "\"fury login --as={0}\"", ".", "format", "(", "GEM_FURY", ")", ".", "split", "(", "\" \"",...
40.047619
18.714286
def createShadowHandlerWithName(self, shadowName, isPersistentSubscribe): """ **Description** Create a device shadow handler using the specified shadow name and isPersistentSubscribe. **Syntax** .. code:: python # Create a device shadow handler for shadow named "Bot...
[ "def", "createShadowHandlerWithName", "(", "self", ",", "shadowName", ",", "isPersistentSubscribe", ")", ":", "# Create and return a deviceShadow instance", "return", "deviceShadow", ".", "deviceShadow", "(", "shadowName", ",", "isPersistentSubscribe", ",", "self", ".", "...
41.5
36.366667
def clear_high_level_pars(self): """ clears all high level pars display boxes """ for val in ['mean_type', 'dec', 'inc', 'alpha95', 'K', 'R', 'n_lines', 'n_planes']: COMMAND = """self.%s_window.SetValue("")""" % (val) exec(COMMAND) if self.ie_open: ...
[ "def", "clear_high_level_pars", "(", "self", ")", ":", "for", "val", "in", "[", "'mean_type'", ",", "'dec'", ",", "'inc'", ",", "'alpha95'", ",", "'K'", ",", "'R'", ",", "'n_lines'", ",", "'n_planes'", "]", ":", "COMMAND", "=", "\"\"\"self.%s_window.SetValue...
44.5
14.083333
def supports_version(self, guid_set): """ Returns whether a GUID set in for_appversions format is compatbile with the current supported applications list. """ # Don't let the test run if we haven't parsed install.rdf yet. if self.supported_versions is None: r...
[ "def", "supports_version", "(", "self", ",", "guid_set", ")", ":", "# Don't let the test run if we haven't parsed install.rdf yet.", "if", "self", ".", "supported_versions", "is", "None", ":", "raise", "Exception", "(", "'Early compatibility test run before install.rdf '", "'...
42.076923
19.307692
def _get_prm_file(file_name=None, search_order=None): """returns name of the prm file""" if file_name is not None: if os.path.isfile(file_name): return file_name else: logger.info("Could not find the prm-file") default_name = prms._prm_default_name prm_globtxt = ...
[ "def", "_get_prm_file", "(", "file_name", "=", "None", ",", "search_order", "=", "None", ")", ":", "if", "file_name", "is", "not", "None", ":", "if", "os", ".", "path", ".", "isfile", "(", "file_name", ")", ":", "return", "file_name", "else", ":", "log...
30.09375
19.1875
def aux(self, aux): """ Changes the aux port :params aux: Console port (integer) or None to free the port """ if aux == self._aux: return if self._aux: self._manager.port_manager.release_tcp_port(self._aux, self._project) self._aux =...
[ "def", "aux", "(", "self", ",", "aux", ")", ":", "if", "aux", "==", "self", ".", "_aux", ":", "return", "if", "self", ".", "_aux", ":", "self", ".", "_manager", ".", "port_manager", ".", "release_tcp_port", "(", "self", ".", "_aux", ",", "self", "....
42.894737
30.263158
def set_column_count(self, count): """Sets the table column count. Args: count (int): column of rows """ current_row_count = self.row_count() current_column_count = self.column_count() if count > current_column_count: cl = TableEditableItem if sel...
[ "def", "set_column_count", "(", "self", ",", "count", ")", ":", "current_row_count", "=", "self", ".", "row_count", "(", ")", "current_column_count", "=", "self", ".", "column_count", "(", ")", "if", "count", ">", "current_column_count", ":", "cl", "=", "Tab...
42.347826
11.130435
def session(self): """ Returns the current db session """ if not self.__session: self.__session = dal.get_default_session() return self.__session
[ "def", "session", "(", "self", ")", ":", "if", "not", "self", ".", "__session", ":", "self", ".", "__session", "=", "dal", ".", "get_default_session", "(", ")", "return", "self", ".", "__session" ]
35.4
11.4
def _get(auth, path, fmt, autobox=True, params=None): ''' Issue a GET request to the XNAT REST API and box the response content. Example: >>> import yaxil >>> from yaxil import Format >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> yaxil.get(auth...
[ "def", "_get", "(", "auth", ",", "path", ",", "fmt", ",", "autobox", "=", "True", ",", "params", "=", "None", ")", ":", "if", "not", "params", ":", "params", "=", "{", "}", "url", "=", "\"%s/%s\"", "%", "(", "auth", ".", "url", ".", "rstrip", "...
38.842105
22.105263
def UpsertUser(self, database_link, user, options=None): """Upserts a user. :param str database_link: The link to the database. :param dict user: The Azure Cosmos user to upsert. :param dict options: The request options for the request. :retu...
[ "def", "UpsertUser", "(", "self", ",", "database_link", ",", "user", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "{", "}", "database_id", ",", "path", "=", "self", ".", "_GetDatabaseIdWithPathForUser", "(", ...
29.708333
14.416667
def get_sentences(self, root_element, block_tags): """Returns a list of plain-text sentences by iterating through XML tags except for those listed in block_tags.""" sentences = [] for element in root_element: if not self.any_ends_with(block_tags, element.tag): ...
[ "def", "get_sentences", "(", "self", ",", "root_element", ",", "block_tags", ")", ":", "sentences", "=", "[", "]", "for", "element", "in", "root_element", ":", "if", "not", "self", ".", "any_ends_with", "(", "block_tags", ",", "element", ".", "tag", ")", ...
45.705882
16.764706
def delete_vip_request(self, vip_request_ids): """ Method to delete vip request param vip_request_ids: vip_request ids """ uri = 'api/v3/vip-request/%s/' % vip_request_ids return super(ApiVipRequest, self).delete(uri)
[ "def", "delete_vip_request", "(", "self", ",", "vip_request_ids", ")", ":", "uri", "=", "'api/v3/vip-request/%s/'", "%", "vip_request_ids", "return", "super", "(", "ApiVipRequest", ",", "self", ")", ".", "delete", "(", "uri", ")" ]
28.777778
13.888889
def run(cls, version=None): """ Test runner method; is called by parent class defined in suite.py. :param version: B2G version string to test against :return: bool PASS/FAIL status """ try: dumper = certdump() versions = dumper.nssversion_via_mari...
[ "def", "run", "(", "cls", ",", "version", "=", "None", ")", ":", "try", ":", "dumper", "=", "certdump", "(", ")", "versions", "=", "dumper", ".", "nssversion_via_marionette", "(", ")", "except", "Exception", "as", "e", ":", "# TODO: too broad exception", "...
47.608696
31.782609
def load_ref_spectra(): """ Pull out wl, flux, ivar from files of training spectra """ data_dir = "/Users/annaho/Data/AAOmega/ref_spectra" # Load the files & count the number of training objects ff = glob.glob("%s/*.txt" %data_dir) nstars = len(ff) print("We have %s training objects" %nstars) ...
[ "def", "load_ref_spectra", "(", ")", ":", "data_dir", "=", "\"/Users/annaho/Data/AAOmega/ref_spectra\"", "# Load the files & count the number of training objects", "ff", "=", "glob", ".", "glob", "(", "\"%s/*.txt\"", "%", "data_dir", ")", "nstars", "=", "len", "(", "ff"...
32.192308
16.038462
def polynomial_sign(poly_surface, degree): r"""Determine the "sign" of a polynomial on the reference triangle. .. note:: This is used **only** by :meth:`Surface._compute_valid` (which is in turn used to compute / cache the :attr:`Surface.is_valid` property). Checks if a polynomial :m...
[ "def", "polynomial_sign", "(", "poly_surface", ",", "degree", ")", ":", "# The indices where the corner nodes in a surface are.", "corner_indices", "=", "(", "0", ",", "degree", ",", "-", "1", ")", "sub_polys", "=", "[", "poly_surface", "]", "signs", "=", "set", ...
33.479452
21.890411
def upsert(self, _id, dct, attribute="_id"): """Update or Insert a new document :param str _id: The document id :param dict dct: The dictionary to set on the document :param str attribute: The attribute to query for to find the object to set this data on :returns: JSON Mongo cli...
[ "def", "upsert", "(", "self", ",", "_id", ",", "dct", ",", "attribute", "=", "\"_id\"", ")", ":", "mongo_response", "=", "yield", "self", ".", "update", "(", "_id", ",", "dct", ",", "upsert", "=", "True", ",", "attribute", "=", "attribute", ")", "rai...
43
26.083333
def humanize_size(size): """Create a nice human readable representation of the given number (understood as bytes) using the "KiB" and "MiB" suffixes to indicate kibibytes and mebibytes. A kibibyte is defined as 1024 bytes (as opposed to a kilobyte which is 1000 bytes) and a mibibyte is 1024**2 bytes (as...
[ "def", "humanize_size", "(", "size", ")", ":", "for", "factor", ",", "format_string", "in", "(", "(", "1", ",", "'%i'", ")", ",", "(", "1024", ",", "'%iKiB'", ")", ",", "(", "1024", "*", "1024", ",", "'%.1fMiB'", ")", ")", ":", "if", "size", "/",...
43.222222
15.833333
def _setOutputNames(self,rootname,suffix='_drz'): """ Define the default output filenames for drizzle products, these are based on the original rootname of the image filename should be just 1 filename, so call this in a loop for chip names contained inside a file. """...
[ "def", "_setOutputNames", "(", "self", ",", "rootname", ",", "suffix", "=", "'_drz'", ")", ":", "# Define FITS output filenames for intermediate products", "# Build names based on final DRIZZLE output name", "# where 'output' normally would have been created", "# by 'process_input()'...
36.47619
13.142857
def auth(username, password): """ Middleware implementing authentication via LOGIN. Most of the time this middleware needs to be placed *after* TLS. :param username: Username to login with. :param password: Password of the user. """ def middleware(conn): conn.login(username, pas...
[ "def", "auth", "(", "username", ",", "password", ")", ":", "def", "middleware", "(", "conn", ")", ":", "conn", ".", "login", "(", "username", ",", "password", ")", "return", "middleware" ]
28.083333
12.083333
def run(self, args): """ Load the pecan app, prepare the locals, sets the banner, and invokes the python shell. """ super(ShellCommand, self).run(args) # load the application app = self.load_app() # prepare the locals locs = dict(__name__='pecan-...
[ "def", "run", "(", "self", ",", "args", ")", ":", "super", "(", "ShellCommand", ",", "self", ")", ".", "run", "(", "args", ")", "# load the application", "app", "=", "self", ".", "load_app", "(", ")", "# prepare the locals", "locs", "=", "dict", "(", "...
32.097561
17.268293
def GetKey(self, public_key_hash): """ Get the KeyPair belonging to the public key hash. Args: public_key_hash (UInt160): a public key hash to get the KeyPair for. Returns: KeyPair: If successful, the KeyPair belonging to the public key hash, otherwise None ...
[ "def", "GetKey", "(", "self", ",", "public_key_hash", ")", ":", "if", "public_key_hash", ".", "ToBytes", "(", ")", "in", "self", ".", "_keys", ".", "keys", "(", ")", ":", "return", "self", ".", "_keys", "[", "public_key_hash", ".", "ToBytes", "(", ")",...
34.692308
23.461538
def disconnect(self, timeout_sec=TIMEOUT_SEC): """Disconnect from the device. If not disconnected within the specified timeout then an exception is thrown. """ # Remove all the services, characteristics, and descriptors from the # lists of those items. Do this before disconnect...
[ "def", "disconnect", "(", "self", ",", "timeout_sec", "=", "TIMEOUT_SEC", ")", ":", "# Remove all the services, characteristics, and descriptors from the", "# lists of those items. Do this before disconnecting because they wont't", "# be accessible afterwards.", "for", "service", "in"...
53.235294
14.941176
def subscribe(self, id, name, port): """Send a Subscribe request to a remote machine""" sub = gntp.core.GNTPSubscribe() sub.add_header('Subscriber-ID', id) sub.add_header('Subscriber-Name', name) sub.add_header('Subscriber-Port', port) if self.password: sub.set_password(self.password, self.passwordHash) ...
[ "def", "subscribe", "(", "self", ",", "id", ",", "name", ",", "port", ")", ":", "sub", "=", "gntp", ".", "core", ".", "GNTPSubscribe", "(", ")", "sub", ".", "add_header", "(", "'Subscriber-ID'", ",", "id", ")", "sub", ".", "add_header", "(", "'Subscr...
30.923077
12.307692
def filename(self): """ Name if the MOP formatted file to parse. @rtype: basestring @return: filename """ if self._filename is None: self._filename = storage.get_file(self.basename, self.ccd, ...
[ "def", "filename", "(", "self", ")", ":", "if", "self", ".", "_filename", "is", "None", ":", "self", ".", "_filename", "=", "storage", ".", "get_file", "(", "self", ".", "basename", ",", "self", ".", "ccd", ",", "ext", "=", "self", ".", "extension", ...
39.384615
14.153846
def cookie( url, name, value, expires=None): '''Return a new Cookie using a slightly more friendly API than that provided by six.moves.http_cookiejar @param name The cookie name {str} @param value The cookie value {str} @param url The URL path of the cookie {str} ...
[ "def", "cookie", "(", "url", ",", "name", ",", "value", ",", "expires", "=", "None", ")", ":", "u", "=", "urlparse", "(", "url", ")", "domain", "=", "u", ".", "hostname", "if", "'.'", "not", "in", "domain", "and", "not", "_is_ip_addr", "(", "domain...
29.837209
17.697674
def _WritePathInfo(self, client_id, path_info): """Writes a single path info record for given client.""" if client_id not in self.metadatas: raise db.UnknownClientError(client_id) path_record = self._GetPathRecord(client_id, path_info) path_record.AddPathInfo(path_info) parent_path_info = pa...
[ "def", "_WritePathInfo", "(", "self", ",", "client_id", ",", "path_info", ")", ":", "if", "client_id", "not", "in", "self", ".", "metadatas", ":", "raise", "db", ".", "UnknownClientError", "(", "client_id", ")", "path_record", "=", "self", ".", "_GetPathReco...
40.5
13.333333
def process(self, context, data): """ Default interface for microservices. Process the input data for the input context. """ self.context = context # Find the entityID for the SP that initiated the flow. try: sp_entity_id = context.state.state_dict['S...
[ "def", "process", "(", "self", ",", "context", ",", "data", ")", ":", "self", ".", "context", "=", "context", "# Find the entityID for the SP that initiated the flow.", "try", ":", "sp_entity_id", "=", "context", ".", "state", ".", "state_dict", "[", "'SATOSA_BASE...
53.182609
34.486957
def get_or_create(full_filename, headers_types=None, default_entry=''): """Load a .csv file into a CSVModel if the file exists, or create a new CSVModel with the given filename if the file does not exist. Parameters ---------- full_filename : :obj:`str` The file path...
[ "def", "get_or_create", "(", "full_filename", ",", "headers_types", "=", "None", ",", "default_entry", "=", "''", ")", ":", "# convert dictionaries to list", "if", "isinstance", "(", "headers_types", ",", "dict", ")", ":", "headers_types_list", "=", "[", "(", "k...
40.125
22.375
def mss(**kwargs): # type: (Any) -> MSSMixin """ Factory returning a proper MSS class instance. It detects the plateform we are running on and choose the most adapted mss_class to take screenshots. It then proxies its arguments to the class for instantiation. """ ...
[ "def", "mss", "(", "*", "*", "kwargs", ")", ":", "# type: (Any) -> MSSMixin", "os_", "=", "platform", ".", "system", "(", ")", ".", "lower", "(", ")", "if", "os_", "==", "\"darwin\"", ":", "from", ".", "import", "darwin", "return", "darwin", ".", "MSS"...
22.533333
21.7
def reset_stats(self, pattern): """Reset VM statistics. in pattern of type str The selection pattern. A bit similar to filename globbing. """ if not isinstance(pattern, basestring): raise TypeError("pattern can only be an instance of type basestring") se...
[ "def", "reset_stats", "(", "self", ",", "pattern", ")", ":", "if", "not", "isinstance", "(", "pattern", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"pattern can only be an instance of type basestring\"", ")", "self", ".", "_call", "(", "\"resetStats\...
33.545455
17.181818
def prt_nts(self, desc2nts, prt=sys.stdout, prtfmt=None): """Print grouped and sorted GO IDs.""" # deprecated # Set print format string if prtfmt is None: prtfmt = "{{hdr1usr01:2}} {FMT}\n".format(FMT=self.grprobj.gosubdag.prt_attr['fmt']) # 1-D: data to print is a fl...
[ "def", "prt_nts", "(", "self", ",", "desc2nts", ",", "prt", "=", "sys", ".", "stdout", ",", "prtfmt", "=", "None", ")", ":", "# deprecated", "# Set print format string", "if", "prtfmt", "is", "None", ":", "prtfmt", "=", "\"{{hdr1usr01:2}} {FMT}\\n\"", ".", "...
47.583333
20.083333
def update_liststore_image(liststore, tree_iters, col, pcs_files, dir_name, icon_size=96): '''下载文件缩略图, 并将它显示到liststore里. pcs_files - 里面包含了几个必要的字段. dir_name - 缓存目录, 下载到的图片会保存这个目录里. size - 指定图片的缩放大小, 默认是96px. ''' def update_image(filepath, tree_iter): ...
[ "def", "update_liststore_image", "(", "liststore", ",", "tree_iters", ",", "col", ",", "pcs_files", ",", "dir_name", ",", "icon_size", "=", "96", ")", ":", "def", "update_image", "(", "filepath", ",", "tree_iter", ")", ":", "try", ":", "pix", "=", "GdkPixb...
36.68
16.08
def disable_by_count(self): """ Disable the profiler if the number of disable requests matches the number of enable requests. """ if self.enable_count > 0: self.enable_count -= 1 if self.enable_count == 0: self.disable()
[ "def", "disable_by_count", "(", "self", ")", ":", "if", "self", ".", "enable_count", ">", "0", ":", "self", ".", "enable_count", "-=", "1", "if", "self", ".", "enable_count", "==", "0", ":", "self", ".", "disable", "(", ")" ]
35.625
5.5
def load(self, dataset_keys, previous_datasets=None): """Load `dataset_keys`. If `previous_datasets` is provided, do not reload those.""" all_datasets = previous_datasets or DatasetDict() datasets = DatasetDict() # Include coordinates in the list of datasets to load dsi...
[ "def", "load", "(", "self", ",", "dataset_keys", ",", "previous_datasets", "=", "None", ")", ":", "all_datasets", "=", "previous_datasets", "or", "DatasetDict", "(", ")", "datasets", "=", "DatasetDict", "(", ")", "# Include coordinates in the list of datasets to load"...
39.28
17.28
def set_color(self, group, color, pct=1): """ Sets brightness of LEDs in the given group to the values specified in color tuple. When percentage is specified, brightness of each LED is reduced proportionally. Example:: my_leds = Leds() my_leds.set_color(...
[ "def", "set_color", "(", "self", ",", "group", ",", "color", ",", "pct", "=", "1", ")", ":", "# If this is a platform without LEDs there is nothing to do", "if", "not", "self", ".", "leds", ":", "return", "color_tuple", "=", "color", "if", "isinstance", "(", "...
33.636364
19.818182
def multi_evaluate(self, x, out=None): """Evaluate log of the density to propose ``x``, namely log(q(x)) for each row in x. :param x: Matrix-like array; the proposed points. Expect i-th accessible as ``x[i]``. :param out: Vector-like array, length=...
[ "def", "multi_evaluate", "(", "self", ",", "x", ",", "out", "=", "None", ")", ":", "if", "out", "is", "None", ":", "out", "=", "_np", ".", "empty", "(", "len", "(", "x", ")", ")", "else", ":", "assert", "len", "(", "out", ")", "==", "len", "(...
25.375
21.291667
def request(self, persist_id=None): """Cancel an ongoing confirmed commit. Depends on the `:candidate` and `:confirmed-commit` capabilities. *persist-id* value must be equal to the value given in the <persist> parameter to the previous <commit> operation. """ node = new_ele("cancel-comm...
[ "def", "request", "(", "self", ",", "persist_id", "=", "None", ")", ":", "node", "=", "new_ele", "(", "\"cancel-commit\"", ")", "if", "persist_id", "is", "not", "None", ":", "sub_ele", "(", "node", ",", "\"persist-id\"", ")", ".", "text", "=", "persist_i...
44.4
19.7
def to_representation(self, instance): """ Object instance -> Dict of primitive datatypes. """ ret = OrderedDict() readable_fields = [ field for field in self.fields.values() if not field.write_only ] for field in readable_fields: ...
[ "def", "to_representation", "(", "self", ",", "instance", ")", ":", "ret", "=", "OrderedDict", "(", ")", "readable_fields", "=", "[", "field", "for", "field", "in", "self", ".", "fields", ".", "values", "(", ")", "if", "not", "field", ".", "write_only", ...
29.666667
17.333333
def write_chunk(outfile, tag, data=b''): """ Write a PNG chunk to the output file, including length and checksum. """ data = bytes(data) # http://www.w3.org/TR/PNG/#5Chunk-layout outfile.write(struct.pack("!I", len(data))) outfile.write(tag) outfile.write(data) checksum = zlib.c...
[ "def", "write_chunk", "(", "outfile", ",", "tag", ",", "data", "=", "b''", ")", ":", "data", "=", "bytes", "(", "data", ")", "# http://www.w3.org/TR/PNG/#5Chunk-layout", "outfile", ".", "write", "(", "struct", ".", "pack", "(", "\"!I\"", ",", "len", "(", ...
28.8
12.266667
def _slice(self, slicer): """ Return a slice of myself. For internal compatibility with numpy arrays. """ # only allow 1 dimensional slicing, but can # in a 2-d case be passd (slice(None),....) if isinstance(slicer, tuple) and len(slicer) == 2: if no...
[ "def", "_slice", "(", "self", ",", "slicer", ")", ":", "# only allow 1 dimensional slicing, but can", "# in a 2-d case be passd (slice(None),....)", "if", "isinstance", "(", "slicer", ",", "tuple", ")", "and", "len", "(", "slicer", ")", "==", "2", ":", "if", "not"...
35.529412
17.411765
def bbox_to_ybox(bbox): """Convert from corner bounding box to center/shape""" return [ (bbox[1] + bbox[3]) / 2, (bbox[0] + bbox[2]) / 2, (bbox[3] - bbox[1]), (bbox[2] - bbox[0]), ]
[ "def", "bbox_to_ybox", "(", "bbox", ")", ":", "return", "[", "(", "bbox", "[", "1", "]", "+", "bbox", "[", "3", "]", ")", "/", "2", ",", "(", "bbox", "[", "0", "]", "+", "bbox", "[", "2", "]", ")", "/", "2", ",", "(", "bbox", "[", "3", ...
29.25
13
def post(self, request): """Log out the user.""" logout_url = self.redirect_url if is_authenticated(request.user): # Check if a method exists to build the URL to log out the user # from the OP. logout_from_op = self.get_settings('OIDC_OP_LOGOUT_URL_METHOD', '...
[ "def", "post", "(", "self", ",", "request", ")", ":", "logout_url", "=", "self", ".", "redirect_url", "if", "is_authenticated", "(", "request", ".", "user", ")", ":", "# Check if a method exists to build the URL to log out the user", "# from the OP.", "logout_from_op", ...
36.8
20.066667
def solveAndNotify(self, request): """Notifies the owner of the current request (so, the user doing the exercise) that they've solved the exercise, and mark it as solved in the database. """ remote = request.transport.remote withThisIdentifier = Exercise.identifier == se...
[ "def", "solveAndNotify", "(", "self", ",", "request", ")", ":", "remote", "=", "request", ".", "transport", ".", "remote", "withThisIdentifier", "=", "Exercise", ".", "identifier", "==", "self", ".", "exerciseIdentifier", "exercise", "=", "self", ".", "store",...
44.4
14.7
def Modified(self): """Also updates the state of the containing oneof in the parent message.""" try: self._parent_message_weakref._UpdateOneofState(self._field) super(_OneofListener, self).Modified() except ReferenceError: pass
[ "def", "Modified", "(", "self", ")", ":", "try", ":", "self", ".", "_parent_message_weakref", ".", "_UpdateOneofState", "(", "self", ".", "_field", ")", "super", "(", "_OneofListener", ",", "self", ")", ".", "Modified", "(", ")", "except", "ReferenceError", ...
35.857143
18
def upsert_all(engine, table, data): """ Update data by primary key columns. If not able to update, do insert. Example:: # suppose in database we already have {"id": 1, "name": "Alice"} >>> data = [ ... {"id": 1, "name": "Bob"}, # this will be updated ... {"id": 2, ...
[ "def", "upsert_all", "(", "engine", ",", "table", ",", "data", ")", ":", "update_all", "(", "engine", ",", "table", ",", "data", ",", "upsert", "=", "True", ")" ]
33.047619
21.809524
def query(self): """A MultiDictProxy representing parsed query parameters in decoded representation. Empty value if URL has no query part. """ ret = MultiDict(parse_qsl(self.raw_query_string, keep_blank_values=True)) return MultiDictProxy(ret)
[ "def", "query", "(", "self", ")", ":", "ret", "=", "MultiDict", "(", "parse_qsl", "(", "self", ".", "raw_query_string", ",", "keep_blank_values", "=", "True", ")", ")", "return", "MultiDictProxy", "(", "ret", ")" ]
31.666667
19.222222
def _send_content(self, content, connection): """ Send a content array from the connection """ if connection: if connection.async: callback = connection.callbacks['remote'] if callback: callback(self, self.parent_object, content) ...
[ "def", "_send_content", "(", "self", ",", "content", ",", "connection", ")", ":", "if", "connection", ":", "if", "connection", ".", "async", ":", "callback", "=", "connection", ".", "callbacks", "[", "'remote'", "]", "if", "callback", ":", "callback", "(",...
31.933333
20.333333
def vol_tehrahedron(poly): """volume of a irregular tetrahedron""" p_a = np.array(poly[0]) p_b = np.array(poly[1]) p_c = np.array(poly[2]) p_d = np.array(poly[3]) return abs(np.dot( np.subtract(p_a, p_d), np.cross( np.subtract(p_b, p_d), np.subtract(p_c, p...
[ "def", "vol_tehrahedron", "(", "poly", ")", ":", "p_a", "=", "np", ".", "array", "(", "poly", "[", "0", "]", ")", "p_b", "=", "np", ".", "array", "(", "poly", "[", "1", "]", ")", "p_c", "=", "np", ".", "array", "(", "poly", "[", "2", "]", "...
29.090909
11.181818
def permute(self, qubits: Qubits) -> 'QubitVector': """Permute the order of the qubits""" if qubits == self.qubits: return self N = self.qubit_nb assert len(qubits) == N # Will raise a value error if qubits don't match indices = [self.qubits.index(q) for q ...
[ "def", "permute", "(", "self", ",", "qubits", ":", "Qubits", ")", "->", "'QubitVector'", ":", "if", "qubits", "==", "self", ".", "qubits", ":", "return", "self", "N", "=", "self", ".", "qubit_nb", "assert", "len", "(", "qubits", ")", "==", "N", "# Wi...
32.058824
17.882353
def update_doc(input, **params): """ Updates document with value from another document :param input: :param params: :return: """ PARAM_SOURCE = 'source' SOURCE_COL = 'src.col' SOURCE_FIELD = 'src.field' PARAM_RESULT = 'result' res = input[params.get(PARAM_RESULT)] for sr...
[ "def", "update_doc", "(", "input", ",", "*", "*", "params", ")", ":", "PARAM_SOURCE", "=", "'source'", "SOURCE_COL", "=", "'src.col'", "SOURCE_FIELD", "=", "'src.field'", "PARAM_RESULT", "=", "'result'", "res", "=", "input", "[", "params", ".", "get", "(", ...
26.5625
15.3125
def rename_notes_folder(self, title, folderid): """Rename a folder :param title: New title of the folder :param folderid: The UUID of the folder to rename """ if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Aut...
[ "def", "rename_notes_folder", "(", "self", ",", "title", ",", "folderid", ")", ":", "if", "self", ".", "standard_grant_type", "is", "not", "\"authorization_code\"", ":", "raise", "DeviantartError", "(", "\"Authentication through Authorization Code (Grant Type) is required i...
33.5
28.6875
def resize_bytes(self, size): """ Resize the buffer (in-place, deferred operation) Parameters ---------- size : integer New buffer size in bytes Notes ----- This clears any pending operations. """ Buffer.resize_bytes(self, size) ...
[ "def", "resize_bytes", "(", "self", ",", "size", ")", ":", "Buffer", ".", "resize_bytes", "(", "self", ",", "size", ")", "self", ".", "_size", "=", "size", "//", "self", ".", "itemsize" ]
24.571429
15.5
def disk_clone(hypervisor, identifier, storage_pool, configuration, image, logger): """Disk image cloning. Given an original disk image it clones it into a new one, the clone will be created within the storage pool. The following values are set into the disk XML configuration: * name * target...
[ "def", "disk_clone", "(", "hypervisor", ",", "identifier", ",", "storage_pool", ",", "configuration", ",", "image", ",", "logger", ")", ":", "cow", "=", "configuration", ".", "get", "(", "'copy_on_write'", ",", "False", ")", "try", ":", "volume", "=", "hyp...
34.684211
23.131579
def get_doc(node): """ Return a node's documentation as a string, pulling from annotations or constructing a simple fake as needed. """ res = " ".join(get_doc_annotations(node)) if not res: res = "(%s)" % node.__class__.__name__.lower() return res
[ "def", "get_doc", "(", "node", ")", ":", "res", "=", "\" \"", ".", "join", "(", "get_doc_annotations", "(", "node", ")", ")", "if", "not", "res", ":", "res", "=", "\"(%s)\"", "%", "node", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", "...
30.555556
14.111111
def join_swarm(self, remote_addrs, join_token, listen_addr='0.0.0.0:2377', advertise_addr=None): """ Make this Engine join a swarm that has already been created. Args: remote_addrs (:py:class:`list`): Addresses of one or more manager nodes already ...
[ "def", "join_swarm", "(", "self", ",", "remote_addrs", ",", "join_token", ",", "listen_addr", "=", "'0.0.0.0:2377'", ",", "advertise_addr", "=", "None", ")", ":", "data", "=", "{", "\"RemoteAddrs\"", ":", "remote_addrs", ",", "\"ListenAddr\"", ":", "listen_addr"...
45.394737
21.657895
def tree_node_to_xml(self, parent, item): """Converts a treeview item and children to xml nodes""" tree = self.treeview data = self.treedata[item] node = data.to_xml_node() children = tree.get_children(item) for child in children: cnode = ET.Element('child')...
[ "def", "tree_node_to_xml", "(", "self", ",", "parent", ",", "item", ")", ":", "tree", "=", "self", ".", "treeview", "data", "=", "self", ".", "treedata", "[", "item", "]", "node", "=", "data", ".", "to_xml_node", "(", ")", "children", "=", "tree", "....
29.933333
14.2
async def sort(self, request, reverse=False): """Sort collection.""" return sorted( self.collection, key=lambda o: getattr(o, self.columns_sort, 0), reverse=reverse)
[ "async", "def", "sort", "(", "self", ",", "request", ",", "reverse", "=", "False", ")", ":", "return", "sorted", "(", "self", ".", "collection", ",", "key", "=", "lambda", "o", ":", "getattr", "(", "o", ",", "self", ".", "columns_sort", ",", "0", "...
47.5
19
def stripboxplot(x, y, data, ax=None, significant=None, **kwargs): """ Overlay a stripplot on top of a boxplot. """ ax = sb.boxplot( x=x, y=y, data=data, ax=ax, fliersize=0, **kwargs ) plot = sb.stripplot( x=x, y=y, data=da...
[ "def", "stripboxplot", "(", "x", ",", "y", ",", "data", ",", "ax", "=", "None", ",", "significant", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ax", "=", "sb", ".", "boxplot", "(", "x", "=", "x", ",", "y", "=", "y", ",", "data", "=", "...
20.758621
21.310345
def asserts(self, *args, **kwargs): """Wraps match method and places under an assertion. Override this for higher-level control, such as returning a custom object for additional validation (e.g. expect().to.change()) """ result = self.match(*args, **kwargs) self.expect(resul...
[ "def", "asserts", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "self", ".", "match", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "expect", "(", "result", ")", "return", "result" ]
48.428571
13.714286
def check_AP_phase(abf,n=10): """X""" timePoints=get_AP_timepoints(abf)[:10] #first 10 if len(timePoints)==0: return swhlab.plot.new(abf,True,title="AP phase (n=%d)"%n,xlabel="mV",ylabel="V/S") Ys=abf.get_data_around(timePoints,msDeriv=.1,padding=.005) Xs=abf.get_data_around(timePoints,p...
[ "def", "check_AP_phase", "(", "abf", ",", "n", "=", "10", ")", ":", "timePoints", "=", "get_AP_timepoints", "(", "abf", ")", "[", ":", "10", "]", "#first 10", "if", "len", "(", "timePoints", ")", "==", "0", ":", "return", "swhlab", ".", "plot", ".", ...
40
15.25
def ref_build_and_muscle_chunk(data, sample): """ 1. Run bedtools to get all overlapping regions 2. Parse out reads from regions using pysam and dump into chunk files. We measure it out to create 10 chunk files per sample. 3. If we really wanted to speed this up, though it is pretty fast alrea...
[ "def", "ref_build_and_muscle_chunk", "(", "data", ",", "sample", ")", ":", "## get regions using bedtools", "regions", "=", "bedtools_merge", "(", "data", ",", "sample", ")", ".", "strip", "(", ")", ".", "split", "(", "\"\\n\"", ")", "nregions", "=", "len", ...
41.7
22.6625
def _pci_seq(ipmicmd): """Get output of ipmiraw command and the ordinal numbers. :param ipmicmd: IPMI command object. :returns: List of tuple contain ordinal number and output of ipmiraw command. """ for i in range(1, 0xff + 1): try: res = _send_raw_command(ipmicmd, GET_PCI ...
[ "def", "_pci_seq", "(", "ipmicmd", ")", ":", "for", "i", "in", "range", "(", "1", ",", "0xff", "+", "1", ")", ":", "try", ":", "res", "=", "_send_raw_command", "(", "ipmicmd", ",", "GET_PCI", "%", "hex", "(", "i", ")", ")", "yield", "i", ",", "...
37.333333
17.866667
def process_input(self, question): """ takes a question and returns the best answer based on known skills """ ans = '' if self.status == 'EXIT': print('bye') sys.exit() if '?' in question: ans = self.info.find_answer(question) ...
[ "def", "process_input", "(", "self", ",", "question", ")", ":", "ans", "=", "''", "if", "self", ".", "status", "==", "'EXIT'", ":", "print", "(", "'bye'", ")", "sys", ".", "exit", "(", ")", "if", "'?'", "in", "question", ":", "ans", "=", "self", ...
31.958333
14.291667
def load(settings=None, namespace=None, prefix=None): """ Call this guy to init pyaas stuffs :param settings: Alternative name of ini file to load :param namespace: Namespace is used to derive paths, pass '' for an empty namespace :param prefix: The root path of the app :return: None """ ...
[ "def", "load", "(", "settings", "=", "None", ",", "namespace", "=", "None", ",", "prefix", "=", "None", ")", ":", "parent", "=", "pyaas", ".", "util", ".", "getParent", "(", ")", "script_name", "=", "os", ".", "path", ".", "basename", "(", "parent", ...
30.130435
19.347826
def is_literal_or_name(value): """Return True if value is a literal or a name.""" try: ast.literal_eval(value) return True except (SyntaxError, ValueError): pass if value.strip() in ['dict()', 'list()', 'set()']: return True # Support removal of variables on the rig...
[ "def", "is_literal_or_name", "(", "value", ")", ":", "try", ":", "ast", ".", "literal_eval", "(", "value", ")", "return", "True", "except", "(", "SyntaxError", ",", "ValueError", ")", ":", "pass", "if", "value", ".", "strip", "(", ")", "in", "[", "'dic...
31.142857
19.428571
def start(name): ''' Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' cmd = '/usr/sbin/svcadm enable -s -t {0}'.format(name) retcode = __salt__['cmd.retcode'](cmd, python_shell=False) if not retcode: return True ...
[ "def", "start", "(", "name", ")", ":", "cmd", "=", "'/usr/sbin/svcadm enable -s -t {0}'", ".", "format", "(", "name", ")", "retcode", "=", "__salt__", "[", "'cmd.retcode'", "]", "(", "cmd", ",", "python_shell", "=", "False", ")", "if", "not", "retcode", ":...
31.909091
23.272727
def strain_in_plane(self, **kwargs): ''' Returns the in-plane strain assuming no lattice relaxation, which is positive for tensile strain and negative for compressive strain. ''' if self._strain_out_of_plane is not None: return ((self._strain_out_of_plane / -2.) * ...
[ "def", "strain_in_plane", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_strain_out_of_plane", "is", "not", "None", ":", "return", "(", "(", "self", ".", "_strain_out_of_plane", "/", "-", "2.", ")", "*", "(", "self", ".", "unstrai...
46.363636
22.545455
def get_sql(self, debug=False, use_cache=True): """ Generates the sql for this query window and returns the sql as a string. :type debug: bool :param debug: If True, the sql will be returned in a format that is easier to read and debug. Defaults to False :type use_c...
[ "def", "get_sql", "(", "self", ",", "debug", "=", "False", ",", "use_cache", "=", "True", ")", ":", "# TODO: implement caching and debug", "sql", "=", "''", "sql", "+=", "self", ".", "build_partition_by_fields", "(", ")", "sql", "+=", "self", ".", "build_ord...
36.08
22.48
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'dbpedia_resource') and self.dbpedia_resource is not None: _dic...
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'name'", ")", "and", "self", ".", "name", "is", "not", "None", ":", "_dict", "[", "'name'", "]", "=", "self", ".", "name", "if", "hasattr", "(",...
44.181818
17
def _parse_file(self, file_obj): """Directly read from file handler. Note that this will move the file pointer. """ byte_data = file_obj.read(self.size) self._parse_byte_data(byte_data)
[ "def", "_parse_file", "(", "self", ",", "file_obj", ")", ":", "byte_data", "=", "file_obj", ".", "read", "(", "self", ".", "size", ")", "self", ".", "_parse_byte_data", "(", "byte_data", ")" ]
27.5
12.75
def update_user(self, auth, username, update): """ Updates the user with username ``username`` according to ``update``. :param auth.Authentication auth: authentication object, must be admin-level :param str username: username of user to update :param GogsUserUpdate update: a ``G...
[ "def", "update_user", "(", "self", ",", "auth", ",", "username", ",", "update", ")", ":", "path", "=", "\"/admin/users/{}\"", ".", "format", "(", "username", ")", "response", "=", "self", ".", "patch", "(", "path", ",", "auth", "=", "auth", ",", "data"...
49.8
22.066667
def locations_for(self, city_name, country=None, matching='nocase'): """ Returns a list of Location objects corresponding to the int IDs and relative toponyms and 2-chars country of the cities matching the provided city name. The rule for identifying matchings is according to the...
[ "def", "locations_for", "(", "self", ",", "city_name", ",", "country", "=", "None", ",", "matching", "=", "'nocase'", ")", ":", "if", "not", "city_name", ":", "return", "[", "]", "if", "matching", "not", "in", "self", ".", "MATCHINGS", ":", "raise", "V...
55.275862
22.172414
def file_md5(f, size=8192): "Calculates the MD5 of a file." md5 = hashlib.md5() while True: data = f.read(size) if not data: break md5.update(data) return md5.hexdigest()
[ "def", "file_md5", "(", "f", ",", "size", "=", "8192", ")", ":", "md5", "=", "hashlib", ".", "md5", "(", ")", "while", "True", ":", "data", "=", "f", ".", "read", "(", "size", ")", "if", "not", "data", ":", "break", "md5", ".", "update", "(", ...
23.777778
16.222222
def _load_init(self, data, ctx): """(Re)initializes by loading from data.""" if self.shape: for self_dim, data_dim in zip(self.shape, data.shape): assert self_dim in (0, data_dim), \ "Failed loading Parameter '%s' from saved params: " \ ...
[ "def", "_load_init", "(", "self", ",", "data", ",", "ctx", ")", ":", "if", "self", ".", "shape", ":", "for", "self_dim", ",", "data_dim", "in", "zip", "(", "self", ".", "shape", ",", "data", ".", "shape", ")", ":", "assert", "self_dim", "in", "(", ...
49.685714
18