text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def instantiate_interface(virtual_iface, config, loop): """Find a virtual interface by name and instantiate it Args: virtual_iface (string): The name of the pkg_resources entry point corresponding to the interface. It should be in group iotile.virtual_interface config (dict): A dic...
[ "def", "instantiate_interface", "(", "virtual_iface", ",", "config", ",", "loop", ")", ":", "# Allow the null virtual interface for testing", "if", "virtual_iface", "==", "'null'", ":", "return", "StandardDeviceServer", "(", "None", ",", "{", "}", ",", "loop", "=", ...
39.818182
27.363636
def t_IDENTIFER(self, t): r'\#?[a-zA-Z_][a-zA-Z_0-9]*' t.type = SpecParser.reserved.get(t.value, 'IDENTIFIER') return t
[ "def", "t_IDENTIFER", "(", "self", ",", "t", ")", ":", "t", ".", "type", "=", "SpecParser", ".", "reserved", ".", "get", "(", "t", ".", "value", ",", "'IDENTIFIER'", ")", "return", "t" ]
35
16.5
def allocate(self, amount, child=None, update=True): """ Allocate capital to Strategy. By default, capital is allocated recursively down the children, proportionally to the children's weights. If a child is specified, capital will be allocated to that specific child. Al...
[ "def", "allocate", "(", "self", ",", "amount", ",", "child", "=", "None", ",", "update", "=", "True", ")", ":", "# allocate to child", "if", "child", "is", "not", "None", ":", "if", "child", "not", "in", "self", ".", "children", ":", "c", "=", "Secur...
38.716981
17.358491
def pivot_wavelength(self): """Get the bandpass' pivot wavelength. Unlike calc_pivot_wavelength(), this function will use a cached value if available. """ wl = self.registry._pivot_wavelengths.get((self.telescope, self.band)) if wl is not None: return wl ...
[ "def", "pivot_wavelength", "(", "self", ")", ":", "wl", "=", "self", ".", "registry", ".", "_pivot_wavelengths", ".", "get", "(", "(", "self", ".", "telescope", ",", "self", ".", "band", ")", ")", "if", "wl", "is", "not", "None", ":", "return", "wl",...
31.642857
22.142857
def convert_attrs_to_bool(obj: Any, attrs: Iterable[str], default: bool = None) -> None: """ Applies :func:`convert_to_bool` to the specified attributes of an object, modifying it in place. """ for a in attrs: setattr(obj, a, convert_to_boo...
[ "def", "convert_attrs_to_bool", "(", "obj", ":", "Any", ",", "attrs", ":", "Iterable", "[", "str", "]", ",", "default", ":", "bool", "=", "None", ")", "->", "None", ":", "for", "a", "in", "attrs", ":", "setattr", "(", "obj", ",", "a", ",", "convert...
38.666667
14.888889
def create_1to1_bitmap(mask: str) -> Dict[str, str]: """ Create a bit map function (as a dictionary) for a given mask. e.g., for a mask :math:`m = 10` the return is a dictionary: >>> create_1to1_bitmap('10') ... { ... '00': '10', ... '01': '11', ... '10': '00', ... ...
[ "def", "create_1to1_bitmap", "(", "mask", ":", "str", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "n_bits", "=", "len", "(", "mask", ")", "form_string", "=", "\"{0:0\"", "+", "str", "(", "n_bits", ")", "+", "\"b}\"", "bit_map_dct", "=", "{",...
31
19.923077
def delete_vhost(self, name): """ Delete a vhost. :param name: The vhost name :type name: str """ self._api_delete('/api/vhosts/{0}'.format( urllib.parse.quote_plus(name) ))
[ "def", "delete_vhost", "(", "self", ",", "name", ")", ":", "self", ".", "_api_delete", "(", "'/api/vhosts/{0}'", ".", "format", "(", "urllib", ".", "parse", ".", "quote_plus", "(", "name", ")", ")", ")" ]
23.3
13.1
def _split_on_reappear(cls, df, p, id_offset): """Assign a new identity to an objects that appears after disappearing previously. Works on `df` in-place. :param df: data frame :param p: presence :param id_offset: offset added to new ids :return: """ next_...
[ "def", "_split_on_reappear", "(", "cls", ",", "df", ",", "p", ",", "id_offset", ")", ":", "next_id", "=", "id_offset", "+", "1", "added_ids", "=", "[", "]", "nt", "=", "p", ".", "sum", "(", "0", ")", "start", "=", "np", ".", "argmax", "(", "p", ...
32.83871
13.258065
def in6_getnsmac(a): # return multicast Ethernet address associated with multicast v6 destination """ Return the multicast mac address associated with provided IPv6 address. Passed address must be in network format. """ a = struct.unpack('16B', a)[-4:] mac = '33:33:' mac += (':'.join(map(l...
[ "def", "in6_getnsmac", "(", "a", ")", ":", "# return multicast Ethernet address associated with multicast v6 destination", "a", "=", "struct", ".", "unpack", "(", "'16B'", ",", "a", ")", "[", "-", "4", ":", "]", "mac", "=", "'33:33:'", "mac", "+=", "(", "':'",...
35
20
def examples(self): """Return example functions in the space. These are created by discretizing the examples in the underlying `fspace`. See Also -------- odl.space.fspace.FunctionSpace.examples """ for name, elem in self.fspace.examples: yie...
[ "def", "examples", "(", "self", ")", ":", "for", "name", ",", "elem", "in", "self", ".", "fspace", ".", "examples", ":", "yield", "(", "name", ",", "self", ".", "element", "(", "elem", ")", ")" ]
28.166667
18.5
def MGMT_COMM_GET(self, Addr='ff02::1', TLVs=[]): """send MGMT_COMM_GET command Returns: True: successful to send MGMT_COMM_GET False: fail to send MGMT_COMM_GET """ print '%s call MGMT_COMM_GET' % self.port try: cmd = 'commissioner mgmtget' ...
[ "def", "MGMT_COMM_GET", "(", "self", ",", "Addr", "=", "'ff02::1'", ",", "TLVs", "=", "[", "]", ")", ":", "print", "'%s call MGMT_COMM_GET'", "%", "self", ".", "port", "try", ":", "cmd", "=", "'commissioner mgmtget'", "if", "len", "(", "TLVs", ")", "!=",...
30.090909
20
def _get_YYTfactor(self, Y): """ find a matrix L which satisfies LLT = YYT. Note that L may have fewer columns than Y. """ N, D = Y.shape if (N>=D): return Y.view(np.ndarray) else: return jitchol(tdot(Y))
[ "def", "_get_YYTfactor", "(", "self", ",", "Y", ")", ":", "N", ",", "D", "=", "Y", ".", "shape", "if", "(", "N", ">=", "D", ")", ":", "return", "Y", ".", "view", "(", "np", ".", "ndarray", ")", "else", ":", "return", "jitchol", "(", "tdot", "...
25
13.363636
def batch_delete_attributes(self, domain_or_name, items): """ Delete multiple items in a domain. :type domain_or_name: string or :class:`boto.sdb.domain.Domain` object. :param domain_or_name: Either the name of a domain or a Domain object :type items: dict or dict-like ...
[ "def", "batch_delete_attributes", "(", "self", ",", "domain_or_name", ",", "items", ")", ":", "domain", ",", "domain_name", "=", "self", ".", "get_domain_and_name", "(", "domain_or_name", ")", "params", "=", "{", "'DomainName'", ":", "domain_name", "}", "self", ...
47.12
21.52
def grant_sudo_privileges(request, max_age=COOKIE_AGE): """ Assigns a random token to the user's session that allows them to have elevated permissions """ user = getattr(request, 'user', None) # If there's not a user on the request, just noop if user is None: return if not user...
[ "def", "grant_sudo_privileges", "(", "request", ",", "max_age", "=", "COOKIE_AGE", ")", ":", "user", "=", "getattr", "(", "request", ",", "'user'", ",", "None", ")", "# If there's not a user on the request, just noop", "if", "user", "is", "None", ":", "return", ...
31.545455
16
def _EvaluateExpression(frame, expression): """Compiles and evaluates watched expression. Args: frame: evaluation context. expression: watched expression to compile and evaluate. Returns: (False, status) on error or (True, value) on success. """ try: code = compile(expression, '<watched_expr...
[ "def", "_EvaluateExpression", "(", "frame", ",", "expression", ")", ":", "try", ":", "code", "=", "compile", "(", "expression", ",", "'<watched_expression>'", ",", "'eval'", ")", "except", "(", "TypeError", ",", "ValueError", ")", "as", "e", ":", "# expressi...
30.432432
15.72973
def add(self, dist): """Add `dist` if we ``can_add()`` it and it has not already been added """ if self.can_add(dist) and dist.has_version(): dists = self._distmap.setdefault(dist.key, []) if dist not in dists: dists.append(dist) dists.sort...
[ "def", "add", "(", "self", ",", "dist", ")", ":", "if", "self", ".", "can_add", "(", "dist", ")", "and", "dist", ".", "has_version", "(", ")", ":", "dists", "=", "self", ".", "_distmap", ".", "setdefault", "(", "dist", ".", "key", ",", "[", "]", ...
45.375
12.5
def plugins(self): """ Get the set of plugins that this field may display. """ from fluent_contents import extensions if self._plugins is None: return extensions.plugin_pool.get_plugins() else: try: return extensions.plugin_pool.get...
[ "def", "plugins", "(", "self", ")", ":", "from", "fluent_contents", "import", "extensions", "if", "self", ".", "_plugins", "is", "None", ":", "return", "extensions", ".", "plugin_pool", ".", "get_plugins", "(", ")", "else", ":", "try", ":", "return", "exte...
50.666667
28.833333
def run(fn, blocksize, seed, c, delta): """Run the encoder until the channel is broken, signalling that the receiver has successfully reconstructed the file """ with open(fn, 'rb') as f: for block in encode.encoder(f, blocksize, seed, c, delta): sys.stdout.buffer.write(block)
[ "def", "run", "(", "fn", ",", "blocksize", ",", "seed", ",", "c", ",", "delta", ")", ":", "with", "open", "(", "fn", ",", "'rb'", ")", "as", "f", ":", "for", "block", "in", "encode", ".", "encoder", "(", "f", ",", "blocksize", ",", "seed", ",",...
38.375
11.5
def download_dataset( dataset_name, file_path, task=None, dataset_attributes=None, **kwargs): """Downloads the given dataset from dataset store. Parameters ---------- dataset_name : str The name of the dataset to upload. file_path : str The full path to the file to upload ...
[ "def", "download_dataset", "(", "dataset_name", ",", "file_path", ",", "task", "=", "None", ",", "dataset_attributes", "=", "None", ",", "*", "*", "kwargs", ")", ":", "fname", "=", "ntpath", ".", "basename", "(", "file_path", ")", "blob_name", "=", "_blob_...
38.727273
16.977273
def do_open(self, args, arguments): """ :: Usage: open FILENAME ARGUMENTS: FILENAME the file to open in the cwd if . is specified. If file in in cwd you must specify it with ./FILENAME ...
[ "def", "do_open", "(", "self", ",", "args", ",", "arguments", ")", ":", "filename", "=", "arguments", "[", "'FILENAME'", "]", "filename", "=", "self", ".", "_expand_filename", "(", "filename", ")", "Console", ".", "ok", "(", "\"open {0}\"", ".", "format", ...
31.483871
20.516129
def _class_defining_method(meth): # pragma: no cover '''Gets the name of the class that defines meth. Adapted from http://stackoverflow.com/questions/3589311/get-defining-class-of-unbound-method-object-in-python-3/25959545#25959545. ''' if inspect.ismethod(meth): for cls in inspect.getmro(...
[ "def", "_class_defining_method", "(", "meth", ")", ":", "# pragma: no cover", "if", "inspect", ".", "ismethod", "(", "meth", ")", ":", "for", "cls", "in", "inspect", ".", "getmro", "(", "meth", ".", "__self__", ".", "__class__", ")", ":", "if", "cls", "....
46.6875
23.4375
def canonical_statistics_dtype(spanning_cluster=True): """ The NumPy Structured Array type for canonical statistics Helper function Parameters ---------- spanning_cluster : bool, optional Whether to detect a spanning cluster or not. Defaults to ``True``. Returns ------...
[ "def", "canonical_statistics_dtype", "(", "spanning_cluster", "=", "True", ")", ":", "fields", "=", "list", "(", ")", "if", "spanning_cluster", ":", "fields", ".", "extend", "(", "[", "(", "'percolation_probability'", ",", "'float64'", ")", ",", "]", ")", "f...
25.647059
19.294118
def _ReadEncodedData(self, read_size): """Reads encoded data from the file-like object. Args: read_size (int): number of bytes of encoded data to read. Returns: int: number of bytes of encoded data read. """ encoded_data = self._file_object.read(read_size) read_count = len(encoded...
[ "def", "_ReadEncodedData", "(", "self", ",", "read_size", ")", ":", "encoded_data", "=", "self", ".", "_file_object", ".", "read", "(", "read_size", ")", "read_count", "=", "len", "(", "encoded_data", ")", "self", ".", "_encoded_data", "=", "b''", ".", "jo...
26.333333
22.190476
def get_changes(self, dest_attr, new_name=None, resources=None, task_handle=taskhandle.NullTaskHandle()): """Return the changes needed for this refactoring Parameters: - `dest_attr`: the name of the destination attribute - `new_name`: the name of the new method; if ...
[ "def", "get_changes", "(", "self", ",", "dest_attr", ",", "new_name", "=", "None", ",", "resources", "=", "None", ",", "task_handle", "=", "taskhandle", ".", "NullTaskHandle", "(", ")", ")", ":", "changes", "=", "ChangeSet", "(", "'Moving method <%s>'", "%",...
44.978261
19.76087
def AuxPlane(s1, d1, r1): """ Get Strike and dip of second plane. Adapted from MATLAB script `bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_ written by Andy Michael and Oliver Boyd. """ r2d = 180 / np.pi z = (s1 + 90) / r2d z2 = d1 / r2d z3 = r1 / r2d...
[ "def", "AuxPlane", "(", "s1", ",", "d1", ",", "r1", ")", ":", "r2d", "=", "180", "/", "np", ".", "pi", "z", "=", "(", "s1", "+", "90", ")", "/", "r2d", "z2", "=", "d1", "/", "r2d", "z3", "=", "r1", "/", "r2d", "# slick vector in plane 1", "sl...
27.457143
17.971429
def _recv_thread(self): """ Internal thread to iterate over source messages and dispatch callbacks. """ for msg, metadata in self._source: if msg.msg_type: self._call(msg, **metadata) # Break any upstream iterators for sink in self._sinks: ...
[ "def", "_recv_thread", "(", "self", ")", ":", "for", "msg", ",", "metadata", "in", "self", ".", "_source", ":", "if", "msg", ".", "msg_type", ":", "self", ".", "_call", "(", "msg", ",", "*", "*", "metadata", ")", "# Break any upstream iterators", "for", ...
31.692308
10.615385
def _create(self, cache_file): """Create the tables needed to store the information.""" conn = sqlite3.connect(cache_file) cur = conn.cursor() cur.execute("PRAGMA foreign_keys = ON") cur.execute(''' CREATE TABLE jobs( hash TEXT NOT NULL UNIQUE PRIMARY ...
[ "def", "_create", "(", "self", ",", "cache_file", ")", ":", "conn", "=", "sqlite3", ".", "connect", "(", "cache_file", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "\"PRAGMA foreign_keys = ON\"", ")", "cur", ".", "execute...
38
19.294118
def get_max_col_num(mention): """Return the largest column number that a Mention occupies. :param mention: The Mention to evaluate. If a candidate is given, default to its last Mention. :rtype: integer or None """ span = _to_span(mention, idx=-1) if span.sentence.is_tabular(): r...
[ "def", "get_max_col_num", "(", "mention", ")", ":", "span", "=", "_to_span", "(", "mention", ",", "idx", "=", "-", "1", ")", "if", "span", ".", "sentence", ".", "is_tabular", "(", ")", ":", "return", "span", ".", "sentence", ".", "cell", ".", "col_en...
30.916667
14.666667
def overloaded(func): """ Introduces a new overloaded function and registers its first implementation. """ fn = unwrap(func) ensure_function(fn) def dispatcher(*args, **kwargs): resolved = None if dispatcher.__complex_parameters: cache_key_pos = [] cache...
[ "def", "overloaded", "(", "func", ")", ":", "fn", "=", "unwrap", "(", "func", ")", "ensure_function", "(", "fn", ")", "def", "dispatcher", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "resolved", "=", "None", "if", "dispatcher", ".", "__compl...
37.86747
16.903614
def classify(self, text=u''): """ Predicts the Language of a given text. :param text: Unicode text to be classified. """ text = self.lm.normalize(text) tokenz = LM.tokenize(text, mode='c') result = self.lm.calculate(doc_terms=tokenz) #print 'Karbasa:', self....
[ "def", "classify", "(", "self", ",", "text", "=", "u''", ")", ":", "text", "=", "self", ".", "lm", ".", "normalize", "(", "text", ")", "tokenz", "=", "LM", ".", "tokenize", "(", "text", ",", "mode", "=", "'c'", ")", "result", "=", "self", ".", ...
32.333333
15.066667
def _parse_profile(profile): ''' From a pillar key, or a dictionary, return index and host keys. ''' if isinstance(profile, string_types): _profile = __salt__['config.option'](profile) if not _profile: msg = 'Pillar key for profile {0} not found.'.format(profile) ...
[ "def", "_parse_profile", "(", "profile", ")", ":", "if", "isinstance", "(", "profile", ",", "string_types", ")", ":", "_profile", "=", "__salt__", "[", "'config.option'", "]", "(", "profile", ")", "if", "not", "_profile", ":", "msg", "=", "'Pillar key for pr...
33.428571
17.428571
def get_mysql_credentials(cfg_file): """Get the credentials and database name from options in config file.""" try: parser = ConfigParser.ConfigParser() cfg_fp = open(cfg_file) parser.readfp(cfg_fp) cfg_fp.close() except ConfigParser.NoOptionError: cfg_fp.close() ...
[ "def", "get_mysql_credentials", "(", "cfg_file", ")", ":", "try", ":", "parser", "=", "ConfigParser", ".", "ConfigParser", "(", ")", "cfg_fp", "=", "open", "(", "cfg_file", ")", "parser", ".", "readfp", "(", "cfg_fp", ")", "cfg_fp", ".", "close", "(", ")...
33.456522
19.152174
async def publish(self, message): """Pushes data to a listener.""" try: self.write('data: {}\n\n'.format(message)) await self.flush() except StreamClosedError: self.finished = True
[ "async", "def", "publish", "(", "self", ",", "message", ")", ":", "try", ":", "self", ".", "write", "(", "'data: {}\\n\\n'", ".", "format", "(", "message", ")", ")", "await", "self", ".", "flush", "(", ")", "except", "StreamClosedError", ":", "self", "...
34.285714
10.142857
def label(self, name, value, cluster_ids=None): """Assign a label to clusters. Example: `quality 3` """ if cluster_ids is None: cluster_ids = self.cluster_view.selected if not hasattr(cluster_ids, '__len__'): cluster_ids = [cluster_ids] if len(cl...
[ "def", "label", "(", "self", ",", "name", ",", "value", ",", "cluster_ids", "=", "None", ")", ":", "if", "cluster_ids", "is", "None", ":", "cluster_ids", "=", "self", ".", "cluster_view", ".", "selected", "if", "not", "hasattr", "(", "cluster_ids", ",", ...
32.357143
13.285714
def getCellStr(self, x, y): # TODO: refactor regarding issue #11 """ return a string representation of the cell located at x,y. """ c = self.board.getCell(x, y) if c == 0: return '.' if self.__azmode else ' .' elif self.__azmode: az = {} ...
[ "def", "getCellStr", "(", "self", ",", "x", ",", "y", ")", ":", "# TODO: refactor regarding issue #11", "c", "=", "self", ".", "board", ".", "getCell", "(", "x", ",", "y", ")", "if", "c", "==", "0", ":", "return", "'.'", "if", "self", ".", "__azmode"...
27.16
19.88
def associate_azure_publisher(self, publisher_name, azure_publisher_id): """AssociateAzurePublisher. [Preview API] :param str publisher_name: :param str azure_publisher_id: :rtype: :class:`<AzurePublisher> <azure.devops.v5_0.gallery.models.AzurePublisher>` """ rou...
[ "def", "associate_azure_publisher", "(", "self", ",", "publisher_name", ",", "azure_publisher_id", ")", ":", "route_values", "=", "{", "}", "if", "publisher_name", "is", "not", "None", ":", "route_values", "[", "'publisherName'", "]", "=", "self", ".", "_seriali...
53.894737
21.473684
def get(self, hook_id): """Get a webhook.""" path = '/'.join(['notification', 'webhook', hook_id]) return self.rachio.get(path)
[ "def", "get", "(", "self", ",", "hook_id", ")", ":", "path", "=", "'/'", ".", "join", "(", "[", "'notification'", ",", "'webhook'", ",", "hook_id", "]", ")", "return", "self", ".", "rachio", ".", "get", "(", "path", ")" ]
37
10.5
def get_all_xml_file_paths(self, raw_data_directory: str) -> List[str]: """ Loads all XML-files that are located in the folder. :param raw_data_directory: Path to the raw directory, where the MUSCIMA++ dataset was extracted to """ raw_data_directory = os.path.join(raw_data_directory, "v1...
[ "def", "get_all_xml_file_paths", "(", "self", ",", "raw_data_directory", ":", "str", ")", "->", "List", "[", "str", "]", ":", "raw_data_directory", "=", "os", ".", "path", ".", "join", "(", "raw_data_directory", ",", "\"v1.0\"", ",", "\"data\"", ",", "\"crop...
68.142857
33.571429
def get_thumbprint(self): """ Calculates the current thumbprint of the item being tracked. """ extensions = self.extensions.split(' ') name_str = ' -or '.join('-name "%s"' % ext for ext in extensions) cmd = 'find ' + self.base_dir + r' -type f \( ' + name_str + r' \) -exe...
[ "def", "get_thumbprint", "(", "self", ")", ":", "extensions", "=", "self", ".", "extensions", ".", "split", "(", "' '", ")", "name_str", "=", "' -or '", ".", "join", "(", "'-name \"%s\"'", "%", "ext", "for", "ext", "in", "extensions", ")", "cmd", "=", ...
47.375
21.125
def _read_loop(self, data=''): """ Read loop for gathering bytes from the server in a buffer of maximum MAX_CONTROL_LINE_SIZE, then received bytes are streamed to the parsing callback for processing. """ while True: if not self.is_connected or self.is_connecti...
[ "def", "_read_loop", "(", "self", ",", "data", "=", "''", ")", ":", "while", "True", ":", "if", "not", "self", ".", "is_connected", "or", "self", ".", "is_connecting", "or", "self", ".", "io", ".", "closed", "(", ")", ":", "break", "try", ":", "yie...
39.45
17.75
def do_IDENT(self, service_name: str, source: list, *args, **kwargs) -> None: """ Perform identification of a service to a binary representation. Args: service_name: human readable name for service source: zmq representation for the socket source """ self...
[ "def", "do_IDENT", "(", "self", ",", "service_name", ":", "str", ",", "source", ":", "list", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "None", ":", "self", ".", "logger", ".", "info", "(", "' IDENT %s as %s'", ",", "service_name", ",", "s...
42.3
21.5
def parts(self): """An object providing sequence-like access to the components in the filesystem path.""" # We cache the tuple to avoid building a new one each time .parts # is accessed. XXX is this necessary? try: return self._pparts except AttributeError: ...
[ "def", "parts", "(", "self", ")", ":", "# We cache the tuple to avoid building a new one each time .parts", "# is accessed. XXX is this necessary?", "try", ":", "return", "self", ".", "_pparts", "except", "AttributeError", ":", "self", ".", "_pparts", "=", "tuple", "(", ...
38.7
12.4
def keyframe(self, keyframe): """Set keyframe.""" if self._keyframe == keyframe: return if self._keyframe is not None: raise RuntimeError('cannot reset keyframe') if len(self._offsetscounts[0]) != len(keyframe.dataoffsets): raise RuntimeError('incompat...
[ "def", "keyframe", "(", "self", ",", "keyframe", ")", ":", "if", "self", ".", "_keyframe", "==", "keyframe", ":", "return", "if", "self", ".", "_keyframe", "is", "not", "None", ":", "raise", "RuntimeError", "(", "'cannot reset keyframe'", ")", "if", "len",...
40.875
15.6875
def teleport_camera(self, location, rotation): """Queue up a teleport camera command to stop the day cycle. By the next tick, the camera's location and rotation will be updated """ self._should_write_to_command_buffer = True command_to_send = TeleportCameraCommand(location, rotat...
[ "def", "teleport_camera", "(", "self", ",", "location", ",", "rotation", ")", ":", "self", ".", "_should_write_to_command_buffer", "=", "True", "command_to_send", "=", "TeleportCameraCommand", "(", "location", ",", "rotation", ")", "self", ".", "_commands", ".", ...
52.857143
13
def add_edge(self, u, v, **kwargs): """ Add an edge between u and v. The nodes u and v will be automatically added if they are not already in the graph Parameters ---------- u,v : nodes Nodes can be any hashable python object. Examples ...
[ "def", "add_edge", "(", "self", ",", "u", ",", "v", ",", "*", "*", "kwargs", ")", ":", "if", "u", "==", "v", ":", "raise", "ValueError", "(", "'Self loops are not allowed.'", ")", "if", "u", "in", "self", ".", "nodes", "(", ")", "and", "v", "in", ...
34.538462
21.307692
def on_step_end(self, step, logs): """ Update progression bar at the end of each step """ if self.info_names is None: self.info_names = logs['info'].keys() values = [('reward', logs['reward'])] if KERAS_VERSION > '2.1.3': self.progbar.update((self.step % self.inte...
[ "def", "on_step_end", "(", "self", ",", "step", ",", "logs", ")", ":", "if", "self", ".", "info_names", "is", "None", ":", "self", ".", "info_names", "=", "logs", "[", "'info'", "]", ".", "keys", "(", ")", "values", "=", "[", "(", "'reward'", ",", ...
47.538462
15.846154
def _lengstr(obj): '''Object length as a string. ''' n = leng(obj) if n is None: # no len r = '' elif n > _len(obj): # extended r = ' leng %d!' % n else: r = ' leng %d' % n return r
[ "def", "_lengstr", "(", "obj", ")", ":", "n", "=", "leng", "(", "obj", ")", "if", "n", "is", "None", ":", "# no len", "r", "=", "''", "elif", "n", ">", "_len", "(", "obj", ")", ":", "# extended", "r", "=", "' leng %d!'", "%", "n", "else", ":", ...
20.181818
19.818182
def set( self, key, value, loader_identifier=None, tomlfy=False, dotted_lookup=True, is_secret=False, ): """Set a value storing references for the loader :param key: The key to store :param value: The value to store :param load...
[ "def", "set", "(", "self", ",", "key", ",", "value", ",", "loader_identifier", "=", "None", ",", "tomlfy", "=", "False", ",", "dotted_lookup", "=", "True", ",", "is_secret", "=", "False", ",", ")", ":", "if", "\".\"", "in", "key", "and", "dotted_lookup...
37.066667
20.644444
def close(self): """Tell the process to exit """ try: self.p.stdin.write(bytes("X\n","utf-8")) self.p.stdin.flush() except IOError: self.report("could not send exit command") self.p.wait() # wait until the process is closed try: ...
[ "def", "close", "(", "self", ")", ":", "try", ":", "self", ".", "p", ".", "stdin", ".", "write", "(", "bytes", "(", "\"X\\n\"", ",", "\"utf-8\"", ")", ")", "self", ".", "p", ".", "stdin", ".", "flush", "(", ")", "except", "IOError", ":", "self", ...
32.076923
15.615385
def remove_non_latin(input_string, also_keep=None): """Remove non-Latin characters. `also_keep` should be a list which will add chars (e.g. punctuation) that will not be filtered. """ if also_keep: also_keep += [' '] else: also_keep = [' '] latin_chars = 'ABCDEFGHIJKLMNOPQRST...
[ "def", "remove_non_latin", "(", "input_string", ",", "also_keep", "=", "None", ")", ":", "if", "also_keep", ":", "also_keep", "+=", "[", "' '", "]", "else", ":", "also_keep", "=", "[", "' '", "]", "latin_chars", "=", "'ABCDEFGHIJKLMNOPQRSTUVWXYZ'", "latin_char...
35
14.714286
def slot_availability_array(events, slots): """ Return a numpy array mapping events to slots - Rows corresponds to events - Columns correspond to stags Array has value 0 if event cannot be scheduled in a given slot (1 otherwise) """ array = np.ones((len(events), len(slots))) for ro...
[ "def", "slot_availability_array", "(", "events", ",", "slots", ")", ":", "array", "=", "np", ".", "ones", "(", "(", "len", "(", "events", ")", ",", "len", "(", "slots", ")", ")", ")", "for", "row", ",", "event", "in", "enumerate", "(", "events", ")...
31.875
14.375
def iscached(self): """ Get whether object is cached (Spark only). """ if self.mode == 'spark': return self.tordd().is_cached else: notsupported(self.mode)
[ "def", "iscached", "(", "self", ")", ":", "if", "self", ".", "mode", "==", "'spark'", ":", "return", "self", ".", "tordd", "(", ")", ".", "is_cached", "else", ":", "notsupported", "(", "self", ".", "mode", ")" ]
26.5
9
def send_location(self, number, name, url, latitude, longitude): """ Send location message :param str number: phone number with cc (country code) :param str name: indentifier for the location :param str url: location url :param str longitude: location longitude :p...
[ "def", "send_location", "(", "self", ",", "number", ",", "name", ",", "url", ",", "latitude", ",", "longitude", ")", ":", "location_message", "=", "LocationMediaMessageProtocolEntity", "(", "latitude", ",", "longitude", ",", "name", ",", "url", ",", "encoding"...
48.615385
17.076923
def _init_metadata(self): """stub""" ItemTextsFormRecord._init_metadata(self) ItemFilesFormRecord._init_metadata(self) super(ItemTextsAndFilesMixin, self)._init_metadata()
[ "def", "_init_metadata", "(", "self", ")", ":", "ItemTextsFormRecord", ".", "_init_metadata", "(", "self", ")", "ItemFilesFormRecord", ".", "_init_metadata", "(", "self", ")", "super", "(", "ItemTextsAndFilesMixin", ",", "self", ")", ".", "_init_metadata", "(", ...
39.8
10.2
def enable(cls, allow_net_connect=True): """Enables HTTPretty. When ``allow_net_connect`` is ``False`` any connection to an unregistered uri will throw :py:class:`httpretty.errors.UnmockedError`. .. testcode:: import re, json import httpretty httpretty.enable(...
[ "def", "enable", "(", "cls", ",", "allow_net_connect", "=", "True", ")", ":", "cls", ".", "allow_net_connect", "=", "allow_net_connect", "cls", ".", "_is_enabled", "=", "True", "# Some versions of python internally shadowed the", "# SocketType variable incorrectly https://b...
40.25
25.328947
def DEBUG_ON_RESPONSE(self, statusCode, responseHeader, data): ''' Update current frame with response Current frame index will be attached to responseHeader ''' if self.DEBUG_FLAG: # pragma no branch (Flag always set in tests) self._frameBuffer[self._frameCount][1:4]...
[ "def", "DEBUG_ON_RESPONSE", "(", "self", ",", "statusCode", ",", "responseHeader", ",", "data", ")", ":", "if", "self", ".", "DEBUG_FLAG", ":", "# pragma no branch (Flag always set in tests)", "self", ".", "_frameBuffer", "[", "self", ".", "_frameCount", "]", "[",...
52.375
26.875
def process_tags(self, user, msg, reply, st=[], bst=[], depth=0, ignore_object_errors=True): """Post process tags in a message. :param str user: The user ID. :param str msg: The user's formatted message. :param str reply: The raw RiveScript reply for the message. :param []str st...
[ "def", "process_tags", "(", "self", ",", "user", ",", "msg", ",", "reply", ",", "st", "=", "[", "]", ",", "bst", "=", "[", "]", ",", "depth", "=", "0", ",", "ignore_object_errors", "=", "True", ")", ":", "stars", "=", "[", "''", "]", "stars", "...
43.4
19.225532
def includeme(config): """ Pyramid includeme file for the :class:`pyramid.config.Configurator` """ settings = config.registry.settings # config.add_renderer('json', JSONP()) # release file download config.add_renderer('repository', dl_renderer_factory) # Jinja configuration # We do...
[ "def", "includeme", "(", "config", ")", ":", "settings", "=", "config", ".", "registry", ".", "settings", "# config.add_renderer('json', JSONP())", "# release file download", "config", ".", "add_renderer", "(", "'repository'", ",", "dl_renderer_factory", ")", "# Jinja c...
38.808743
18.699454
def main(source_samplerate, target_samplerate, params, converter_type): """Setup the resampling and audio output callbacks and start playback.""" from time import sleep ratio = target_samplerate / source_samplerate with sr.CallbackResampler(get_input_callback(source_samplerate, params), ...
[ "def", "main", "(", "source_samplerate", ",", "target_samplerate", ",", "params", ",", "converter_type", ")", ":", "from", "time", "import", "sleep", "ratio", "=", "target_samplerate", "/", "source_samplerate", "with", "sr", ".", "CallbackResampler", "(", "get_inp...
43.352941
21.411765
def get_argument(self, name, default=_ARG_DEFAULT, strip=True): """Returns the value of the argument with the given name. If default is not provided, the argument is considered to be required, and we throw an HTTP 400 exception if it is missing. If the argument appears in the url more ...
[ "def", "get_argument", "(", "self", ",", "name", ",", "default", "=", "_ARG_DEFAULT", ",", "strip", "=", "True", ")", ":", "args", "=", "self", ".", "get_arguments", "(", "name", ",", "strip", "=", "strip", ")", "if", "not", "args", ":", "if", "defau...
37.882353
20.705882
def explicit_line_join(logical_line, tokens): r"""Avoid explicit line join between brackets. The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parenthe...
[ "def", "explicit_line_join", "(", "logical_line", ",", "tokens", ")", ":", "prev_start", "=", "prev_end", "=", "parens", "=", "0", "comment", "=", "False", "backslash", "=", "None", "for", "token_type", ",", "text", ",", "start", ",", "end", ",", "line", ...
37.972973
16.594595
def _get_request_body_bytes_only(param_name, param_value): '''Validates the request body passed in and converts it to bytes if our policy allows it.''' if param_value is None: return b'' if isinstance(param_value, bytes): return param_value raise TypeError(_ERROR_VALUE_SHOULD_BE_BY...
[ "def", "_get_request_body_bytes_only", "(", "param_name", ",", "param_value", ")", ":", "if", "param_value", "is", "None", ":", "return", "b''", "if", "isinstance", "(", "param_value", ",", "bytes", ")", ":", "return", "param_value", "raise", "TypeError", "(", ...
33.4
21.4
async def preprocess_websocket( self, websocket_context: Optional[WebsocketContext]=None, ) -> Optional[ResponseReturnValue]: """Preprocess the websocket i.e. call before_websocket functions. Arguments: websocket_context: The websocket context, optional as Flask ...
[ "async", "def", "preprocess_websocket", "(", "self", ",", "websocket_context", ":", "Optional", "[", "WebsocketContext", "]", "=", "None", ",", ")", "->", "Optional", "[", "ResponseReturnValue", "]", ":", "websocket_", "=", "(", "websocket_context", "or", "_webs...
43.36
17.68
def save(self, filename, show_ports=False, forcefield_name=None, forcefield_files=None, forcefield_debug=False, box=None, overwrite=False, residues=None, references_file=None, combining_rule='lorentz', foyerkwargs={}, **kwargs): """Save the Compound to a file. Par...
[ "def", "save", "(", "self", ",", "filename", ",", "show_ports", "=", "False", ",", "forcefield_name", "=", "None", ",", "forcefield_files", "=", "None", ",", "forcefield_debug", "=", "False", ",", "box", "=", "None", ",", "overwrite", "=", "False", ",", ...
48.683333
21.666667
def download(self, destination, # type: Union[str, fs.base.FS] condition=None, # type: Optional[Callable[[dict], bool]] media_count=None, # type: Optional[int] timeframe=None, # type: Optional[_Timeframe] new_only=False, ...
[ "def", "download", "(", "self", ",", "destination", ",", "# type: Union[str, fs.base.FS]", "condition", "=", "None", ",", "# type: Optional[Callable[[dict], bool]]", "media_count", "=", "None", ",", "# type: Optional[int]", "timeframe", "=", "None", ",", "# type: Optional...
37.883721
21.534884
def formatmonthname(self, theyear, themonth, withyear=True): """Return a month name translated as a table row.""" monthname = '%s %s' % (MONTHS[themonth].title(), theyear) return '<caption>%s</caption>' % monthname
[ "def", "formatmonthname", "(", "self", ",", "theyear", ",", "themonth", ",", "withyear", "=", "True", ")", ":", "monthname", "=", "'%s %s'", "%", "(", "MONTHS", "[", "themonth", "]", ".", "title", "(", ")", ",", "theyear", ")", "return", "'<caption>%s</c...
58.75
13.75
def refresh(self)->None: "Apply any logit, flow, or affine transfers that have been sent to the `Image`." if self._logit_px is not None: self._px = self._logit_px.sigmoid_() self._logit_px = None if self._affine_mat is not None or self._flow is not None: self....
[ "def", "refresh", "(", "self", ")", "->", "None", ":", "if", "self", ".", "_logit_px", "is", "not", "None", ":", "self", ".", "_px", "=", "self", ".", "_logit_px", ".", "sigmoid_", "(", ")", "self", ".", "_logit_px", "=", "None", "if", "self", ".",...
45.8
18.2
def laser_hook(self, hook_type: str) -> Callable: """Registers the annotated function with register_laser_hooks :param hook_type: :return: hook decorator """ def hook_decorator(func: Callable): """ Hook decorator generated by laser_hook :param func: Dec...
[ "def", "laser_hook", "(", "self", ",", "hook_type", ":", "str", ")", "->", "Callable", ":", "def", "hook_decorator", "(", "func", ":", "Callable", ")", ":", "\"\"\" Hook decorator generated by laser_hook\n\n :param func: Decorated function\n \"\"\"", "...
27.875
15.0625
def start(self, job): """ Start spark and hdfs worker containers :param job: The underlying job. """ # start spark and our datanode self.sparkContainerID = dockerCheckOutput(job=job, defer=STOP, ...
[ "def", "start", "(", "self", ",", "job", ")", ":", "# start spark and our datanode", "self", ".", "sparkContainerID", "=", "dockerCheckOutput", "(", "job", "=", "job", ",", "defer", "=", "STOP", ",", "workDir", "=", "os", ".", "getcwd", "(", ")", ",", "t...
47.232877
26.493151
def feature_path(self, gff_path): """Load a GFF file with information on a single sequence and store features in the ``features`` attribute Args: gff_path: Path to GFF file. """ if not gff_path: self.feature_dir = None self.feature_file = None ...
[ "def", "feature_path", "(", "self", ",", "gff_path", ")", ":", "if", "not", "gff_path", ":", "self", ".", "feature_dir", "=", "None", "self", ".", "feature_file", "=", "None", "else", ":", "if", "not", "op", ".", "exists", "(", "gff_path", ")", ":", ...
31.65
16.75
def insertUserStore(siteStore, userStorePath): """ Move the SubStore at the indicated location into the given site store's directory and then hook it up to the site store's authentication database. @type siteStore: C{Store} @type userStorePath: C{FilePath} """ # The following may, but does ...
[ "def", "insertUserStore", "(", "siteStore", ",", "userStorePath", ")", ":", "# The following may, but does not need to be in a transaction, because it", "# is merely an attempt to guess a reasonable filesystem name to use for", "# this avatar. The user store being operated on is expected to be ...
43.756757
19.594595
def deps_status(self): """Returns a list with the status of the dependencies.""" if not self.deps: return [self.S_OK] return [d.status for d in self.deps]
[ "def", "deps_status", "(", "self", ")", ":", "if", "not", "self", ".", "deps", ":", "return", "[", "self", ".", "S_OK", "]", "return", "[", "d", ".", "status", "for", "d", "in", "self", ".", "deps", "]" ]
31
14.5
def set(self, data=None): """ Sets the event """ self.__data = data self.__exception = None self.__event.set()
[ "def", "set", "(", "self", ",", "data", "=", "None", ")", ":", "self", ".", "__data", "=", "data", "self", ".", "__exception", "=", "None", "self", ".", "__event", ".", "set", "(", ")" ]
21.714286
10
def create_endpoints_csv_file(self, timeout=-1): """ Creates an endpoints CSV file for a SAN. Args: timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its compl...
[ "def", "create_endpoints_csv_file", "(", "self", ",", "timeout", "=", "-", "1", ")", ":", "uri", "=", "\"{}/endpoints/\"", ".", "format", "(", "self", ".", "data", "[", "\"uri\"", "]", ")", "return", "self", ".", "_helper", ".", "do_post", "(", "uri", ...
36
21.714286
def _make_allowed_states(self) -> Iterator[Text]: """ Sometimes we load states from the database. In order to avoid loading an arbitrary class, we list here the state classes that are allowed. """ for trans in self.transitions: yield trans.dest.name() if...
[ "def", "_make_allowed_states", "(", "self", ")", "->", "Iterator", "[", "Text", "]", ":", "for", "trans", "in", "self", ".", "transitions", ":", "yield", "trans", ".", "dest", ".", "name", "(", ")", "if", "trans", ".", "origin", ":", "yield", "trans", ...
33.272727
16.545455
def get_anon_name(rec): # type: (MutableMapping[Text, Any]) -> Text """Calculate a reproducible name for anonymous types.""" if "name" in rec: return rec["name"] anon_name = "" if rec['type'] in ('enum', 'https://w3id.org/cwl/salad#enum'): for sym in rec["symbols"]: anon_...
[ "def", "get_anon_name", "(", "rec", ")", ":", "# type: (MutableMapping[Text, Any]) -> Text", "if", "\"name\"", "in", "rec", ":", "return", "rec", "[", "\"name\"", "]", "anon_name", "=", "\"\"", "if", "rec", "[", "'type'", "]", "in", "(", "'enum'", ",", "'htt...
46.352941
19.294118
def can_edit(self, user=None, request=None): """ Define if a user can edit or not the instance, according to his account or the request. """ can = False if request and not self.owner: if (getattr(settings, "LEAFLET_STORAGE_ALLOW_ANONYMOUS", False) ...
[ "def", "can_edit", "(", "self", ",", "user", "=", "None", ",", "request", "=", "None", ")", ":", "can", "=", "False", "if", "request", "and", "not", "self", ".", "owner", ":", "if", "(", "getattr", "(", "settings", ",", "\"LEAFLET_STORAGE_ALLOW_ANONYMOUS...
40.12
16.36
async def get_misc_settings(self) -> List[Setting]: """Return miscellaneous settings such as name and timezone.""" misc = await self.services["system"]["getDeviceMiscSettings"](target="") return [Setting.make(**x) for x in misc]
[ "async", "def", "get_misc_settings", "(", "self", ")", "->", "List", "[", "Setting", "]", ":", "misc", "=", "await", "self", ".", "services", "[", "\"system\"", "]", "[", "\"getDeviceMiscSettings\"", "]", "(", "target", "=", "\"\"", ")", "return", "[", "...
62.25
14.75
def write_data_to_file(self, file_path='', date=str(datetime.date.today()), organization='llnl',dict_to_write={}, name='', row_count=0): """ Writes given dict to file. """ exists = os.path.isfile(file_path) with open(file_path, 'a') as out: if not exists: ...
[ "def", "write_data_to_file", "(", "self", ",", "file_path", "=", "''", ",", "date", "=", "str", "(", "datetime", ".", "date", ".", "today", "(", ")", ")", ",", "organization", "=", "'llnl'", ",", "dict_to_write", "=", "{", "}", ",", "name", "=", "''"...
46.166667
14.833333
def find_duplicates(l: list) -> set: """ Return the duplicates in a list. The function relies on https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list . Parameters ---------- l : list Name Returns ------- set Duplicated values >>> f...
[ "def", "find_duplicates", "(", "l", ":", "list", ")", "->", "set", ":", "return", "set", "(", "[", "x", "for", "x", "in", "l", "if", "l", ".", "count", "(", "x", ")", ">", "1", "]", ")" ]
19.545455
22.181818
def interp_qa_v1(self): """Calculate the lake outflow based on linear interpolation. Required control parameters: |N| |llake_control.Q| Required derived parameters: |llake_derived.TOY| |llake_derived.VQ| Required aide sequence: |llake_aides.VQ| Calculated aide seque...
[ "def", "interp_qa_v1", "(", "self", ")", ":", "con", "=", "self", ".", "parameters", ".", "control", ".", "fastaccess", "der", "=", "self", ".", "parameters", ".", "derived", ".", "fastaccess", "aid", "=", "self", ".", "sequences", ".", "aides", ".", "...
33.046296
19.981481
def get_parent_label(self, treepos): """Given the treeposition of a node, return the label of its parent. Returns None, if the tree has no parent. """ parent_pos = self.get_parent_treepos(treepos) if parent_pos is not None: parent = self.dgtree[parent_pos] ...
[ "def", "get_parent_label", "(", "self", ",", "treepos", ")", ":", "parent_pos", "=", "self", ".", "get_parent_treepos", "(", "treepos", ")", "if", "parent_pos", "is", "not", "None", ":", "parent", "=", "self", ".", "dgtree", "[", "parent_pos", "]", "return...
37.1
8.6
def transaction(self, session=None): """Start a new transaction based on the passed session object. If session is not passed, then create one and make sure of closing it finally. """ local_session = None if session is None: local_session = session = self.create_scoped...
[ "def", "transaction", "(", "self", ",", "session", "=", "None", ")", ":", "local_session", "=", "None", "if", "session", "is", "None", ":", "local_session", "=", "session", "=", "self", ".", "create_scoped_session", "(", ")", "try", ":", "yield", "session"...
48.857143
22.761905
def fill(self, field, value): """ Fill a specified form field in the current document. :param field: an instance of :class:`zombie.dom.DOMNode` :param value: any string value :return: self to allow function chaining. """ self.client.nowait('browser.fill', (field,...
[ "def", "fill", "(", "self", ",", "field", ",", "value", ")", ":", "self", ".", "client", ".", "nowait", "(", "'browser.fill'", ",", "(", "field", ",", "value", ")", ")", "return", "self" ]
33.9
14.5
def start(self, value: typing.Union[float, typing.Tuple[float, float]]) -> None: """Set the end property in relative coordinates. End may be a float when graphic is an Interval or a tuple (y, x) when graphic is a Line.""" ...
[ "def", "start", "(", "self", ",", "value", ":", "typing", ".", "Union", "[", "float", ",", "typing", ".", "Tuple", "[", "float", ",", "float", "]", "]", ")", "->", "None", ":", "..." ]
49.2
21.8
def p_function_statement(self, p): 'function_statement : funcvardecls function_calc' p[0] = p[1] + (p[2],) p.set_lineno(0, p.lineno(1))
[ "def", "p_function_statement", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "(", "p", "[", "2", "]", ",", ")", "p", ".", "set_lineno", "(", "0", ",", "p", ".", "lineno", "(", "1", ")", ")" ]
39
9.5
def _CheckWindowsPath(self, filename, artifact_definition, source, path): """Checks if a path is a valid Windows path. Args: filename (str): name of the artifacts definition file. artifact_definition (ArtifactDefinition): artifact definition. source (SourceType): source definition. path...
[ "def", "_CheckWindowsPath", "(", "self", ",", "filename", ",", "artifact_definition", ",", "source", ",", "path", ")", ":", "result", "=", "True", "number_of_forward_slashes", "=", "path", ".", "count", "(", "'/'", ")", "number_of_backslashes", "=", "path", "....
41.801887
23.264151
def all_departed_units(self): """ Collection of all units that were previously part of any relation on this endpoint but which have since departed. This collection is persistent and mutable. The departed units will be kept until they are explicitly removed, to allow for reasona...
[ "def", "all_departed_units", "(", "self", ")", ":", "if", "self", ".", "_all_departed_units", "is", "None", ":", "self", ".", "_all_departed_units", "=", "CachedKeyList", ".", "load", "(", "'reactive.endpoints.departed.{}'", ".", "format", "(", "self", ".", "end...
45.5
23.166667
def retrieve_paths(self, products, report_path, suffix=None): """Helper method to retrieve path from particular report metadata. :param products: Report products. :type products: list :param report_path: Path of the IF output. :type report_path: str :param suffix: Expe...
[ "def", "retrieve_paths", "(", "self", ",", "products", ",", "report_path", ",", "suffix", "=", "None", ")", ":", "paths", "=", "[", "]", "for", "product", "in", "products", ":", "path", "=", "ImpactReport", ".", "absolute_output_path", "(", "join", "(", ...
32.029412
15.823529
def parse_dtype(features, check=True): """Return the features scalar type, raise if error Raise IOError if all features have not the same data type. Return dtype, the features scalar type. """ dtype = features[0].dtype if check: types = [x.dtype for x in features] if not all([t...
[ "def", "parse_dtype", "(", "features", ",", "check", "=", "True", ")", ":", "dtype", "=", "features", "[", "0", "]", ".", "dtype", "if", "check", ":", "types", "=", "[", "x", ".", "dtype", "for", "x", "in", "features", "]", "if", "not", "all", "(...
31.538462
15.153846
def export(id, local=False, scrub_pii=False): """Export data from an experiment.""" print("Preparing to export the data...") if local: db_uri = db.db_url else: db_uri = HerokuApp(id).db_uri # Create the data package if it doesn't already exist. subdata_path = os.path.join("dat...
[ "def", "export", "(", "id", ",", "local", "=", "False", ",", "scrub_pii", "=", "False", ")", ":", "print", "(", "\"Preparing to export the data...\"", ")", "if", "local", ":", "db_uri", "=", "db", ".", "db_url", "else", ":", "db_uri", "=", "HerokuApp", "...
26.87931
21.965517
def init(name, description, bucket, timeout, memory, stages, requirements, function, runtime, config_file, **kwargs): """Generate a configuration file.""" if os.path.exists(config_file): raise RuntimeError('Please delete the old version {} if you want to ' 'reconfigur...
[ "def", "init", "(", "name", ",", "description", ",", "bucket", ",", "timeout", ",", "memory", ",", "stages", ",", "requirements", ",", "function", ",", "runtime", ",", "config_file", ",", "*", "*", "kwargs", ")", ":", "if", "os", ".", "path", ".", "e...
43.293103
19.534483
def newton_call(self): """ Function calls for Newton power flow Returns ------- None """ # system = self.system # exec(system.call.newton) system = self.system dae = self.system.dae system.dae.init_fg() system.dae.reset_...
[ "def", "newton_call", "(", "self", ")", ":", "# system = self.system", "# exec(system.call.newton)", "system", "=", "self", ".", "system", "dae", "=", "self", ".", "system", ".", "dae", "system", ".", "dae", ".", "init_fg", "(", ")", "system", ".", "dae", ...
32.355932
19.305085
def poke(self, context): """ Execute the bash command in a temporary directory which will be cleaned afterwards """ bash_command = self.bash_command self.log.info("Tmp dir root location: \n %s", gettempdir()) with TemporaryDirectory(prefix='airflowtmp') as tmp_dir...
[ "def", "poke", "(", "self", ",", "context", ")", ":", "bash_command", "=", "self", ".", "bash_command", "self", ".", "log", ".", "info", "(", "\"Tmp dir root location: \\n %s\"", ",", "gettempdir", "(", ")", ")", "with", "TemporaryDirectory", "(", "prefix", ...
41.09375
16.71875
def make_statement(self, action, mention): """Makes an INDRA statement from a Geneways action and action mention. Parameters ---------- action : GenewaysAction The mechanism that the Geneways mention maps to. Note that several text mentions can correspond to the ...
[ "def", "make_statement", "(", "self", ",", "action", ",", "mention", ")", ":", "(", "statement_generator", ",", "is_direct", ")", "=", "geneways_action_to_indra_statement_type", "(", "mention", ".", "actiontype", ",", "action", ".", "plo", ")", "if", "statement_...
46.057971
20.826087
def wait_lock(path, lock_fn=None, timeout=5, sleep=0.1, time_start=None): ''' Obtain a write lock. If one exists, wait for it to release first ''' if not isinstance(path, six.string_types): raise FileLockError('path must be a string') if lock_fn is None: lock_fn = path + '.w' if ...
[ "def", "wait_lock", "(", "path", ",", "lock_fn", "=", "None", ",", "timeout", "=", "5", ",", "sleep", "=", "0.1", ",", "time_start", "=", "None", ")", ":", "if", "not", "isinstance", "(", "path", ",", "six", ".", "string_types", ")", ":", "raise", ...
33.445946
21.364865
def _encode(data, convert_to_float): """Convert the Python values to values suitable to send to Octave. """ ctf = convert_to_float # Handle variable pointer. if isinstance(data, (OctaveVariablePtr)): return _encode(data.value, ctf) # Handle a user defined object. if isins...
[ "def", "_encode", "(", "data", ",", "convert_to_float", ")", ":", "ctf", "=", "convert_to_float", "# Handle variable pointer.\r", "if", "isinstance", "(", "data", ",", "(", "OctaveVariablePtr", ")", ")", ":", "return", "_encode", "(", "data", ".", "value", ","...
31.651163
14.104651
def resource_url(self): """str: Root URL for IBM Streams REST API""" if self._iam: self._resource_url = self._resource_url or _get_iam_rest_api_url_from_creds(self.rest_client, self.credentials) else: self._resource_url = self._resource_url or _get_rest_api_url_from_creds...
[ "def", "resource_url", "(", "self", ")", ":", "if", "self", ".", "_iam", ":", "self", ".", "_resource_url", "=", "self", ".", "_resource_url", "or", "_get_iam_rest_api_url_from_creds", "(", "self", ".", "rest_client", ",", "self", ".", "credentials", ")", "e...
54.285714
32.571429
def modis1kmto500m(lons1km, lats1km, cores=1): """Getting 500m geolocation for modis from 1km tiepoints. http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation """ if cores > 1: return _multi(modis1kmto500m, lons1km, lats1km, 10, cores) cols1km = np.arange(1354) cols500m = np.aran...
[ "def", "modis1kmto500m", "(", "lons1km", ",", "lats1km", ",", "cores", "=", "1", ")", ":", "if", "cores", ">", "1", ":", "return", "_multi", "(", "modis1kmto500m", ",", "lons1km", ",", "lats1km", ",", "10", ",", "cores", ")", "cols1km", "=", "np", "....
35.038462
15.807692
def process_request(self, req): """ Process the given request `req`, implements an `IRequestHandler` API. Normally, `process_request` would return a tuple, but since none of these requests will return an HTML page, they will all terminate without a return value and directly send...
[ "def", "process_request", "(", "self", ",", "req", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "'TRAC_GITHUB_ENABLE_DEBUGGING'", ",", "None", ")", "is", "not", "None", ":", "debug_match", "=", "self", ".", "_debug_request_re", ".", "match", "(",...
43.614035
21.403509