text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def gaussian(x, a, b, c, d=0): ''' a -> height of the curve's peak b -> position of the center of the peak c -> standard deviation or Gaussian RMS width d -> offset ''' return a * np.exp( -(((x-b)**2 )/ (2*(c**2))) ) + d
[ "def", "gaussian", "(", "x", ",", "a", ",", "b", ",", "c", ",", "d", "=", "0", ")", ":", "return", "a", "*", "np", ".", "exp", "(", "-", "(", "(", "(", "x", "-", "b", ")", "**", "2", ")", "/", "(", "2", "*", "(", "c", "**", "2", ")"...
31.5
0.023166
def profiling(self): """A generator which profiles then broadcasts the result. Implement sleeping loop using this:: def profile_periodically(self): for __ in self.profiling(): time.sleep(self.interval) """ self._log_profiler_started() ...
[ "def", "profiling", "(", "self", ")", ":", "self", ".", "_log_profiler_started", "(", ")", "while", "self", ".", "clients", ":", "try", ":", "self", ".", "profiler", ".", "start", "(", ")", "except", "RuntimeError", ":", "pass", "# should sleep.", "yield",...
33.628571
0.001652
def linear_smooth(t, y, dy, span=None, cv=True, t_out=None, span_out=None, period=None): """Perform a linear smooth of the data Parameters ---------- t, y, dy : array_like time, value, and error in value of the input data span : array_like the integer spans of the ...
[ "def", "linear_smooth", "(", "t", ",", "y", ",", "dy", ",", "span", "=", "None", ",", "cv", "=", "True", ",", "t_out", "=", "None", ",", "span_out", "=", "None", ",", "period", "=", "None", ")", ":", "t_input", "=", "t", "prep", "=", "_prep_smoot...
36.846154
0.000508
def cmd_import(*args): """ Arguments: <file_or_folder> [<file_or_folder> [...]] [-- [--no_ocr] [--no_label_guessing] [--append <document_id>]] Import a file or a PDF folder. OCR is run by default on images and on PDF pages without text (PDF containing only images) Please keep i...
[ "def", "cmd_import", "(", "*", "args", ")", ":", "guess_labels", "=", "True", "ocr", "=", "pyocr", ".", "get_available_tools", "(", ")", "docid", "=", "None", "doc", "=", "None", "args", "=", "list", "(", "args", ")", "if", "len", "(", "ocr", ")", ...
28.504854
0.000329
def _get_colors(n): """Returns n unique and "evenly" spaced colors for the backgrounds of the projects. Args: n (int): The number of unique colors wanted. Returns: colors (list of str): The colors in hex form. """ import matplotlib.pyplot as plt from matplotlib.colors impo...
[ "def", "_get_colors", "(", "n", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "from", "matplotlib", ".", "colors", "import", "rgb2hex", "as", "r2h", "from", "numpy", "import", "linspace", "cols", "=", "linspace", "(", "0.05", ",", ".95", ...
25.944444
0.002066
def delete_user(email, profile="splunk"): ''' Delete a splunk user by email CLI Example: salt myminion splunk_user.delete 'user@example.com' ''' client = _get_splunk(profile) user = list_users(profile).get(email) if user: try: client.users.delete(user.name) ...
[ "def", "delete_user", "(", "email", ",", "profile", "=", "\"splunk\"", ")", ":", "client", "=", "_get_splunk", "(", "profile", ")", "user", "=", "list_users", "(", "profile", ")", ".", "get", "(", "email", ")", "if", "user", ":", "try", ":", "client", ...
21.26087
0.001957
def perform_request_vote(cmt_id, client_ip_address, value, uid=-1): """ Vote positively or negatively for a comment/review :param cmt_id: review id :param value: +1 for voting positively -1 for voting negatively :return: integer 1 if successful, integer 0 if not """ cmt_id ...
[ "def", "perform_request_vote", "(", "cmt_id", ",", "client_ip_address", ",", "value", ",", "uid", "=", "-", "1", ")", ":", "cmt_id", "=", "wash_url_argument", "(", "cmt_id", ",", "'int'", ")", "client_ip_address", "=", "wash_url_argument", "(", "client_ip_addres...
47.5
0.000737
def do_step(self, values, xy_values,coeff, width): """Calculates forces between two diagrams and pushes them apart by tenth of width""" forces = {k:[] for k,i in enumerate(xy_values)} for (index1, value1), (index2,value2) in combinations(enumerate(xy_values),2): f = self.calc_2d_forc...
[ "def", "do_step", "(", "self", ",", "values", ",", "xy_values", ",", "coeff", ",", "width", ")", ":", "forces", "=", "{", "k", ":", "[", "]", "for", "k", ",", "i", "in", "enumerate", "(", "xy_values", ")", "}", "for", "(", "index1", ",", "value1"...
56.346154
0.02349
def add(self, key, value=None): """ Adds the new key to this enumerated type. :param key | <str> """ if value is None: value = 2 ** (len(self)) self[key] = value setattr(self, key, self[key]) return value
[ "def", "add", "(", "self", ",", "key", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "value", "=", "2", "**", "(", "len", "(", "self", ")", ")", "self", "[", "key", "]", "=", "value", "setattr", "(", "self", ",", "key...
23.666667
0.010169
def new_section(self, name, params=None): """Return a new section""" self.sections[name.lower()] = SectionTerm(None, name, term_args=params, doc=self) # Set the default arguments s = self.sections[name.lower()] if name.lower() in self.decl_sections: s.args = self.de...
[ "def", "new_section", "(", "self", ",", "name", ",", "params", "=", "None", ")", ":", "self", ".", "sections", "[", "name", ".", "lower", "(", ")", "]", "=", "SectionTerm", "(", "None", ",", "name", ",", "term_args", "=", "params", ",", "doc", "=",...
32.818182
0.008086
def audio_outputs(self): """ :return: A list of audio output :class:`Ports`. """ return self.client.get_ports(is_audio=True, is_physical=True, is_output=True)
[ "def", "audio_outputs", "(", "self", ")", ":", "return", "self", ".", "client", ".", "get_ports", "(", "is_audio", "=", "True", ",", "is_physical", "=", "True", ",", "is_output", "=", "True", ")" ]
37.2
0.015789
def copy(self): """ Creates a copy of model """ return self.__class__(field_type=self.get_field_type(), data=self.export_data())
[ "def", "copy", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "field_type", "=", "self", ".", "get_field_type", "(", ")", ",", "data", "=", "self", ".", "export_data", "(", ")", ")" ]
31.2
0.01875
def _clean_spaces_backtick_quoted_names(tok): """Clean up a column name if surrounded by backticks. Backtick quoted string are indicated by a certain tokval value. If a string is a backtick quoted token it will processed by :func:`_remove_spaces_column_name` so that the parser can find this string ...
[ "def", "_clean_spaces_backtick_quoted_names", "(", "tok", ")", ":", "toknum", ",", "tokval", "=", "tok", "if", "toknum", "==", "_BACKTICK_QUOTED_STRING", ":", "return", "tokenize", ".", "NAME", ",", "_remove_spaces_column_name", "(", "tokval", ")", "return", "tokn...
35.043478
0.001208
def relpath(self, path, start=None): """We mostly rely on the native implementation and adapt the path separator.""" if not path: raise ValueError("no path specified") path = make_string_path(path) if start is not None: start = make_string_path(start) ...
[ "def", "relpath", "(", "self", ",", "path", ",", "start", "=", "None", ")", ":", "if", "not", "path", ":", "raise", "ValueError", "(", "\"no path specified\"", ")", "path", "=", "make_string_path", "(", "path", ")", "if", "start", "is", "not", "None", ...
48.85
0.002008
def inv_shift_rows(state): """ Transformation in the Inverse Cipher that is the inverse of ShiftRows(). """ state = state.reshape(4, 4, 8) return fcat( state[0][0], state[3][1], state[2][2], state[1][3], state[1][0], state[0][1], state[3][2], state[2][3], state[2][0], state[1...
[ "def", "inv_shift_rows", "(", "state", ")", ":", "state", "=", "state", ".", "reshape", "(", "4", ",", "4", ",", "8", ")", "return", "fcat", "(", "state", "[", "0", "]", "[", "0", "]", ",", "state", "[", "3", "]", "[", "1", "]", ",", "state",...
36.909091
0.002404
async def get_profile(self, *tags): '''Get a profile object using tag(s)''' url = '{0.BASE}/profile/{1}'.format(self, ','.join(tags)) data = await self.request(url) if isinstance(data, list): return [Profile(self, c) for c in data] else: ...
[ "async", "def", "get_profile", "(", "self", ",", "*", "tags", ")", ":", "url", "=", "'{0.BASE}/profile/{1}'", ".", "format", "(", "self", ",", "','", ".", "join", "(", "tags", ")", ")", "data", "=", "await", "self", ".", "request", "(", "url", ")", ...
33.7
0.008671
def initrole(self, check=True): """ Called to set default password login for systems that do not yet have passwordless login setup. """ if self.env.original_user is None: self.env.original_user = self.genv.user if self.env.original_key_filename is None: ...
[ "def", "initrole", "(", "self", ",", "check", "=", "True", ")", ":", "if", "self", ".", "env", ".", "original_user", "is", "None", ":", "self", ".", "env", ".", "original_user", "=", "self", ".", "genv", ".", "user", "if", "self", ".", "env", ".", ...
41.775281
0.002365
def init_controller(url): """Initialize a controller. Provides a single global controller for applications that can't do this themselves """ # pylint: disable=global-statement global _VERA_CONTROLLER created = False if _VERA_CONTROLLER is None: _VERA_CONTROLLER = VeraController(...
[ "def", "init_controller", "(", "url", ")", ":", "# pylint: disable=global-statement", "global", "_VERA_CONTROLLER", "created", "=", "False", "if", "_VERA_CONTROLLER", "is", "None", ":", "_VERA_CONTROLLER", "=", "VeraController", "(", "url", ")", "created", "=", "Tru...
29
0.002387
def geodetic_to_ecef(latitude, longitude, altitude): """Convert WGS84 geodetic coordinates into ECEF Parameters ---------- latitude : float or array_like Geodetic latitude (degrees) longitude : float or array_like Geodetic longitude (degrees) altitude : float or array_like ...
[ "def", "geodetic_to_ecef", "(", "latitude", ",", "longitude", ",", "altitude", ")", ":", "ellip", "=", "np", ".", "sqrt", "(", "1.", "-", "earth_b", "**", "2", "/", "earth_a", "**", "2", ")", "r_n", "=", "earth_a", "/", "np", ".", "sqrt", "(", "1."...
31.241379
0.008565
def check_required_keys(self, required_keys): '''raise InsufficientGraftMPackageException if this package does not conform to the standard of the given package''' h = self._contents_hash for key in required_keys: if key not in h: raise InsufficientGraftMPackag...
[ "def", "check_required_keys", "(", "self", ",", "required_keys", ")", ":", "h", "=", "self", ".", "_contents_hash", "for", "key", "in", "required_keys", ":", "if", "key", "not", "in", "h", ":", "raise", "InsufficientGraftMPackageException", "(", "\"Package missi...
50.857143
0.008287
def _get_csv_fieldnames(csv_reader): """Finds fieldnames in Polarion exported csv file.""" fieldnames = [] for row in csv_reader: for col in row: field = ( col.strip() .replace('"', "") .replace(" ", "") .replace("(", "") ...
[ "def", "_get_csv_fieldnames", "(", "csv_reader", ")", ":", "fieldnames", "=", "[", "]", "for", "row", "in", "csv_reader", ":", "for", "col", "in", "row", ":", "field", "=", "(", "col", ".", "strip", "(", ")", ".", "replace", "(", "'\"'", ",", "\"\"",...
27.371429
0.001008
def _ReadTablesArray(self, file_object, tables_array_offset): """Reads the tables array. Args: file_object (file): file-like object. tables_array_offset (int): offset of the tables array relative to the start of the file. Returns: dict[int, KeychainDatabaseTable]: tables per id...
[ "def", "_ReadTablesArray", "(", "self", ",", "file_object", ",", "tables_array_offset", ")", ":", "# TODO: implement https://github.com/libyal/dtfabric/issues/12 and update", "# keychain_tables_array definition.", "data_type_map", "=", "self", ".", "_GetDataTypeMap", "(", "'keych...
32.148148
0.002237
def _register_lltd_specific_class(*attr_types): """This can be used as a class decorator; if we want to support Python 2.5, we have to replace @_register_lltd_specific_class(x[, y[, ...]]) class LLTDAttributeSpecific(LLTDAttribute): [...] by class LLTDAttributeSpecific(LLTDAttribute): [...] LLTDAttributeSpec...
[ "def", "_register_lltd_specific_class", "(", "*", "attr_types", ")", ":", "def", "_register", "(", "cls", ")", ":", "for", "attr_type", "in", "attr_types", ":", "SPECIFIC_CLASSES", "[", "attr_type", "]", "=", "cls", "type_fld", "=", "LLTDAttribute", ".", "fiel...
27.32
0.001414
def add(self, data): """Add data to the buffer""" assert isinstance(data, bytes) with self.lock: self.buf += data
[ "def", "add", "(", "self", ",", "data", ")", ":", "assert", "isinstance", "(", "data", ",", "bytes", ")", "with", "self", ".", "lock", ":", "self", ".", "buf", "+=", "data" ]
29
0.013423
async def check_update(dev: Device, internet: bool, update: bool): """Print out update information.""" if internet: print("Checking updates from network") else: print("Not checking updates from internet") update_info = await dev.get_update_info(from_network=internet) if not update_in...
[ "async", "def", "check_update", "(", "dev", ":", "Device", ",", "internet", ":", "bool", ",", "update", ":", "bool", ")", ":", "if", "internet", ":", "print", "(", "\"Checking updates from network\"", ")", "else", ":", "print", "(", "\"Not checking updates fro...
39.588235
0.001451
def parse_simple_value(self, stream): """ SimpleValue ::= Integer | FloatingPoint | Exponential | BinaryNum | OctalNum | HexadecimalNum | DateTimeValue ...
[ "def", "parse_simple_value", "(", "self", ",", "stream", ")", ":", "if", "self", ".", "has_quoted_string", "(", "stream", ")", ":", "return", "self", ".", "parse_quoted_string", "(", "stream", ")", "if", "self", ".", "has_binary_number", "(", "stream", ")", ...
31.147059
0.001832
def parse_characters(self, character_page): """Parses the DOM and returns anime character attributes in the sidebar. :type character_page: :class:`bs4.BeautifulSoup` :param character_page: MAL anime character page's DOM :rtype: dict :return: anime character attributes :raises: :class:`.Invali...
[ "def", "parse_characters", "(", "self", ",", "character_page", ")", ":", "anime_info", "=", "self", ".", "parse_sidebar", "(", "character_page", ")", "try", ":", "character_title", "=", "filter", "(", "lambda", "x", ":", "'Characters & Voice Actors'", "in", "x",...
42.4375
0.01468
def start(self): """Starts the external measurement program.""" assert not self.is_running(), 'Attempted to start an energy measurement while one was already running.' self._measurement_process = subprocess.Popen( [self._executable, '-r'], stdout=subprocess.PIPE, ...
[ "def", "start", "(", "self", ")", ":", "assert", "not", "self", ".", "is_running", "(", ")", ",", "'Attempted to start an energy measurement while one was already running.'", "self", ".", "_measurement_process", "=", "subprocess", ".", "Popen", "(", "[", "self", "."...
41.545455
0.008565
def parse_sparse(filename, vocab_filename): """ Parse a file that's in libSVM format. In libSVM format each line of the text file represents a document in bag of words format: num_unique_words_in_doc word_id:count another_id:count The word_ids have 0-based indexing, i.e. 0 corresponds to the first...
[ "def", "parse_sparse", "(", "filename", ",", "vocab_filename", ")", ":", "vocab", "=", "_turicreate", ".", "SFrame", ".", "read_csv", "(", "vocab_filename", ",", "header", "=", "None", ")", "[", "'X1'", "]", "vocab", "=", "list", "(", "vocab", ")", "docs...
31.442857
0.000881
def set(self, prop, value): """ sets the dot notated property to the passed in value args: prop: a string of the property to retreive "a.b.c" ~ dictionary['a']['b']['c'] value: the value to set the prop object """ prop_parts = prop.split(".") ...
[ "def", "set", "(", "self", ",", "prop", ",", "value", ")", ":", "prop_parts", "=", "prop", ".", "split", "(", "\".\"", ")", "if", "self", ".", "copy_dict", ":", "new_dict", "=", "copy", ".", "deepcopy", "(", "self", ".", "obj", ")", "else", ":", ...
32.884615
0.002273
def logpdf(x, mean=None, cov=1, allow_singular=True): """ Computes the log of the probability density function of the normal N(mean, cov) for the data x. The normal may be univariate or multivariate. Wrapper for older versions of scipy.multivariate_normal.logpdf which don't support support the allo...
[ "def", "logpdf", "(", "x", ",", "mean", "=", "None", ",", "cov", "=", "1", ",", "allow_singular", "=", "True", ")", ":", "if", "mean", "is", "not", "None", ":", "flat_mean", "=", "np", ".", "asarray", "(", "mean", ")", ".", "flatten", "(", ")", ...
34.166667
0.002372
def msearch(self, body, index=None, doc_type=None, **query_params): """ Execute several search requests within the same API. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html>`_ :arg body: The request definitions (metadata-search request definition...
[ "def", "msearch", "(", "self", ",", "body", ",", "index", "=", "None", ",", "doc_type", "=", "None", ",", "*", "*", "query_params", ")", ":", "self", ".", "_es_parser", ".", "is_not_empty_params", "(", "body", ")", "path", "=", "self", ".", "_es_parser...
51.782609
0.001649
def to_dict(self, into=dict): """ Convert Series to {label -> value} dict or dict-like object. Parameters ---------- into : class, default dict The collections.abc.Mapping subclass to use as the return object. Can be the actual class or an empty ...
[ "def", "to_dict", "(", "self", ",", "into", "=", "dict", ")", ":", "# GH16122", "into_c", "=", "com", ".", "standardize_mapping", "(", "into", ")", "return", "into_c", "(", "self", ".", "items", "(", ")", ")" ]
31.735294
0.001799
def HEADING(txt=None, c="#"): """ Prints a message to stdout with #### surrounding it. This is useful for nosetests to better distinguish them. :param c: uses the given char to wrap the header :param txt: a text message to be printed :type txt: string """ frame = inspect.getouterframes(...
[ "def", "HEADING", "(", "txt", "=", "None", ",", "c", "=", "\"#\"", ")", ":", "frame", "=", "inspect", ".", "getouterframes", "(", "inspect", ".", "currentframe", "(", ")", ")", "filename", "=", "frame", "[", "1", "]", "[", "1", "]", ".", "replace",...
29.333333
0.001835
def get_resource_data(ref_key, ref_id, scenario_id, type_id=None, expunge_session=True, **kwargs): """ Get all the resource scenarios for a given resource in a given scenario. If type_id is specified, only return the resource scenarios for the attributes within the type. """ ...
[ "def", "get_resource_data", "(", "ref_key", ",", "ref_id", ",", "scenario_id", ",", "type_id", "=", "None", ",", "expunge_session", "=", "True", ",", "*", "*", "kwargs", ")", ":", "user_id", "=", "kwargs", ".", "get", "(", "'user_id'", ")", "resource_data_...
34.020408
0.012828
def maybe_upcast_putmask(result, mask, other): """ A safe version of putmask that potentially upcasts the result. The result is replaced with the first N elements of other, where N is the number of True values in mask. If the length of other is shorter than N, other will be repeated. Parameters...
[ "def", "maybe_upcast_putmask", "(", "result", ",", "mask", ",", "other", ")", ":", "if", "not", "isinstance", "(", "result", ",", "np", ".", "ndarray", ")", ":", "raise", "ValueError", "(", "\"The result input must be a ndarray.\"", ")", "if", "mask", ".", "...
33.041667
0.000306
def setup_oauth_client(self, url=None): """ Sets up client for requests to pump """ if url and "://" in url: server, endpoint = self._deconstruct_url(url) else: server = self.client.server if server not in self._server_cache: self._add_client(server) ...
[ "def", "setup_oauth_client", "(", "self", ",", "url", "=", "None", ")", ":", "if", "url", "and", "\"://\"", "in", "url", ":", "server", ",", "endpoint", "=", "self", ".", "_deconstruct_url", "(", "url", ")", "else", ":", "server", "=", "self", ".", "...
36.913043
0.002296
def get_tag(self, tagname, tagidx): """ :returns: the tag associated to the given tagname and tag index """ return '%s=%s' % (tagname, decode(getattr(self, tagname)[tagidx]))
[ "def", "get_tag", "(", "self", ",", "tagname", ",", "tagidx", ")", ":", "return", "'%s=%s'", "%", "(", "tagname", ",", "decode", "(", "getattr", "(", "self", ",", "tagname", ")", "[", "tagidx", "]", ")", ")" ]
40.4
0.009709
def validate_search_input(self) -> bool: "Check if input value is empty." input = self._search_input if input.value == str(): input.layout = Layout(border="solid 2px red", height='auto') else: self._search_input.layout = Layout() return input.value != str()
[ "def", "validate_search_input", "(", "self", ")", "->", "bool", ":", "input", "=", "self", ".", "_search_input", "if", "input", ".", "value", "==", "str", "(", ")", ":", "input", ".", "layout", "=", "Layout", "(", "border", "=", "\"solid 2px red\"", ",",...
51.833333
0.015823
def request_body(request): """ Extracts the credentials of a client from the *application/x-www-form-urlencoded* body of a request. Expects the client_id to be the value of the ``client_id`` parameter and the client_secret to be the value of the ``client_secret`` parameter. :param request: The...
[ "def", "request_body", "(", "request", ")", ":", "client_id", "=", "request", ".", "post_param", "(", "\"client_id\"", ")", "if", "client_id", "is", "None", ":", "raise", "OAuthInvalidError", "(", "error", "=", "\"invalid_request\"", ",", "explanation", "=", "...
36.32
0.001073
def change_zoom(self, zoom): '''zoom in or out by zoom factor, keeping centered''' state = self.state if self.mouse_pos: (x,y) = (self.mouse_pos.x, self.mouse_pos.y) else: (x,y) = (state.width/2, state.height/2) (lat,lon) = self.coordinates(x, y) s...
[ "def", "change_zoom", "(", "self", ",", "zoom", ")", ":", "state", "=", "self", ".", "state", "if", "self", ".", "mouse_pos", ":", "(", "x", ",", "y", ")", "=", "(", "self", ".", "mouse_pos", ".", "x", ",", "self", ".", "mouse_pos", ".", "y", "...
41.153846
0.010969
def move(self, point, reverse=False): """ Translates the box by given (tx, ty) :param point: (tx, ty) :param reverse: If true, the translation direction is reversed. ie. (-tx, -ty) :return: New translated box """ if reverse: point = [-1 * i for i in p...
[ "def", "move", "(", "self", ",", "point", ",", "reverse", "=", "False", ")", ":", "if", "reverse", ":", "point", "=", "[", "-", "1", "*", "i", "for", "i", "in", "point", "]", "return", "Box", "(", "self", ".", "x", "+", "point", "[", "0", "]"...
36.090909
0.009828
def rounded(self, number, roundto=None): """ Rounds the inputed number to the nearest value. :param number | <int> || <float> """ if roundto is None: roundto = self.roundTo() if not roundto: return number ...
[ "def", "rounded", "(", "self", ",", "number", ",", "roundto", "=", "None", ")", ":", "if", "roundto", "is", "None", ":", "roundto", "=", "self", ".", "roundTo", "(", ")", "if", "not", "roundto", ":", "return", "number", "remain", "=", "number", "%", ...
26.625
0.011338
def get_layers(self, Psurf=1013.25, Ptop=0.01, **kwargs): """ Compute scalars or coordinates associated to the vertical layers. Parameters ---------- grid_spec : CTMGrid object CTMGrid containing the information necessary to re-construct grid levels for a...
[ "def", "get_layers", "(", "self", ",", "Psurf", "=", "1013.25", ",", "Ptop", "=", "0.01", ",", "*", "*", "kwargs", ")", ":", "Psurf", "=", "np", ".", "asarray", "(", "Psurf", ")", "output_ndims", "=", "Psurf", ".", "ndim", "+", "1", "if", "output_n...
34.916667
0.001031
def write_quick(self): """ Send only the read / write bit """ self.bus.write_quick(self.address) self.log.debug("write_quick: Sent the read / write bit")
[ "def", "write_quick", "(", "self", ")", ":", "self", ".", "bus", ".", "write_quick", "(", "self", ".", "address", ")", "self", ".", "log", ".", "debug", "(", "\"write_quick: Sent the read / write bit\"", ")" ]
31.333333
0.010363
def delete_variable(self, name): """Deletes a variable from a DataFrame.""" del self.variables[name] self.signal_variable_changed.emit(self, name, "delete")
[ "def", "delete_variable", "(", "self", ",", "name", ")", ":", "del", "self", ".", "variables", "[", "name", "]", "self", ".", "signal_variable_changed", ".", "emit", "(", "self", ",", "name", ",", "\"delete\"", ")" ]
44.25
0.011111
def _save_owner_cover_photo(session, hash, photo): """ https://vk.com/dev/photos.saveOwnerCoverPhoto """ response = session.fetch('photos.saveOwnerCoverPhoto', hash=hash, photo=photo) return response
[ "def", "_save_owner_cover_photo", "(", "session", ",", "hash", ",", "photo", ")", ":", "response", "=", "session", ".", "fetch", "(", "'photos.saveOwnerCoverPhoto'", ",", "hash", "=", "hash", ",", "photo", "=", "photo", ")", "return", "response" ]
39
0.012552
def post(self, uri, data, **kwargs): """POST the provided data to the specified path See :meth:`request` for additional details. The `data` parameter here is expected to be a string type. """ return self.request("POST", uri, data=data, **kwargs)
[ "def", "post", "(", "self", ",", "uri", ",", "data", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "request", "(", "\"POST\"", ",", "uri", ",", "data", "=", "data", ",", "*", "*", "kwargs", ")" ]
40.142857
0.010453
def ParsePathItem(item, opts=None): """Parses string path component to an `PathComponent` instance. Args: item: A path component string to be parsed. opts: A `PathOpts` object. Returns: `PathComponent` instance corresponding to given path fragment. Raises: ValueError: If the path item contain...
[ "def", "ParsePathItem", "(", "item", ",", "opts", "=", "None", ")", ":", "if", "item", "==", "os", ".", "path", ".", "curdir", ":", "return", "CurrentComponent", "(", ")", "if", "item", "==", "os", ".", "path", ".", "pardir", ":", "return", "ParentCo...
26.352941
0.011841
def load_stdgraphs(size: int) -> List[nx.Graph]: """Load standard graph validation sets For each size (from 6 to 32 graph nodes) the dataset consists of 100 graphs drawn from the Erdős-Rényi ensemble with edge probability 50%. """ from pkg_resources import resource_stream if size < 6 or si...
[ "def", "load_stdgraphs", "(", "size", ":", "int", ")", "->", "List", "[", "nx", ".", "Graph", "]", ":", "from", "pkg_resources", "import", "resource_stream", "if", "size", "<", "6", "or", "size", ">", "32", ":", "raise", "ValueError", "(", "'Size out of ...
33.866667
0.001916
def _update_marshallers(self): """ Update the full marshaller list and other data structures. Makes a full list of both builtin and user marshallers and rebuilds internal data structures used for looking up which marshaller to use for reading/writing Python objects to/from file....
[ "def", "_update_marshallers", "(", "self", ")", ":", "# Combine all sets of marshallers.", "self", ".", "_marshallers", "=", "[", "]", "for", "v", "in", "self", ".", "_priority", ":", "if", "v", "==", "'builtin'", ":", "self", ".", "_marshallers", ".", "exte...
42.895238
0.000868
def html(self): """ Wrapper for only doing the rendering on request (drastically reduces memory) """ return self.render(self.data, self.proj, self.obj)
[ "def", "html", "(", "self", ")", ":", "return", "self", ".", "render", "(", "self", ".", "data", ",", "self", ".", "proj", ",", "self", ".", "obj", ")" ]
55
0.017964
def prepare_axes(axes, title, size, cmap=None): """Prepares an axes object for clean plotting. Removes x and y axes labels and ticks, sets the aspect ratio to be equal, uses the size to determine the drawing area and fills the image with random colors as visual feedback. Creates an AxesImage to be...
[ "def", "prepare_axes", "(", "axes", ",", "title", ",", "size", ",", "cmap", "=", "None", ")", ":", "if", "axes", "is", "None", ":", "return", "None", "# prepare axis itself", "axes", ".", "set_xlim", "(", "[", "0", ",", "size", "[", "1", "]", "]", ...
30.025641
0.000827
def compute_mean_reward(rollouts, clipped): """Calculate mean rewards from given epoch.""" reward_name = "reward" if clipped else "unclipped_reward" rewards = [] for rollout in rollouts: if rollout[-1].done: rollout_reward = sum(getattr(frame, reward_name) for frame in rollout) rewards.append(ro...
[ "def", "compute_mean_reward", "(", "rollouts", ",", "clipped", ")", ":", "reward_name", "=", "\"reward\"", "if", "clipped", "else", "\"unclipped_reward\"", "rewards", "=", "[", "]", "for", "rollout", "in", "rollouts", ":", "if", "rollout", "[", "-", "1", "]"...
32.461538
0.023041
def _graph_is_connected(graph): """ Return whether the graph is connected (True) or Not (False) Parameters ---------- graph : array-like or sparse matrix, shape: (n_samples, n_samples) adjacency matrix of the graph, non-zero weight means an edge between the nodes Returns --...
[ "def", "_graph_is_connected", "(", "graph", ")", ":", "if", "sparse", ".", "isspmatrix", "(", "graph", ")", ":", "# sparse graph, find all the connected components", "n_connected_components", ",", "_", "=", "connected_components", "(", "graph", ")", "return", "n_conne...
34.5
0.001282
def extend(cls, services): """ Extends services list with reflection service: .. code-block:: python3 from grpclib.reflection.service import ServerReflection services = [Greeter()] services = ServerReflection.extend(services) server = Server(se...
[ "def", "extend", "(", "cls", ",", "services", ")", ":", "service_names", "=", "[", "]", "for", "service", "in", "services", ":", "service_names", ".", "append", "(", "_service_name", "(", "service", ")", ")", "services", "=", "list", "(", "services", ")"...
32.5
0.002491
def _S(kappa, alpha, beta): """Compute the antiderivative of the Amos-type bound G on the modified Bessel function ratio. Note: Handles scalar kappa, alpha, and beta only. See "S <-" in movMF.R and utility function implementation notes from https://cran.r-project.org/web/packages/movMF/index.html...
[ "def", "_S", "(", "kappa", ",", "alpha", ",", "beta", ")", ":", "kappa", "=", "1.", "*", "np", ".", "abs", "(", "kappa", ")", "alpha", "=", "1.", "*", "alpha", "beta", "=", "1.", "*", "np", ".", "abs", "(", "beta", ")", "a_plus_b", "=", "alph...
30.45
0.001592
def sortby(listoflists,sortcols): """ Sorts a list of lists on the column(s) specified in the sequence sortcols. Usage: sortby(listoflists,sortcols) Returns: sorted list, unchanged column ordering """ newlist = abut(colex(listoflists,sortcols),listoflists) newlist.sort() try: numcols = len(so...
[ "def", "sortby", "(", "listoflists", ",", "sortcols", ")", ":", "newlist", "=", "abut", "(", "colex", "(", "listoflists", ",", "sortcols", ")", ",", "listoflists", ")", "newlist", ".", "sort", "(", ")", "try", ":", "numcols", "=", "len", "(", "sortcols...
26.058824
0.010893
def _lm_solve_full(a, b, ddiag, delta, par0, dtype=np.float): """Compute the Levenberg-Marquardt parameter and solution vector. Parameters: a - n-by-m matrix, m >= n (only the n-by-n component is used) b - n-by-n matrix ddiag - n-vector, diagonal elements of D delta - positive scalar, specifies scale of en...
[ "def", "_lm_solve_full", "(", "a", ",", "b", ",", "ddiag", ",", "delta", ",", "par0", ",", "dtype", "=", "np", ".", "float", ")", ":", "a", "=", "np", ".", "asarray", "(", "a", ",", "dtype", ")", "b", "=", "np", ".", "asarray", "(", "b", ",",...
30.576923
0.000609
def checkIfRemoteIsNewer(self, remote, local, headers): """ Given a remote file location, and the corresponding local file this will check the datetime stamp on the files to see if the remote one is newer. This is a convenience method to be used so that we don't have to r...
[ "def", "checkIfRemoteIsNewer", "(", "self", ",", "remote", ",", "local", ",", "headers", ")", ":", "LOG", ".", "info", "(", "\"Checking if remote file \\n(%s)\\n is newer than local \\n(%s)\"", ",", "remote", ",", "local", ")", "# check if local file exists", "# if no l...
36.394737
0.001056
def parse_config(init_func): """Decorator wrapping the environment to use a config file""" @functools.wraps(init_func) def new_func(env, *args, **kwargs): config_interpreter = ConfigInterpreter(kwargs) # Pass the config data to the kwargs new_kwargs = config_interpreter.interpret() ...
[ "def", "parse_config", "(", "init_func", ")", ":", "@", "functools", ".", "wraps", "(", "init_func", ")", "def", "new_func", "(", "env", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "config_interpreter", "=", "ConfigInterpreter", "(", "kwargs", "...
44.181818
0.002016
def get_column_metadata(conn, table: str, schema='public'): """Returns column data following db.Column parameter specification.""" query = """\ SELECT attname as name, format_type(atttypid, atttypmod) AS data_type, NOT attnotnull AS nullable FROM pg_catalog.pg_attribute WHERE attrelid=%s::regclass AND a...
[ "def", "get_column_metadata", "(", "conn", ",", "table", ":", "str", ",", "schema", "=", "'public'", ")", ":", "query", "=", "\"\"\"\\\nSELECT\n attname as name,\n format_type(atttypid, atttypmod) AS data_type,\n NOT attnotnull AS nullable\nFROM pg_catalog.pg_attribute\nWHERE attr...
32.125
0.00189
def imresize(self, data, new_wd, new_ht, method='bilinear'): """Scale an image in numpy array _data_ to the specified width and height. A smooth scaling is preferred. """ old_ht, old_wd = data.shape[:2] start_time = time.time() if have_pilutil: means = 'PIL'...
[ "def", "imresize", "(", "self", ",", "data", ",", "new_wd", ",", "new_ht", ",", "method", "=", "'bilinear'", ")", ":", "old_ht", ",", "old_wd", "=", "data", ".", "shape", "[", ":", "2", "]", "start_time", "=", "time", ".", "time", "(", ")", "if", ...
33.444444
0.002153
def _load_fsLR_atlasroi(filename, data): ''' Loads the appropriate atlas for the given data; data may point to a cifti file whose atlas is needed or to an atlas file. ''' (fdir, fnm) = os.path.split(filename) fparts = fnm.split('.') atl = fparts[-3] if atl in _load_fsLR_atlasroi.atlases:...
[ "def", "_load_fsLR_atlasroi", "(", "filename", ",", "data", ")", ":", "(", "fdir", ",", "fnm", ")", "=", "os", ".", "path", ".", "split", "(", "filename", ")", "fparts", "=", "fnm", ".", "split", "(", "'.'", ")", "atl", "=", "fparts", "[", "-", "...
45.52381
0.01332
def pp_hex(raw, reverse=True): """Return a pretty-printed (hex style) version of a binary string. Args: raw (bytes): any sequence of bytes reverse (bool): True if output should be in reverse order. Returns: Hex string corresponding to input byte sequence. """ if not reverse...
[ "def", "pp_hex", "(", "raw", ",", "reverse", "=", "True", ")", ":", "if", "not", "reverse", ":", "return", "''", ".", "join", "(", "[", "'{:02x}'", ".", "format", "(", "v", ")", "for", "v", "in", "bytearray", "(", "raw", ")", "]", ")", "return", ...
34.846154
0.002151
def R_value_to_k(R_value, SI=True): r'''Returns the thermal conductivity of a substance given its R-value, which can be in either SI units of m^2 K/(W*inch) or the Imperial units of ft^2 deg F*h/(BTU*inch). Parameters ---------- R_value : float R-value of a substance [m^2 K/(W*inch) or ...
[ "def", "R_value_to_k", "(", "R_value", ",", "SI", "=", "True", ")", ":", "if", "SI", ":", "r", "=", "R_value", "/", "inch", "else", ":", "r", "=", "R_value", "*", "foot", "**", "2", "*", "degree_Fahrenheit", "*", "hour", "/", "Btu", "/", "inch", ...
28.525
0.000847
def get_pp_name(self): '''Determine the pseudopotential names from the output''' ppnames = [] # Find the number of atom types natomtypes = int(self._get_line('number of atomic types', self.outputf).split()[5]) # Find the pseudopotential names with open(self.outputf) as fp...
[ "def", "get_pp_name", "(", "self", ")", ":", "ppnames", "=", "[", "]", "# Find the number of atom types", "natomtypes", "=", "int", "(", "self", ".", "_get_line", "(", "'number of atomic types'", ",", "self", ".", "outputf", ")", ".", "split", "(", ")", "[",...
50
0.009063
def decode(self, frame: Frame, *, max_size: Optional[int] = None) -> Frame: """ Decode an incoming frame. """ # Skip control frames. if frame.opcode in CTRL_OPCODES: return frame # Handle continuation data frames: # - skip if the initial data frame w...
[ "def", "decode", "(", "self", ",", "frame", ":", "Frame", ",", "*", ",", "max_size", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "Frame", ":", "# Skip control frames.", "if", "frame", ".", "opcode", "in", "CTRL_OPCODES", ":", "return", "f...
38.367347
0.002075
def get_curie_prefix(self, uri): ''' Return the CURIE's prefix:''' for key, value in self.uri_map.items(): if uri.startswith(key): return value return None
[ "def", "get_curie_prefix", "(", "self", ",", "uri", ")", ":", "for", "key", ",", "value", "in", "self", ".", "uri_map", ".", "items", "(", ")", ":", "if", "uri", ".", "startswith", "(", "key", ")", ":", "return", "value", "return", "None" ]
33.666667
0.009662
def tange_grun(v, v0, gamma0, a, b): """ calculate Gruneisen parameter for the Tange equation :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param gamma0: Gruneisen parameter at 1 bar :param a: volume-independent adjustable parameters :param b: volume-indepen...
[ "def", "tange_grun", "(", "v", ",", "v0", ",", "gamma0", ",", "a", ",", "b", ")", ":", "x", "=", "v", "/", "v0", "return", "gamma0", "*", "(", "1.", "+", "a", "*", "(", "np", ".", "power", "(", "x", ",", "b", ")", "-", "1.", ")", ")" ]
34.076923
0.002198
def get_last_name_first_name(self): """ :rtype: str """ last_names = [] if self._get_last_names(): last_names += self._get_last_names() first_and_additional_names = [] if self._get_first_names(): first_and_additional_names += self._get_firs...
[ "def", "get_last_name_first_name", "(", "self", ")", ":", "last_names", "=", "[", "]", "if", "self", ".", "_get_last_names", "(", ")", ":", "last_names", "+=", "self", ".", "_get_last_names", "(", ")", "first_and_additional_names", "=", "[", "]", "if", "self...
40.636364
0.002186
def restore(self, training_info: TrainingInfo, local_batch_idx: int, model: Model, hidden_state: dict): """ Restore learning from intermediate state. """ pass
[ "def", "restore", "(", "self", ",", "training_info", ":", "TrainingInfo", ",", "local_batch_idx", ":", "int", ",", "model", ":", "Model", ",", "hidden_state", ":", "dict", ")", ":", "pass" ]
37.2
0.015789
def register(self, key, initializer: callable, param=None): '''Add resolver to container''' if not callable(initializer): raise DependencyError('Initializer {0} is not callable'.format(initializer)) if key not in self._initializers: self._initializers[key] = {} se...
[ "def", "register", "(", "self", ",", "key", ",", "initializer", ":", "callable", ",", "param", "=", "None", ")", ":", "if", "not", "callable", "(", "initializer", ")", ":", "raise", "DependencyError", "(", "'Initializer {0} is not callable'", ".", "format", ...
50.857143
0.008287
def remove_from(self, target, ctx=None): """Remove self annotation from target annotations. :param target: target from where remove self annotation. :param ctx: target ctx. """ annotations_key = Annotation.__ANNOTATIONS_KEY__ try: # get local annotations ...
[ "def", "remove_from", "(", "self", ",", "target", ",", "ctx", "=", "None", ")", ":", "annotations_key", "=", "Annotation", ".", "__ANNOTATIONS_KEY__", "try", ":", "# get local annotations", "local_annotations", "=", "get_local_property", "(", "target", ",", "annot...
38.206897
0.001761
def verify_email(self, action_token, signed_data): """ Verify email account, in which a link was sent to """ try: action = "verify-email" user = get_user_by_action_token(action, action_token) if not user or not user.signed_data_match(signed_data, action): ...
[ "def", "verify_email", "(", "self", ",", "action_token", ",", "signed_data", ")", ":", "try", ":", "action", "=", "\"verify-email\"", "user", "=", "get_user_by_action_token", "(", "action", ",", "action_token", ")", "if", "not", "user", "or", "not", "user", ...
43.789474
0.002353
def getDiskPoolSpace(rh): """ Obtain disk pool space information for all or a specific disk pool. Input: Request Handle with the following properties: function - 'GETHOST' subfunction - 'DISKPOOLSPACE' parms['poolName'] - Name of the disk pool. Opti...
[ "def", "getDiskPoolSpace", "(", "rh", ")", ":", "rh", ".", "printSysLog", "(", "\"Enter getHost.getDiskPoolSpace\"", ")", "results", "=", "{", "'overallRC'", ":", "0", "}", "if", "'poolName'", "not", "in", "rh", ".", "parms", ":", "poolNames", "=", "[", "\...
37.9
0.001607
def find_library_linux(cls): """Loads the SEGGER DLL from the root directory. On Linux, the SEGGER tools are installed under the ``/opt/SEGGER`` directory with versioned directories having the suffix ``_VERSION``. Args: cls (Library): the ``Library`` class Returns: ...
[ "def", "find_library_linux", "(", "cls", ")", ":", "dll", "=", "Library", ".", "JLINK_SDK_NAME", "root", "=", "os", ".", "path", ".", "join", "(", "'/'", ",", "'opt'", ",", "'SEGGER'", ")", "for", "(", "directory_name", ",", "subdirs", ",", "files", ")...
34.166667
0.001581
def urls_for(self, asset_type, *args, **kwargs): """Returns urls needed to include all assets of asset_type """ return self.urls_for_depends(asset_type, *args, **kwargs) + \ self.urls_for_self(asset_type, *args, **kwargs)
[ "def", "urls_for", "(", "self", ",", "asset_type", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "urls_for_depends", "(", "asset_type", ",", "*", "args", ",", "*", "*", "kwargs", ")", "+", "self", ".", "urls_for_self", "...
51.2
0.011538
def getHosts(filename=None, hostlist=None): """Return a list of hosts depending on the environment""" if filename: return getHostsFromFile(filename) elif hostlist: return getHostsFromList(hostlist) elif getEnv() == "SLURM": return getHostsFromSLURM() elif getEnv() == "PBS": ...
[ "def", "getHosts", "(", "filename", "=", "None", ",", "hostlist", "=", "None", ")", ":", "if", "filename", ":", "return", "getHostsFromFile", "(", "filename", ")", "elif", "hostlist", ":", "return", "getHostsFromList", "(", "hostlist", ")", "elif", "getEnv",...
31.571429
0.002198
def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but ...
[ "def", "_delete_resource", "(", "resource", ",", "name", "=", "None", ",", "resource_id", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "...
42.833333
0.000543
def config(name, reset=False, **kwargs): ''' Modify configuration options for a given port. Multiple options can be specified. To see the available options for a port, use :mod:`ports.showconfig <salt.modules.freebsdports.showconfig>`. name The port name, in ``category/name`` format re...
[ "def", "config", "(", "name", ",", "reset", "=", "False", ",", "*", "*", "kwargs", ")", ":", "portpath", "=", "_check_portname", "(", "name", ")", "if", "reset", ":", "rmconfig", "(", "name", ")", "configuration", "=", "showconfig", "(", "name", ",", ...
27.220588
0.000521
def measurements(self): """Return the measurements associated with this instance. if measurements are not present, check if we can model, and then run CRMod to load the measurements. """ # check if we have measurements mid = self.assignments.get('measurements', None) ...
[ "def", "measurements", "(", "self", ")", ":", "# check if we have measurements", "mid", "=", "self", ".", "assignments", ".", "get", "(", "'measurements'", ",", "None", ")", "if", "mid", "is", "None", ":", "return_value", "=", "self", ".", "model", "(", "v...
32.88
0.002364
def getexcfo(e): ''' Get an err tufo from an exception. Args: e (Exception): An Exception (or Exception subclass). Notes: This can be called outside of the context of an exception handler, however details such as file, line, function name and source may be missing. ...
[ "def", "getexcfo", "(", "e", ")", ":", "tb", "=", "sys", ".", "exc_info", "(", ")", "[", "2", "]", "tbinfo", "=", "traceback", ".", "extract_tb", "(", "tb", ")", "path", ",", "line", ",", "name", ",", "src", "=", "''", ",", "''", ",", "''", "...
23.09375
0.001299
def _commitData(self, commit): """Get data from a commit object :param commit: commit object :type commit: git.objects.commit.Commit """ return { "hexsha": commit.hexsha, "adate": commit.authored_date, "cdate": commit.committed_date, "author": "%s <%s>" % (commit.author.name, commit.author.email...
[ "def", "_commitData", "(", "self", ",", "commit", ")", ":", "return", "{", "\"hexsha\"", ":", "commit", ".", "hexsha", ",", "\"adate\"", ":", "commit", ".", "authored_date", ",", "\"cdate\"", ":", "commit", ".", "committed_date", ",", "\"author\"", ":", "\...
26.384615
0.03662
def _render_object(self, obj, *context, **kwargs): """ Render the template associated with the given object. """ loader = self._make_loader() # TODO: consider an approach that does not require using an if # block here. For example, perhaps this class's loader can be ...
[ "def", "_render_object", "(", "self", ",", "obj", ",", "*", "context", ",", "*", "*", "kwargs", ")", ":", "loader", "=", "self", ".", "_make_loader", "(", ")", "# TODO: consider an approach that does not require using an if", "# block here. For example, perhaps this ...
37.809524
0.002457
def RepeatTimer(interval, function, iterations=0, *args, **kwargs): """Repeating timer. Returns a thread id.""" def __repeat_timer(interval, function, iterations, args, kwargs): """Inner function, run in background thread.""" count = 0 while iterations <= 0 or count < iterations: sleep(interval) ...
[ "def", "RepeatTimer", "(", "interval", ",", "function", ",", "iterations", "=", "0", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "__repeat_timer", "(", "interval", ",", "function", ",", "iterations", ",", "args", ",", "kwargs", ")", ":"...
37.333333
0.017429
def _bind_device(self): """ This method transforms the ``self.pvs`` dict of :class:`PV` objects ``self.bound_pvs``, a dict of :class:`BoundPV` objects, the keys are always the PV-names that are exposed via ChannelAccess. In the transformation process, the method tries to find wh...
[ "def", "_bind_device", "(", "self", ")", ":", "self", ".", "bound_pvs", "=", "{", "}", "for", "pv_name", ",", "pv", "in", "self", ".", "pvs", ".", "items", "(", ")", ":", "try", ":", "self", ".", "bound_pvs", "[", "pv_name", "]", "=", "pv", ".", ...
52.652174
0.008921
def get_inline_choice_ids(self): """stub""" return_data = {} for inline_region, data in self.my_osid_object._my_map['inlineRegions'].items(): return_data[inline_region] = { 'choiceIds': IdList(data['choiceIds']) } return return_data
[ "def", "get_inline_choice_ids", "(", "self", ")", ":", "return_data", "=", "{", "}", "for", "inline_region", ",", "data", "in", "self", ".", "my_osid_object", ".", "_my_map", "[", "'inlineRegions'", "]", ".", "items", "(", ")", ":", "return_data", "[", "in...
37.125
0.009868
def list_all_files(i): """ Input: { path - top level path (file_name) - search for a specific file name (pattern) - return only files with this pattern (path_ext) - path extension (needed for recursion) ...
[ "def", "list_all_files", "(", "i", ")", ":", "number", "=", "0", "if", "i", ".", "get", "(", "'number'", ",", "''", ")", "!=", "''", ":", "number", "=", "int", "(", "i", "[", "'number'", "]", ")", "inames", "=", "i", ".", "get", "(", "'ignore_n...
33.234694
0.029815
def check_and_format_logs_params(start, end, tail): """Helper to read the params for the logs command""" def _decode_duration_type(duration_type): durations = {'m': 'minutes', 'h': 'hours', 'd': 'days', 'w': 'weeks'} return durations[duration_type] if not start: if tail: ...
[ "def", "check_and_format_logs_params", "(", "start", ",", "end", ",", "tail", ")", ":", "def", "_decode_duration_type", "(", "duration_type", ")", ":", "durations", "=", "{", "'m'", ":", "'minutes'", ",", "'h'", ":", "'hours'", ",", "'d'", ":", "'days'", "...
38.666667
0.000935
def create_config_drive(network_interface_info, os_version): """Generate config driver for zVM guest vm. :param dict network_interface_info: Required keys: ip_addr - (str) IP address nic_vdev - (str) VDEV of the nic gateway_v4 - IPV4 gateway broadcast_v4 - IPV4 broadcast address...
[ "def", "create_config_drive", "(", "network_interface_info", ",", "os_version", ")", ":", "temp_path", "=", "CONF", ".", "guest", ".", "temp_path", "if", "not", "os", ".", "path", ".", "exists", "(", "temp_path", ")", ":", "os", ".", "mkdir", "(", "temp_pa...
37.02439
0.000642
def _AtNonLeaf(self, attr_value, path): """Called when at a non-leaf value. Should recurse and yield values.""" try: # Check first for iterables # If it's a dictionary, we yield it if isinstance(attr_value, dict): yield attr_value else: # If it's an iterable, we recurse o...
[ "def", "_AtNonLeaf", "(", "self", ",", "attr_value", ",", "path", ")", ":", "try", ":", "# Check first for iterables", "# If it's a dictionary, we yield it", "if", "isinstance", "(", "attr_value", ",", "dict", ")", ":", "yield", "attr_value", "else", ":", "# If it...
39
0.011686
def subtract_ranges(r1s,r2s,already_sorted=False): """Subtract multiple ranges from a list of ranges :param r1s: range list 1 :param r2s: range list 2 :param already_sorted: default (False) :type r1s: GenomicRange[] :type r2s: GenomicRange[] :return: new range r1s minus r2s :rtype: GenomicRange[] ""...
[ "def", "subtract_ranges", "(", "r1s", ",", "r2s", ",", "already_sorted", "=", "False", ")", ":", "from", "seqtools", ".", "stream", "import", "MultiLocusStream", "if", "not", "already_sorted", ":", "r1s", "=", "merge_ranges", "(", "r1s", ")", "r2s", "=", "...
28.15625
0.025737
def zGetUpdate(self): """Update the lens""" status,ret = -998, None ret = self._sendDDEcommand("GetUpdate") if ret != None: status = int(ret) #Note: Zemax returns -1 if GetUpdate fails. return status
[ "def", "zGetUpdate", "(", "self", ")", ":", "status", ",", "ret", "=", "-", "998", ",", "None", "ret", "=", "self", ".", "_sendDDEcommand", "(", "\"GetUpdate\"", ")", "if", "ret", "!=", "None", ":", "status", "=", "int", "(", "ret", ")", "#Note: Zema...
35.142857
0.019841
def get_uses_implied_permission_list(self): """ Return all permissions implied by the target SDK or other permissions. :rtype: list of string """ target_sdk_version = self.get_effective_target_sdk_version() READ_CALL_LOG = 'android.permission.READ_CALL_LOG' ...
[ "def", "get_uses_implied_permission_list", "(", "self", ")", ":", "target_sdk_version", "=", "self", ".", "get_effective_target_sdk_version", "(", ")", "READ_CALL_LOG", "=", "'android.permission.READ_CALL_LOG'", "READ_CONTACTS", "=", "'android.permission.READ_CONTACTS'", "READ_...
42.977273
0.002068
def _write(self, img_array, verbose=False, **kwargs): """Write image data to a JP2/JPX/J2k file. Intended usage of the various parameters follows that of OpenJPEG's opj_compress utility. This method can only be used to create JPEG 2000 images that can fit in memory. """ ...
[ "def", "_write", "(", "self", ",", "img_array", ",", "verbose", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "re", ".", "match", "(", "\"0|1.[0-4]\"", ",", "version", ".", "openjpeg_version", ")", "is", "not", "None", ":", "msg", "=", "(", ...
41.578947
0.002475
def parse_arguments(): """ Parse commandline arguments. """ parser = argparse.ArgumentParser() # Add options parser.add_argument( "-n", "--number", action="store", default=1000000, type=int, help="number of items") parser.add_argument( "-p", "--pause", action="store...
[ "def", "parse_arguments", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "# Add options", "parser", ".", "add_argument", "(", "\"-n\"", ",", "\"--number\"", ",", "action", "=", "\"store\"", ",", "default", "=", "1000000", ",", "ty...
25.4375
0.00237
def unwrap(self, value): """Unpack a Value into an augmented python type (selected from the 'value' field) """ if value.changed('value.choices'): self._choices = value['value.choices'] idx = value['value.index'] ret = ntenum(idx)._store(value) try: ...
[ "def", "unwrap", "(", "self", ",", "value", ")", ":", "if", "value", ".", "changed", "(", "'value.choices'", ")", ":", "self", ".", "_choices", "=", "value", "[", "'value.choices'", "]", "idx", "=", "value", "[", "'value.index'", "]", "ret", "=", "nten...
32.538462
0.009195
def _set_status_channels(self): """Compiles all status channels for the status compiler process """ status_inst = pc.StatusCompiler(template="status_compiler") report_inst = pc.ReportCompiler(template="report_compiler") # Compile status channels from pipeline process st...
[ "def", "_set_status_channels", "(", "self", ")", ":", "status_inst", "=", "pc", ".", "StatusCompiler", "(", "template", "=", "\"status_compiler\"", ")", "report_inst", "=", "pc", ".", "ReportCompiler", "(", "template", "=", "\"report_compiler\"", ")", "# Compile s...
38.421053
0.001336
def clear(self): """ Command: 0x03 clear all leds Data: [Command] """ header = bytearray() header.append(LightProtocolCommand.Clear) return self.send(header)
[ "def", "clear", "(", "self", ")", ":", "header", "=", "bytearray", "(", ")", "header", ".", "append", "(", "LightProtocolCommand", ".", "Clear", ")", "return", "self", ".", "send", "(", "header", ")" ]
12.769231
0.061798