text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def get_database_size(db_user, db_name, localhost=False): """ Returns the total size for the given database role and name. :param db_user: String representing the database role. :param db_name: String representing the database name. """ localhost_part = '' if localhost: localhost_p...
[ "def", "get_database_size", "(", "db_user", ",", "db_name", ",", "localhost", "=", "False", ")", ":", "localhost_part", "=", "''", "if", "localhost", ":", "localhost_part", "=", "'-h localhost '", "cmd", "=", "'psql {0}-U {1} -c \"select pg_database_size(\\'{2}\\');\"'"...
33.533333
0.001934
def _categoryToLabelList(self, category): """ Converts a category number into a list of labels """ if category is None: return [] labelList = [] labelNum = 0 while category > 0: if category % 2 == 1: labelList.append(self.saved_categories[labelNum]) labelNum += 1 ...
[ "def", "_categoryToLabelList", "(", "self", ",", "category", ")", ":", "if", "category", "is", "None", ":", "return", "[", "]", "labelList", "=", "[", "]", "labelNum", "=", "0", "while", "category", ">", "0", ":", "if", "category", "%", "2", "==", "1...
23.733333
0.013514
def take_at_most_n_seconds(time_s, func, *args, **kwargs): """A function that returns whether a function call took less than time_s. NOTE: The function call is not killed and will run indefinitely if hung. Args: time_s: Maximum amount of time to take. func: Function to call. *args: Arguments to call...
[ "def", "take_at_most_n_seconds", "(", "time_s", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "thread", "=", "threading", ".", "Thread", "(", "target", "=", "func", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")", "thr...
32.684211
0.010955
def print_code(vm, out=sys.stdout, ops_per_line=8, registers=True): """Prints code and state for VM.""" if registers: out.write("IP: %d\n" % vm.instruction_pointer) out.write("DS: %s\n" % str(vm.stack)) out.write("RS: %s\n" % str(vm.return_stack)) def to_str(op): if is_embed...
[ "def", "print_code", "(", "vm", ",", "out", "=", "sys", ".", "stdout", ",", "ops_per_line", "=", "8", ",", "registers", "=", "True", ")", ":", "if", "registers", ":", "out", ".", "write", "(", "\"IP: %d\\n\"", "%", "vm", ".", "instruction_pointer", ")"...
33.32
0.002334
def request( self, method, url, timeout=None, headers=None, data=None, params=None ): """ Make a request using the requests library :param method: Which http method to use (GET/POST) :type method: str | unicode :param url: Url to make request to ...
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "timeout", "=", "None", ",", "headers", "=", "None", ",", "data", "=", "None", ",", "params", "=", "None", ")", ":", "if", "headers", "is", "None", ":", "headers", "=", "{", "}", "if"...
35.490909
0.001496
def generate_daily(day_end_hour, use_dst, calib_data, hourly_data, daily_data, process_from): """Generate daily summaries from calibrated and hourly data.""" start = daily_data.before(datetime.max) if start is None: start = datetime.min start = calib_data.after(start + SECOND)...
[ "def", "generate_daily", "(", "day_end_hour", ",", "use_dst", ",", "calib_data", ",", "hourly_data", ",", "daily_data", ",", "process_from", ")", ":", "start", "=", "daily_data", ".", "before", "(", "datetime", ".", "max", ")", "if", "start", "is", "None", ...
36.617021
0.001132
def render_in_page(request, template): """return rendered template in standalone mode or ``False`` """ from leonardo.module.web.models import Page page = request.leonardo_page if hasattr( request, 'leonardo_page') else Page.objects.filter(parent=None).first() if page: try: ...
[ "def", "render_in_page", "(", "request", ",", "template", ")", ":", "from", "leonardo", ".", "module", ".", "web", ".", "models", "import", "Page", "page", "=", "request", ".", "leonardo_page", "if", "hasattr", "(", "request", ",", "'leonardo_page'", ")", ...
29.892857
0.001157
def center_text_cursor(object): """ Centers the text cursor position. :param object: Object to decorate. :type object: object :return: Object. :rtype: object """ @functools.wraps(object) def center_text_cursor_wrapper(*args, **kwargs): """ Centers the text cursor po...
[ "def", "center_text_cursor", "(", "object", ")", ":", "@", "functools", ".", "wraps", "(", "object", ")", "def", "center_text_cursor_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Centers the text cursor position.\n\n :param \\*...
26.694444
0.013052
def gen_centers(self): """Set the centre of the Gaussian basis functions be spaced evenly throughout run time""" '''x_track = self.cs.discrete_rollout() t = np.arange(len(x_track))*self.dt # choose the points in time we'd like centers to be at c_des = np.linspace(0, sel...
[ "def", "gen_centers", "(", "self", ")", ":", "'''x_track = self.cs.discrete_rollout()\n t = np.arange(len(x_track))*self.dt\n # choose the points in time we'd like centers to be at\n c_des = np.linspace(0, self.cs.run_time, self.bfs)\n self.c = np.zeros(len(c_des))\n f...
36.545455
0.011309
def build(self, package_dir, output_style='nested'): """Builds the Sass/SCSS files in the specified :attr:`sass_path`. It finds :attr:`sass_path` and locates :attr:`css_path` as relative to the given ``package_dir``. :param package_dir: the path of package directory :type packag...
[ "def", "build", "(", "self", ",", "package_dir", ",", "output_style", "=", "'nested'", ")", ":", "sass_path", "=", "os", ".", "path", ".", "join", "(", "package_dir", ",", "self", ".", "sass_path", ")", "css_path", "=", "os", ".", "path", ".", "join", ...
41.241379
0.001634
async def update_module( self, module: modules.AbstractModule, firmware_file: str, loop: asyncio.AbstractEventLoop = None) -> Tuple[bool, str]: """ Update a module's firmware. Returns (ok, message) where ok is True if the update succeeded and message is a hum...
[ "async", "def", "update_module", "(", "self", ",", "module", ":", "modules", ".", "AbstractModule", ",", "firmware_file", ":", "str", ",", "loop", ":", "asyncio", ".", "AbstractEventLoop", "=", "None", ")", "->", "Tuple", "[", "bool", ",", "str", "]", ":...
41.35
0.002364
def make_repository_component(self): """Return an XML string representing this BMI in a workflow. This description is required by EMELI to discover and load models. Returns ------- xml : str String serialized XML representation of the component in the mo...
[ "def", "make_repository_component", "(", "self", ")", ":", "component", "=", "etree", ".", "Element", "(", "'component'", ")", "comp_name", "=", "etree", ".", "Element", "(", "'comp_name'", ")", "comp_name", ".", "text", "=", "self", ".", "model", ".", "na...
30.982143
0.001117
def drop(n, it, constructor=list): """ >>> first(10,drop(10,xrange(sys.maxint),iter)) [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] """ return constructor(itertools.islice(it,n,None))
[ "def", "drop", "(", "n", ",", "it", ",", "constructor", "=", "list", ")", ":", "return", "constructor", "(", "itertools", ".", "islice", "(", "it", ",", "n", ",", "None", ")", ")" ]
32.166667
0.015152
def find_directories(root, pattern): """Find all directories matching the glob pattern recursively :param root: string :param pattern: string :return: list of dir paths relative to root """ results = [] for base, dirs, files in os.walk(root): matched = fnmatch.filter(dirs, pattern) ...
[ "def", "find_directories", "(", "root", ",", "pattern", ")", ":", "results", "=", "[", "]", "for", "base", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "root", ")", ":", "matched", "=", "fnmatch", ".", "filter", "(", "dirs", ",", "patte...
32.5
0.002494
def as_scipy_functional(func, return_gradient=False): """Wrap ``op`` as a function operating on linear arrays. This is intended to be used with the `scipy solvers <https://docs.scipy.org/doc/scipy/reference/optimize.html>`_. Parameters ---------- func : `Functional`. A functional that ...
[ "def", "as_scipy_functional", "(", "func", ",", "return_gradient", "=", "False", ")", ":", "def", "func_call", "(", "arr", ")", ":", "return", "func", "(", "np", ".", "asarray", "(", "arr", ")", ".", "reshape", "(", "func", ".", "domain", ".", "shape",...
32.220339
0.00051
def return_hdr(self): """Return the header for further use. Returns ------- subj_id : str subject identification code start_time : datetime start time of the dataset s_freq : float sampling frequency chan_name : list of str ...
[ "def", "return_hdr", "(", "self", ")", ":", "orig", "=", "{", "}", "orig", "=", "_read_header", "(", "self", ".", "filename", ")", "nchan", "=", "int", "(", "orig", "[", "'SourceCh'", "]", ")", "chan_name", "=", "[", "'ch{:03d}'", ".", "format", "(",...
36.096774
0.002175
def _update_exponential_bucket_count(a_float, dist): """Adds `a_float` to `dist`, updating its exponential buckets. Args: a_float (float): a new value dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`): the Distribution being updated Raises: ValueErr...
[ "def", "_update_exponential_bucket_count", "(", "a_float", ",", "dist", ")", ":", "buckets", "=", "dist", ".", "exponentialBuckets", "if", "buckets", "is", "None", ":", "raise", "ValueError", "(", "_BAD_UNSET_BUCKETS", "%", "(", "u'exponential buckets'", ")", ")",...
39.206897
0.001717
def fields_dict(cls): """ Return an ordered dictionary of ``attrs`` attributes for a class, whose keys are the attribute names. :param type cls: Class to introspect. :raise TypeError: If *cls* is not a class. :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` cla...
[ "def", "fields_dict", "(", "cls", ")", ":", "if", "not", "isclass", "(", "cls", ")", ":", "raise", "TypeError", "(", "\"Passed object must be a class.\"", ")", "attrs", "=", "getattr", "(", "cls", ",", "\"__attrs_attrs__\"", ",", "None", ")", "if", "attrs", ...
35.230769
0.001063
def DictReader(file_obj, columns=None): # pylint: disable=invalid-name """ Reader for a parquet file object. This function is a generator returning an OrderedDict for each row of data in the parquet file. Nested values will be flattend into the top-level dict and can be referenced with '.' notatio...
[ "def", "DictReader", "(", "file_obj", ",", "columns", "=", "None", ")", ":", "# pylint: disable=invalid-name", "footer", "=", "_read_footer", "(", "file_obj", ")", "keys", "=", "columns", "if", "columns", "else", "[", "s", ".", "name", "for", "s", "in", "f...
42.578947
0.002418
def byteswap(fmt, data, offset=0): """Swap bytes in `data` according to `fmt`, starting at byte `offset` and return the result. `fmt` must be an iterable, iterating over number of bytes to swap. For example, the format string ``'24'`` applied to the bytes ``b'\\x00\\x11\\x22\\x33\\x44\\x55'`` will p...
[ "def", "byteswap", "(", "fmt", ",", "data", ",", "offset", "=", "0", ")", ":", "data", "=", "BytesIO", "(", "data", ")", "data", ".", "seek", "(", "offset", ")", "data_swapped", "=", "BytesIO", "(", ")", "for", "f", "in", "fmt", ":", "swapped", "...
32.111111
0.001681
def _parse_keypad(self, keypad_xml): """Parses a keypad device (the Visor receiver is technically a keypad too).""" keypad = Keypad(self._lutron, name=keypad_xml.get('Name'), integration_id=int(keypad_xml.get('IntegrationID'))) components = keypad_xml.find('Components...
[ "def", "_parse_keypad", "(", "self", ",", "keypad_xml", ")", ":", "keypad", "=", "Keypad", "(", "self", ".", "_lutron", ",", "name", "=", "keypad_xml", ".", "get", "(", "'Name'", ")", ",", "integration_id", "=", "int", "(", "keypad_xml", ".", "get", "(...
37.210526
0.009655
def connectordb(self): """Returns the ConnectorDB object that the logger uses. Raises an error if Logger isn't able to connect""" if self.__cdb is None: logging.debug("Logger: Connecting to " + self.serverurl) self.__cdb = ConnectorDB(self.apikey, url=self.serverurl) retu...
[ "def", "connectordb", "(", "self", ")", ":", "if", "self", ".", "__cdb", "is", "None", ":", "logging", ".", "debug", "(", "\"Logger: Connecting to \"", "+", "self", ".", "serverurl", ")", "self", ".", "__cdb", "=", "ConnectorDB", "(", "self", ".", "apike...
54.666667
0.009009
def _set_reference_channel_cb(self, w, idx): """This is the GUI callback for the control that sets the reference channel. """ chname = self.chnames[idx] self._set_reference_channel(chname)
[ "def", "_set_reference_channel_cb", "(", "self", ",", "w", ",", "idx", ")", ":", "chname", "=", "self", ".", "chnames", "[", "idx", "]", "self", ".", "_set_reference_channel", "(", "chname", ")" ]
37.166667
0.008772
def _InsertEvent(self, event, force_flush=False): """Inserts an event. Events are buffered in the form of documents and inserted to Elasticsearch when either forced to flush or when the flush interval (threshold) has been reached. Args: event (EventObject): event. force_flush (bool): T...
[ "def", "_InsertEvent", "(", "self", ",", "event", ",", "force_flush", "=", "False", ")", ":", "if", "event", ":", "event_document", "=", "{", "'index'", ":", "{", "'_index'", ":", "self", ".", "_index_name", ",", "'_type'", ":", "self", ".", "_document_t...
35.26087
0.008403
def value(self): """Returns the value of this Slot.""" if hasattr(self, '_value_decoded'): return self._value_decoded if self.value_blob is not None: encoded_value = self.value_blob.open().read() else: encoded_value = self.value_text self._value_decoded = json.loads(encoded_value...
[ "def", "value", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_value_decoded'", ")", ":", "return", "self", ".", "_value_decoded", "if", "self", ".", "value_blob", "is", "not", "None", ":", "encoded_value", "=", "self", ".", "value_blob", "...
30.25
0.010695
def get_analog(self, component_info=None, data=None, component_position=None): """Get analog data.""" components = [] append_components = components.append for _ in range(component_info.device_count): component_position, device = QRTPacket._get_exact( RTAnalog...
[ "def", "get_analog", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "components", "=", "[", "]", "append_components", "=", "components", ".", "append", "for", "_", "in", "range",...
43.217391
0.001969
def purge(gandi, email, background, force, alias): """Purge a mailbox.""" login, domain = email if alias: if not force: proceed = click.confirm('Are you sure to purge all aliases for ' 'mailbox %s@%s ?' % (login, domain)) if not proceed: ...
[ "def", "purge", "(", "gandi", ",", "email", ",", "background", ",", "force", ",", "alias", ")", ":", "login", ",", "domain", "=", "email", "if", "alias", ":", "if", "not", "force", ":", "proceed", "=", "click", ".", "confirm", "(", "'Are you sure to pu...
35.421053
0.001447
def equipable_classes(self): """ Returns a list of classes that _can_ use the item. """ sitem = self._schema_item return [c for c in sitem.get("used_by_classes", self.equipped.keys()) if c]
[ "def", "equipable_classes", "(", "self", ")", ":", "sitem", "=", "self", ".", "_schema_item", "return", "[", "c", "for", "c", "in", "sitem", ".", "get", "(", "\"used_by_classes\"", ",", "self", ".", "equipped", ".", "keys", "(", ")", ")", "if", "c", ...
42
0.014019
def bytes_from_decode_data(s): """copy from base64._bytes_from_decode_data """ if isinstance(s, (str, unicode)): try: return s.encode('ascii') except UnicodeEncodeError: raise NotValidParamError( 'String argument should contain only ASCII characters') ...
[ "def", "bytes_from_decode_data", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "(", "str", ",", "unicode", ")", ")", ":", "try", ":", "return", "s", ".", "encode", "(", "'ascii'", ")", "except", "UnicodeEncodeError", ":", "raise", "NotValidParam...
34
0.00159
def _prepare_docstrings(): """Assign docstrings to the corresponding attributes of class `Options` to make them available in the interactive mode of Python.""" if config.USEAUTODOC: source = inspect.getsource(Options) docstrings = source.split('"""')[3::2] attributes = [line.strip()...
[ "def", "_prepare_docstrings", "(", ")", ":", "if", "config", ".", "USEAUTODOC", ":", "source", "=", "inspect", ".", "getsource", "(", "Options", ")", "docstrings", "=", "source", ".", "split", "(", "'\"\"\"'", ")", "[", "3", ":", ":", "2", "]", "attrib...
52.3
0.00188
def factorize_and_solve(self,A,b): """ Factorizes A and sovles Ax=b. Parameters ---------- A : matrix b : ndarray Returns ------- x : ndarray """ A = coo_matrix(A) x = b.copy() self.mumps.set_centralized_assemble...
[ "def", "factorize_and_solve", "(", "self", ",", "A", ",", "b", ")", ":", "A", "=", "coo_matrix", "(", "A", ")", "x", "=", "b", ".", "copy", "(", ")", "self", ".", "mumps", ".", "set_centralized_assembled_values", "(", "A", ".", "data", ")", "self", ...
17.863636
0.009662
def format_date(self, value, format_): """ Format the date using Babel """ date_ = make_date(value) return dates.format_date(date_, format_, locale=self.lang)
[ "def", "format_date", "(", "self", ",", "value", ",", "format_", ")", ":", "date_", "=", "make_date", "(", "value", ")", "return", "dates", ".", "format_date", "(", "date_", ",", "format_", ",", "locale", "=", "self", ".", "lang", ")" ]
32.166667
0.010101
def build_options(kwargs=None): '''Build options for tabula-java Args: options (str, optional): Raw option string for tabula-java. pages (str, int, :obj:`list` of :obj:`int`, optional): An optional values specifying pages to extract from. It allows `str`,`int...
[ "def", "build_options", "(", "kwargs", "=", "None", ")", ":", "__options", "=", "[", "]", "if", "kwargs", "is", "None", ":", "kwargs", "=", "{", "}", "options", "=", "kwargs", ".", "get", "(", "'options'", ",", "''", ")", "# handle options described in s...
35.777778
0.001727
def execute(self, correlation_id, args): """ Executes the command given specific arguments as an input. Args: correlation_id: a unique correlation/transaction id args: command arguments Returns: an execution result. Rai...
[ "def", "execute", "(", "self", ",", "correlation_id", ",", "args", ")", ":", "return", "self", ".", "_intercepter", ".", "execute", "(", "_next", ",", "correlation_id", ",", "args", ")" ]
33.5
0.010373
async def call_on_response(self, data): """ Try to fill the gaps and strip last tweet from the response if its id is that of the first tweet of the last response Parameters ---------- data : list The response data """ since_id = self.kwargs.ge...
[ "async", "def", "call_on_response", "(", "self", ",", "data", ")", ":", "since_id", "=", "self", ".", "kwargs", ".", "get", "(", "self", ".", "param", ",", "0", ")", "+", "1", "if", "self", ".", "fill_gaps", ":", "if", "data", "[", "-", "1", "]",...
30.285714
0.002286
def _add_type_node(self, node, label): """Add a node representing a SubjectInfo type.""" child = node.add_child(name=label) child.add_feature(TYPE_NODE_TAG, True) return child
[ "def", "_add_type_node", "(", "self", ",", "node", ",", "label", ")", ":", "child", "=", "node", ".", "add_child", "(", "name", "=", "label", ")", "child", ".", "add_feature", "(", "TYPE_NODE_TAG", ",", "True", ")", "return", "child" ]
40.6
0.009662
def _make_job_id(job_id, prefix=None): """Construct an ID for a new job. :type job_id: str or ``NoneType`` :param job_id: the user-provided job ID :type prefix: str or ``NoneType`` :param prefix: (Optional) the user-provided prefix for a job ID :rtype: str :returns: A job ID """ i...
[ "def", "_make_job_id", "(", "job_id", ",", "prefix", "=", "None", ")", ":", "if", "job_id", "is", "not", "None", ":", "return", "job_id", "elif", "prefix", "is", "not", "None", ":", "return", "str", "(", "prefix", ")", "+", "str", "(", "uuid", ".", ...
25.833333
0.002075
def wsproto_demo(host, port): ''' Demonstrate wsproto: 0) Open TCP connection 1) Negotiate WebSocket opening handshake 2) Send a message and display response 3) Send ping and display pong 4) Negotiate WebSocket closing handshake :param stream: a socket stream ''' # 0) Open TCP...
[ "def", "wsproto_demo", "(", "host", ",", "port", ")", ":", "# 0) Open TCP connection", "print", "(", "'Connecting to {}:{}'", ".", "format", "(", "host", ",", "port", ")", ")", "conn", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "sock...
36.661972
0.000374
def read_folder(folder): """ Parameters ---------- folder : string Path to a folde with *.inkml files. Returns ------- list : Objects of the type HandwrittenData """ import glob recordings = [] for filename in natsorted(glob.glob("%s/*.inkml" % folder)): ...
[ "def", "read_folder", "(", "folder", ")", ":", "import", "glob", "recordings", "=", "[", "]", "for", "filename", "in", "natsorted", "(", "glob", ".", "glob", "(", "\"%s/*.inkml\"", "%", "folder", ")", ")", ":", "hw", "=", "read", "(", "filename", ")", ...
32.677419
0.000959
def main(argv=None): """The main entry point to Coverage. This is installed as the script entry point. """ if argv is None: argv = sys.argv[1:] try: start = time.clock() status = CoverageScript().command_line(argv) end = time.clock() if 0: print(...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "[", "1", ":", "]", "try", ":", "start", "=", "time", ".", "clock", "(", ")", "status", "=", "CoverageScript", "(", ")", ".", ...
30.764706
0.000927
def alter(self, interfaces): """ Used to provide the ability to alter the interfaces dictionary before it is returned from self.parse(). Required Arguments: interfaces The interfaces dictionary. Returns: interfaces dict """ # fixup ...
[ "def", "alter", "(", "self", ",", "interfaces", ")", ":", "# fixup some things", "for", "device", ",", "device_dict", "in", "interfaces", ".", "items", "(", ")", ":", "if", "len", "(", "device_dict", "[", "'inet4'", "]", ")", ">", "0", ":", "device_dict"...
37.40625
0.001629
def generate_element_class(tuple_instance): """Dynamically create a sub-class of PREMISElement given ``tuple_instance``, which is a tuple representing an XML data structure. """ schema = tuple_to_schema(tuple_instance) def defaults(self): return {} def schema_getter(self): retu...
[ "def", "generate_element_class", "(", "tuple_instance", ")", ":", "schema", "=", "tuple_to_schema", "(", "tuple_instance", ")", "def", "defaults", "(", "self", ")", ":", "return", "{", "}", "def", "schema_getter", "(", "self", ")", ":", "return", "schema", "...
29.611111
0.001818
def delete_api_key(self, api_key, **kwargs): # noqa: E501 """Delete API key. # noqa: E501 An endpoint for deleting the API key. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/api-keys/{apikey-id} -H 'Authorization: Bearer API_KEY'` # noqa: E501 This method makes ...
[ "def", "delete_api_key", "(", "self", ",", "api_key", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "return", "self", ".", "delet...
50.619048
0.001847
def cmd_feed(): """ Показывает последние операции в ленте. """ r = rocket.operations.cool_feed.get() r = handle_error(r) j = r.json() lines = [] for date, operations in sorted(list(j["dates"].items())): lines += [[ click.style("===== %s =====" % date, fg="blue", bol...
[ "def", "cmd_feed", "(", ")", ":", "r", "=", "rocket", ".", "operations", ".", "cool_feed", ".", "get", "(", ")", "r", "=", "handle_error", "(", "r", ")", "j", "=", "r", ".", "json", "(", ")", "lines", "=", "[", "]", "for", "date", ",", "operati...
26.625
0.001511
def napi_or(values, **kwargs): """Perform element-wise logical *or* operation on arrays. If *values* contains a non-array object with truth_ value **True**, the outcome will be an array of **True**\s with suitable shape without arrays being evaluated. Non-array objects with truth value **False** are om...
[ "def", "napi_or", "(", "values", ",", "*", "*", "kwargs", ")", ":", "arrays", "=", "[", "]", "result", "=", "None", "shapes", "=", "set", "(", ")", "for", "value", "in", "values", ":", "if", "isinstance", "(", "value", ",", "ndarray", ")", "and", ...
31.392157
0.001211
def labels(self): """ Returns symbol instances corresponding to labels in the current scope. """ return [x for x in self[self.current_scope].values() if x.class_ == CLASS.label]
[ "def", "labels", "(", "self", ")", ":", "return", "[", "x", "for", "x", "in", "self", "[", "self", ".", "current_scope", "]", ".", "values", "(", ")", "if", "x", ".", "class_", "==", "CLASS", ".", "label", "]" ]
41
0.014354
def get_BM_EOS(cryst, systems): """Calculate Birch-Murnaghan Equation of State for the crystal. The B-M equation of state is defined by: .. math:: P(V)= \\frac{B_0}{B'_0}\\left[ \\left({\\frac{V}{V_0}}\\right)^{-B'_0} - 1 \\right] It's coefficients are estimated using n single-po...
[ "def", "get_BM_EOS", "(", "cryst", ",", "systems", ")", ":", "pvdat", "=", "array", "(", "[", "[", "r", ".", "get_volume", "(", ")", ",", "get_pressure", "(", "r", ".", "get_stress", "(", ")", ")", ",", "norm", "(", "r", ".", "get_cell", "(", ")"...
33.545455
0.001053
def _error(self, message, start, end=None): """Raise a nice error, with the token highlighted.""" raise errors.EfilterParseError( source=self.source, start=start, end=end, message=message)
[ "def", "_error", "(", "self", ",", "message", ",", "start", ",", "end", "=", "None", ")", ":", "raise", "errors", ".", "EfilterParseError", "(", "source", "=", "self", ".", "source", ",", "start", "=", "start", ",", "end", "=", "end", ",", "message",...
53.25
0.009259
def _create_sub_el(doc, parent, tag, attrib, data=None): """Creates and xml element for the `doc` with the given `parent` and `tag` as the tagName. `attrib` should be a dictionary of string keys to primitives or dicts if the value is a dict, then the keys of the dict are joined with the `att...
[ "def", "_create_sub_el", "(", "doc", ",", "parent", ",", "tag", ",", "attrib", ",", "data", "=", "None", ")", ":", "el", "=", "doc", ".", "createElement", "(", "tag", ")", "if", "attrib", ":", "if", "(", "'id'", "in", "attrib", ")", "and", "(", "...
43.333333
0.000627
def node_statistics(docgraph): """print basic statistics about a node, e.g. layer/attribute counts""" print "Node statistics\n===============" layer_counts = Counter() attrib_counts = Counter() for node_id, node_attrs in docgraph.nodes_iter(data=True): for layer in node_attrs['layers']: ...
[ "def", "node_statistics", "(", "docgraph", ")", ":", "print", "\"Node statistics\\n===============\"", "layer_counts", "=", "Counter", "(", ")", "attrib_counts", "=", "Counter", "(", ")", "for", "node_id", ",", "node_attrs", "in", "docgraph", ".", "nodes_iter", "(...
38.6
0.001686
def _get_value_from_value_pb(value_pb): """Given a protobuf for a Value, get the correct value. The Cloud Datastore Protobuf API returns a Property Protobuf which has one value set and the rest blank. This function retrieves the the one value provided. Some work is done to coerce the return value...
[ "def", "_get_value_from_value_pb", "(", "value_pb", ")", ":", "value_type", "=", "value_pb", ".", "WhichOneof", "(", "\"value_type\"", ")", "if", "value_type", "==", "\"timestamp_value\"", ":", "result", "=", "_pb_timestamp_to_datetime", "(", "value_pb", ".", "times...
30.245902
0.001575
def get_object_header(self, ref): """ Use this method to quickly examine the type and size of the object behind the given ref. :note: The method will only suffer from the costs of command invocation once and reuses the command in subsequent calls. :return: (hexsha, type_str...
[ "def", "get_object_header", "(", "self", ",", "ref", ")", ":", "cmd", "=", "self", ".", "_get_persistent_cmd", "(", "\"cat_file_header\"", ",", "\"cat_file\"", ",", "batch_check", "=", "True", ")", "return", "self", ".", "__get_object_header", "(", "cmd", ",",...
46.9
0.008368
def get_bond_lengths(self, indices): """Return the distances between given atoms. Calculates the distance between the atoms with indices ``i`` and ``b``. The indices can be given in three ways: * As simple list ``[i, b]`` * As list of lists: ``[[i1, b1], [i2, b2]...]`` ...
[ "def", "get_bond_lengths", "(", "self", ",", "indices", ")", ":", "coords", "=", "[", "'x'", ",", "'y'", ",", "'z'", "]", "if", "isinstance", "(", "indices", ",", "pd", ".", "DataFrame", ")", ":", "i_pos", "=", "self", ".", "loc", "[", "indices", "...
36.793103
0.001826
def _lex(verbose=False): """Return LEX analyzer object for the MOF Compiler. As a side effect, the LEX table module for the MOF compiler gets created if it does not exist yet, or updated if its table version does not match the installed version of the `ply` package. To debug lex you may set debug=...
[ "def", "_lex", "(", "verbose", "=", "False", ")", ":", "return", "lex", ".", "lex", "(", "optimize", "=", "_optimize", ",", "lextab", "=", "_lextab", ",", "outputdir", "=", "_tabdir", ",", "debug", "=", "False", ",", "# debuglog = lex.PlyLogger(sys.stdout),"...
37.764706
0.00152
def packet(self): """Returns a string containing the packet's bytes No further parts should be added to the packet once this is done.""" if not self.finished: self.finished = 1 for question in self.questions: self.write_question(question) ...
[ "def", "packet", "(", "self", ")", ":", "if", "not", "self", ".", "finished", ":", "self", ".", "finished", "=", "1", "for", "question", "in", "self", ".", "questions", ":", "self", ".", "write_question", "(", "question", ")", "for", "answer", ",", "...
38.692308
0.00194
def clean(s, lowercase=True, replace_by_none=r'[^ \-\_A-Za-z0-9]+', replace_by_whitespace=r'[\-\_]', strip_accents=None, remove_brackets=True, encoding='utf-8', decode_error='strict'): """Clean string variables. Clean strings in the Series by removing unwanted tokens, whitespace and bra...
[ "def", "clean", "(", "s", ",", "lowercase", "=", "True", ",", "replace_by_none", "=", "r'[^ \\-\\_A-Za-z0-9]+'", ",", "replace_by_whitespace", "=", "r'[\\-\\_]'", ",", "strip_accents", "=", "None", ",", "remove_brackets", "=", "True", ",", "encoding", "=", "'utf...
30.650407
0.000257
def render(directory, opt): """Render any provided template. This includes the Secretfile, Vault policies, and inline AWS roles""" if not os.path.exists(directory) and not os.path.isdir(directory): os.mkdir(directory) a_secretfile = render_secretfile(opt) s_path = "%s/Secretfile" % director...
[ "def", "render", "(", "directory", ",", "opt", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", "and", "not", "os", ".", "path", ".", "isdir", "(", "directory", ")", ":", "os", ".", "mkdir", "(", "directory", ")", "...
42.606061
0.000695
def update_profile( self, profile, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates the specified profile and returns the updated result. Example: ...
[ "def", "update_profile", "(", "self", ",", "profile", ",", "update_mask", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "me...
38.05102
0.00183
def _lex(s): """ Lex the input string according to _tsql_lex_re. Yields (gid, token, line_number) """ s += '.' # make sure there's a terminator to know when to stop parsing lines = enumerate(s.splitlines(), 1) lineno = pos = 0 try: for lineno, line in lines: ...
[ "def", "_lex", "(", "s", ")", ":", "s", "+=", "'.'", "# make sure there's a terminator to know when to stop parsing", "lines", "=", "enumerate", "(", "s", ".", "splitlines", "(", ")", ",", "1", ")", "lineno", "=", "pos", "=", "0", "try", ":", "for", "linen...
32.36
0.0012
def _convert_priority(p_priority): """ Converts todo.txt priority to an iCalendar priority (RFC 2445). Priority A gets priority 1, priority B gets priority 5 and priority C-F get priorities 6-9. This scheme makes sure that clients that use "high", "medium" and "low" show the correct priority. "...
[ "def", "_convert_priority", "(", "p_priority", ")", ":", "result", "=", "0", "prio_map", "=", "{", "'A'", ":", "1", ",", "'B'", ":", "5", ",", "'C'", ":", "6", ",", "'D'", ":", "7", ",", "'E'", ":", "8", ",", "'F'", ":", "9", ",", "}", "try",...
25.862069
0.001285
def jdbc_datasource_present(name, description='', enabled=True, restype='datasource', vendor='mysql', sql_url='', sql_user='', ...
[ "def", "jdbc_datasource_present", "(", "name", ",", "description", "=", "''", ",", "enabled", "=", "True", ",", "restype", "=", "'datasource'", ",", "vendor", "=", "'mysql'", ",", "sql_url", "=", "''", ",", "sql_user", "=", "''", ",", "sql_password", "=", ...
36.911392
0.002004
def disconnect(self): """Disconnect from the device.""" self.target_device.disconnect() self.ctrl.disconnect() self.tail_disconnect(-1)
[ "def", "disconnect", "(", "self", ")", ":", "self", ".", "target_device", ".", "disconnect", "(", ")", "self", ".", "ctrl", ".", "disconnect", "(", ")", "self", ".", "tail_disconnect", "(", "-", "1", ")" ]
32.6
0.011976
def reset_failed(self, pk): """ reset failed counter :param pk: :return: """ TriggerService.objects.filter(consumer__name__id=pk).update(consumer_failed=0, provider_failed=0) TriggerService.objects.filter(provider__name__id=pk).update(consumer_failed=0, provid...
[ "def", "reset_failed", "(", "self", ",", "pk", ")", ":", "TriggerService", ".", "objects", ".", "filter", "(", "consumer__name__id", "=", "pk", ")", ".", "update", "(", "consumer_failed", "=", "0", ",", "provider_failed", "=", "0", ")", "TriggerService", "...
40.625
0.012048
def get_full_page_url(self, page_number, scheme=None): """Get the full, external URL for this page, optinally with the passed in URL scheme""" args = dict( request.view_args, _external=True, ) if scheme is not None: args['_scheme'] = scheme ...
[ "def", "get_full_page_url", "(", "self", ",", "page_number", ",", "scheme", "=", "None", ")", ":", "args", "=", "dict", "(", "request", ".", "view_args", ",", "_external", "=", "True", ",", ")", "if", "scheme", "is", "not", "None", ":", "args", "[", ...
30.214286
0.009174
def register_view(design_doc, full_set=True): """Model document decorator to register its design document view:: @register_view('dev_books') class Book(Document): __bucket_name__ = 'mybucket' doc_type = 'book' structure = { # snip snip ...
[ "def", "register_view", "(", "design_doc", ",", "full_set", "=", "True", ")", ":", "def", "_injector", "(", "doc", ")", ":", "if", "not", "isinstance", "(", "doc", ",", "type", ")", "or", "not", "issubclass", "(", "doc", ",", "Document", ")", ":", "r...
33.666667
0.001203
def contour(self, canvas, X, Y, C, Z=None, color=None, label=None, **kwargs): """ Make a contour plot at (X, Y) with heights/colors stored in C on the canvas. if Z is not None: make 3d contour plot at (X, Y, Z) with heights/colors stored in C on the canvas. the kwargs a...
[ "def", "contour", "(", "self", ",", "canvas", ",", "X", ",", "Y", ",", "C", ",", "Z", "=", "None", ",", "color", "=", "None", ",", "label", "=", "None", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError", "(", "\"Implement all plot fun...
55
0.013917
def profile(ctx, filepath, calltree=False): """ Run and profile a given Python script. :param str filepath: The filepath of the script to profile """ filepath = pathlib.Path(filepath) if not filepath.is_file(): log("profile", f"no such script {filepath!s}", LogLevel.ERROR) else: ...
[ "def", "profile", "(", "ctx", ",", "filepath", ",", "calltree", "=", "False", ")", ":", "filepath", "=", "pathlib", ".", "Path", "(", "filepath", ")", "if", "not", "filepath", ".", "is_file", "(", ")", ":", "log", "(", "\"profile\"", ",", "f\"no such s...
34.727273
0.001274
def pack_sources(sources, normalize=True): ''' Accepts list of dicts (or a string representing a list of dicts) and packs the key/value pairs into a single dict. ``'[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]'`` would become ``{"foo": "salt://foo.rpm", "bar": "salt://bar.rpm"}`` nor...
[ "def", "pack_sources", "(", "sources", ",", "normalize", "=", "True", ")", ":", "if", "normalize", "and", "'pkg.normalize_name'", "in", "__salt__", ":", "_normalize_name", "=", "__salt__", "[", "'pkg.normalize_name'", "]", "else", ":", "_normalize_name", "=", "l...
36.644444
0.001772
def load_markers(self, filename, attachments, max_frames=1e100): '''Load marker data and attachment preferences into the model. Parameters ---------- filename : str The name of a file containing marker data. This currently needs to be either a .C3D or a .CSV file...
[ "def", "load_markers", "(", "self", ",", "filename", ",", "attachments", ",", "max_frames", "=", "1e100", ")", ":", "self", ".", "markers", "=", "Markers", "(", "self", ")", "fn", "=", "filename", ".", "lower", "(", ")", "if", "fn", ".", "endswith", ...
42.96875
0.002134
def plot(self, joints, ax, target=None, show=False): """Plots the Chain using Matplotlib Parameters ---------- joints: list The list of the positions of each joint ax: matplotlib.axes.Axes A matplotlib axes target: numpy.array An optio...
[ "def", "plot", "(", "self", ",", "joints", ",", "ax", ",", "target", "=", "None", ",", "show", "=", "False", ")", ":", "from", ".", "import", "plot_utils", "if", "ax", "is", "None", ":", "# If ax is not given, create one", "ax", "=", "plot_utils", ".", ...
29.296296
0.002448
def scan_handler(parser, args): """Implement `scan` sub-command.""" opts = namespace_to_dict(args) opts.update({"ftp_debug": args.verbose >= 6}) target = make_target(args.target, opts) target.readonly = True root_depth = target.root_dir.count("/") start = time.time() dir_count = 1 fi...
[ "def", "scan_handler", "(", "parser", ",", "args", ")", ":", "opts", "=", "namespace_to_dict", "(", "args", ")", "opts", ".", "update", "(", "{", "\"ftp_debug\"", ":", "args", ".", "verbose", ">=", "6", "}", ")", "target", "=", "make_target", "(", "arg...
32.802469
0.001096
def bootstrap_legislative_office(self, election): """ For legislative offices, create page content for the legislative Body the Office belongs to AND the state-level Division. E.g., for a Texas U.S. Senate seat, create page content for: - U.S. Senate page - Texas...
[ "def", "bootstrap_legislative_office", "(", "self", ",", "election", ")", ":", "body", "=", "election", ".", "race", ".", "office", ".", "body", "body_division", "=", "election", ".", "race", ".", "office", ".", "body", ".", "jurisdiction", ".", "division", ...
40.036364
0.000887
def convert_to_numpy_str(data, length=None): """ Decodes data to Numpy unicode string (numpy.unicode\_). Decodes `data` to Numpy unicode string (UTF-32), which is ``numpy.unicode_``, or an array of them. If it can't be decoded, it is returned as is. Unsigned integers, Python string types (``str``, ...
[ "def", "convert_to_numpy_str", "(", "data", ",", "length", "=", "None", ")", ":", "# The method of conversion depends on its type.", "if", "isinstance", "(", "data", ",", "np", ".", "unicode_", ")", "or", "(", "isinstance", "(", "data", ",", "np", ".", "ndarra...
44.108696
0.001607
def _permission_denied_check(request): '''Internal function to verify that access to this webservice is allowed. Currently, based on the value of EUL_INDEXER_ALLOWED_IPS in settings.py. :param request: HttpRequest ''' allowed_ips = settings.EUL_INDEXER_ALLOWED_IPS if allowed_ips != "ANY" and n...
[ "def", "_permission_denied_check", "(", "request", ")", ":", "allowed_ips", "=", "settings", ".", "EUL_INDEXER_ALLOWED_IPS", "if", "allowed_ips", "!=", "\"ANY\"", "and", "not", "request", ".", "META", "[", "'REMOTE_ADDR'", "]", "in", "allowed_ips", ":", "return", ...
32.75
0.002475
def find_urls(observatory, frametype, start, end, on_gaps='error', connection=None, **connection_kw): """Find the URLs of files of a given data type in a GPS interval. See also -------- gwdatafind.http.HTTPConnection.find_urls FflConnection.find_urls for details on the underly...
[ "def", "find_urls", "(", "observatory", ",", "frametype", ",", "start", ",", "end", ",", "on_gaps", "=", "'error'", ",", "connection", "=", "None", ",", "*", "*", "connection_kw", ")", ":", "return", "connection", ".", "find_urls", "(", "observatory", ",",...
37.25
0.002183
def attr(key, value=None): ''' Access/write a SysFS attribute. If the attribute is a symlink, it's destination is returned :return: value or bool CLI example: .. code-block:: bash salt '*' sysfs.attr block/sda/queue/logical_block_size ''' key = target(key) if key is Fals...
[ "def", "attr", "(", "key", ",", "value", "=", "None", ")", ":", "key", "=", "target", "(", "key", ")", "if", "key", "is", "False", ":", "return", "False", "elif", "os", ".", "path", ".", "isdir", "(", "key", ")", ":", "return", "key", "elif", "...
21.181818
0.002053
def neg_log_perplexity(batch, model_predictions): """Calculate negative log perplexity.""" _, targets = batch model_predictions, targets = _make_list(model_predictions, targets) xent = [] for (prediction, target) in zip(model_predictions, targets): hot_target = layers.one_hot(target, prediction.shape[-1])...
[ "def", "neg_log_perplexity", "(", "batch", ",", "model_predictions", ")", ":", "_", ",", "targets", "=", "batch", "model_predictions", ",", "targets", "=", "_make_list", "(", "model_predictions", ",", "targets", ")", "xent", "=", "[", "]", "for", "(", "predi...
45.111111
0.016908
def sort_index(self): """ Sort the Series by the index. The sort modifies the Series inplace :return: nothing """ sort = sorted_list_indexes(self._index) # sort index self._index = blist([self._index[x] for x in sort]) if self._blist else [self._index[x] for x in...
[ "def", "sort_index", "(", "self", ")", ":", "sort", "=", "sorted_list_indexes", "(", "self", ".", "_index", ")", "# sort index", "self", ".", "_index", "=", "blist", "(", "[", "self", ".", "_index", "[", "x", "]", "for", "x", "in", "sort", "]", ")", ...
40.363636
0.008811
def devices(self): """ Return all devices.""" service_root = self.webservices['findme']['url'] return FindMyiPhoneServiceManager( service_root, self.session, self.params )
[ "def", "devices", "(", "self", ")", ":", "service_root", "=", "self", ".", "webservices", "[", "'findme'", "]", "[", "'url'", "]", "return", "FindMyiPhoneServiceManager", "(", "service_root", ",", "self", ".", "session", ",", "self", ".", "params", ")" ]
29
0.008368
def lsb_release(): """ Get the linux distribution information and return in an attribute dict The following attributes should be available: base, distributor_id, description, release, codename For example Ubuntu Lucid would return base = debian distributor_id = Ubuntu descripti...
[ "def", "lsb_release", "(", ")", ":", "output", "=", "run", "(", "'lsb_release -a'", ")", ".", "split", "(", "'\\n'", ")", "release", "=", "_AttributeDict", "(", "{", "}", ")", "for", "line", "in", "output", ":", "try", ":", "key", ",", "value", "=", ...
28.689655
0.012791
def _skip_spaces(string, idx): # type: (str, int) -> int """ Retrieves the next non-space character after idx index in the given string :param string: The string to look into :param idx: The base search index :return: The next non-space character index, -1 if not found """ i = idx f...
[ "def", "_skip_spaces", "(", "string", ",", "idx", ")", ":", "# type: (str, int) -> int", "i", "=", "idx", "for", "char", "in", "string", "[", "idx", ":", "]", ":", "if", "not", "char", ".", "isspace", "(", ")", ":", "return", "i", "i", "+=", "1", "...
25.6875
0.002347
def find_rootfs(conn, disk_root): """ Find the image's device root filesystem, and return its path. 1. Use :func:`guestfs.GuestFS.inspect_os` method. If it returns more than one root filesystem or None, try: 2. Find an exact match of `disk_root` from :func:`guestfs.GuestFS.list_filesyst...
[ "def", "find_rootfs", "(", "conn", ",", "disk_root", ")", ":", "rootfs", "=", "conn", ".", "inspect_os", "(", ")", "if", "not", "rootfs", "or", "len", "(", "rootfs", ")", ">", "1", ":", "filesystems", "=", "conn", ".", "list_filesystems", "(", ")", "...
36.722222
0.000737
def module_sys_modules_key(key): """ Check if a module is in the sys.modules dictionary in some manner. If so, return the key used in that dictionary. :param key: our key to the module. :returns: the key in sys.modules or None. """ moduleparts = key.split(".") for partnum, part in enum...
[ "def", "module_sys_modules_key", "(", "key", ")", ":", "moduleparts", "=", "key", ".", "split", "(", "\".\"", ")", "for", "partnum", ",", "part", "in", "enumerate", "(", "moduleparts", ")", ":", "modkey", "=", "\".\"", ".", "join", "(", "moduleparts", "[...
32.214286
0.002155
def _config(self) -> ExtensionConfig: """ Tells the processor to look for the specified pattern in node key only. Returns: The scanner configuration. """ return dict(pattern=self.__pattern__, search_in_keys=True, search_in_values=False)
[ "def", "_config", "(", "self", ")", "->", "ExtensionConfig", ":", "return", "dict", "(", "pattern", "=", "self", ".", "__pattern__", ",", "search_in_keys", "=", "True", ",", "search_in_values", "=", "False", ")" ]
45.166667
0.01087
def reindex(self, objs, conn=None): ''' reindex - Reindexes a given list of objects. Probably you want to do Model.objects.reindex() instead of this directly. @param objs list<IndexedRedisModel> - List of objects to reindex @param conn <redis.Redis or None> - Specific Redis connection or None to reuse '''...
[ "def", "reindex", "(", "self", ",", "objs", ",", "conn", "=", "None", ")", ":", "if", "conn", "is", "None", ":", "conn", "=", "self", ".", "_get_connection", "(", ")", "pipeline", "=", "conn", ".", "pipeline", "(", ")", "objDicts", "=", "[", "obj",...
37.1
0.026281
def reload(self, *modules): """Reload one or more plugins""" self.notify('before_reload') if 'configfiles' in self.config: # reload configfiles self.log.info('Reloading configuration...') cfg = utils.parse_config( self.server and 'server' or '...
[ "def", "reload", "(", "self", ",", "*", "modules", ")", ":", "self", ".", "notify", "(", "'before_reload'", ")", "if", "'configfiles'", "in", "self", ".", "config", ":", "# reload configfiles", "self", ".", "log", ".", "info", "(", "'Reloading configuration....
32.757576
0.001797
def daily_occurrences(self, dt=None, event=None): ''' Returns a queryset of for instances that have any overlap with a particular day. * ``dt`` may be either a datetime.datetime, datetime.date object, or ``None``. If ``None``, default to the current day. * ``event`` c...
[ "def", "daily_occurrences", "(", "self", ",", "dt", "=", "None", ",", "event", "=", "None", ")", ":", "dt", "=", "dt", "or", "datetime", ".", "now", "(", ")", "start", "=", "datetime", "(", "dt", ".", "year", ",", "dt", ".", "month", ",", "dt", ...
31.793103
0.002105
def caltrack_usage_per_day_predict( model_type, model_params, prediction_index, temperature_data, degree_day_method="daily", with_disaggregated=False, with_design_matrix=False, ): """ CalTRACK predict method. Given a model type, parameters, hourly temperatures, a :any:`pandas.Da...
[ "def", "caltrack_usage_per_day_predict", "(", "model_type", ",", "model_params", ",", "prediction_index", ",", "temperature_data", ",", "degree_day_method", "=", "\"daily\"", ",", "with_disaggregated", "=", "False", ",", "with_design_matrix", "=", "False", ",", ")", "...
36.139706
0.001584
def update(gandi, fqdn, name, type, value, ttl, file): """Update record entry for a domain. --file option will ignore other parameters and overwrite current zone content with provided file content. """ domains = gandi.dns.list() domains = [domain['fqdn'] for domain in domains] if fqdn not i...
[ "def", "update", "(", "gandi", ",", "fqdn", ",", "name", ",", "type", ",", "value", ",", "ttl", ",", "file", ")", ":", "domains", "=", "gandi", ".", "dns", ".", "list", "(", ")", "domains", "=", "[", "domain", "[", "'fqdn'", "]", "for", "domain",...
33.833333
0.000958
def new(self, fname=None, editorstack=None, text=None): """ Create a new file - Untitled fname=None --> fname will be 'untitledXX.py' but do not create file fname=<basestring> --> create file """ # If no text is provided, create default content empty = Fa...
[ "def", "new", "(", "self", ",", "fname", "=", "None", ",", "editorstack", "=", "None", ",", "text", "=", "None", ")", ":", "# If no text is provided, create default content\r", "empty", "=", "False", "try", ":", "if", "text", "is", "None", ":", "default_cont...
40.853659
0.000874
def load_instrument( self, instrument_name: str, mount: Union[types.Mount, str], tip_racks: List[Labware] = None, replace: bool = False) -> 'InstrumentContext': """ Load a specific instrument required by the protocol. This value will actually ...
[ "def", "load_instrument", "(", "self", ",", "instrument_name", ":", "str", ",", "mount", ":", "Union", "[", "types", ".", "Mount", ",", "str", "]", ",", "tip_racks", ":", "List", "[", "Labware", "]", "=", "None", ",", "replace", ":", "bool", "=", "Fa...
49.298507
0.000594
def load_toml_rest_api_config(filename): """Returns a RestApiConfig created by loading a TOML file from the filesystem. """ if not os.path.exists(filename): LOGGER.info( "Skipping rest api loading from non-existent config file: %s", filename) return RestApiConfig(...
[ "def", "load_toml_rest_api_config", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "LOGGER", ".", "info", "(", "\"Skipping rest api loading from non-existent config file: %s\"", ",", "filename", ")", "return", ...
37.875
0.000644
def tag_del(self, item, tag): """ Remove tag from the tags of item. :param item: item identifier :type item: str :param tag: tag name :type tag: str """ tags = list(self.item(item, "tags")) if tag in tags: tags.remove(tag) ...
[ "def", "tag_del", "(", "self", ",", "item", ",", "tag", ")", ":", "tags", "=", "list", "(", "self", ".", "item", "(", "item", ",", "\"tags\"", ")", ")", "if", "tag", "in", "tags", ":", "tags", ".", "remove", "(", "tag", ")", "self", ".", "item"...
26.846154
0.00831
def ssml_say_as(self, words, interpret_as=None, role=None, **kwargs): """ Create a <Say-As> element :param words: Words to be interpreted :param interpret-as: Specify the type of words are spoken :param role: Specify the format of the date when interpret-as is set to date ...
[ "def", "ssml_say_as", "(", "self", ",", "words", ",", "interpret_as", "=", "None", ",", "role", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "nest", "(", "SsmlSayAs", "(", "words", ",", "interpret_as", "=", "interpret_as", ","...
40.5
0.008048
def delete_port(context, id): """Delete a port. : param context: neutron api request context : param id: UUID representing the port to delete. """ LOG.info("delete_port %s for tenant %s" % (id, context.tenant_id)) port = db_api.port_find(context, id=id, scope=db_api.ONE) if not port: ...
[ "def", "delete_port", "(", "context", ",", "id", ")", ":", "LOG", ".", "info", "(", "\"delete_port %s for tenant %s\"", "%", "(", "id", ",", "context", ".", "tenant_id", ")", ")", "port", "=", "db_api", ".", "port_find", "(", "context", ",", "id", "=", ...
39.967742
0.000788
def simxLoadModel(clientID, modelPathAndName, options, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' baseHandle = ct.c_int() if (sys.version_info[0] == 3) and (type(modelPathAndName) is str): modelPathAndName=modelPathAndName.en...
[ "def", "simxLoadModel", "(", "clientID", ",", "modelPathAndName", ",", "options", ",", "operationMode", ")", ":", "baseHandle", "=", "ct", ".", "c_int", "(", ")", "if", "(", "sys", ".", "version_info", "[", "0", "]", "==", "3", ")", "and", "(", "type",...
55.125
0.008929
def set_n_gram(self, value): ''' setter ''' if isinstance(value, Ngram): self.__n_gram = value else: raise TypeError("The type of n_gram must be Ngram.")
[ "def", "set_n_gram", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Ngram", ")", ":", "self", ".", "__n_gram", "=", "value", "else", ":", "raise", "TypeError", "(", "\"The type of n_gram must be Ngram.\"", ")" ]
32.666667
0.00995
def fastrcnn_predictions(boxes, scores): """ Generate final results from predictions of all proposals. Args: boxes: n#classx4 floatbox in float32 scores: nx#class Returns: boxes: Kx4 scores: K labels: K """ assert boxes.shape[1] == cfg.DATA.NUM_CLASS ...
[ "def", "fastrcnn_predictions", "(", "boxes", ",", "scores", ")", ":", "assert", "boxes", ".", "shape", "[", "1", "]", "==", "cfg", ".", "DATA", ".", "NUM_CLASS", "assert", "scores", ".", "shape", "[", "1", "]", "==", "cfg", ".", "DATA", ".", "NUM_CLA...
39.513889
0.002058
def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ...
[ "def", "tablespace_remove", "(", "name", ",", "user", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "maintenance_db", "=", "None", ",", "password", "=", "None", ",", "runas", "=", "None", ")", ":", "query", "=", "'DROP TABLESPAC...
32.727273
0.00135
def clean(self): """ Validates the considered instance. """ super().clean() # At least a poster (user) or a session key must be associated with # the vote instance. if self.voter is None and self.anonymous_key is None: raise ValidationError(_('A user id or an anonymo...
[ "def", "clean", "(", "self", ")", ":", "super", "(", ")", ".", "clean", "(", ")", "# At least a poster (user) or a session key must be associated with", "# the vote instance.", "if", "self", ".", "voter", "is", "None", "and", "self", ".", "anonymous_key", "is", "N...
47.8
0.008214