text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def get_default_config(self): """ Returns the default collector settings """ config = super(TokuMXCollector, self).get_default_config() config.update({ 'path': 'mongo', 'hosts': ['localhost'], 'user': None, 'passwd': ...
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "TokuMXCollector", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "'path'", ":", "'mongo'", ",", "'hosts'", ":", "[", "'localhost'",...
31.647059
10
def Runtime_releaseObjectGroup(self, objectGroup): """ Function path: Runtime.releaseObjectGroup Domain: Runtime Method name: releaseObjectGroup Parameters: Required arguments: 'objectGroup' (type: string) -> Symbolic object group name. No return value. Description: Releases all remote...
[ "def", "Runtime_releaseObjectGroup", "(", "self", ",", "objectGroup", ")", ":", "assert", "isinstance", "(", "objectGroup", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'objectGroup' must be of type '['str']'. Received type: '%s'\"", "%", "type", "(", "objectGroup",...
32.578947
19.421053
def indicator_summary_table(): """Export a table listing all NUTS2 regions with their (most current) data. Output is a CSV file and an Excel file, saved as 'characters.csv/.xlsx' in the output directory. """ # a database client/session to run queries in cl = client.get_client() session = cl.cre...
[ "def", "indicator_summary_table", "(", ")", ":", "# a database client/session to run queries in", "cl", "=", "client", ".", "get_client", "(", ")", "session", "=", "cl", ".", "create_session", "(", ")", "# Query regions and indicators separately, join them in pandas", "quer...
45.04
23.88
def create_parameter_group(name, db_parameter_group_family, description, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an RDS parameter group CLI example to create an RDS parameter group:: salt myminion boto_rds.create...
[ "def", "create_parameter_group", "(", "name", ",", "db_parameter_group_family", ",", "description", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "res", "=...
41.588235
24.529412
def _xdr_read_address(unpacker): """Reads a stellar address and returns the string representing the address This method assumes the encoded address is a public address (starting with G) """ # First 4 bytes are the address type address_type = unpacker.unpack_uint() if address_type != 0: r...
[ "def", "_xdr_read_address", "(", "unpacker", ")", ":", "# First 4 bytes are the address type", "address_type", "=", "unpacker", ".", "unpack_uint", "(", ")", "if", "address_type", "!=", "0", ":", "raise", "ValueError", "(", "\"Unsupported address type\"", ")", "return...
41.9
14
def update_iteration_num_suggestions(self, num_suggestions): """Update iteration's num_suggestions.""" iteration_config = self.experiment_group.iteration_config iteration_config.num_suggestions = num_suggestions self._update_config(iteration_config)
[ "def", "update_iteration_num_suggestions", "(", "self", ",", "num_suggestions", ")", ":", "iteration_config", "=", "self", ".", "experiment_group", ".", "iteration_config", "iteration_config", ".", "num_suggestions", "=", "num_suggestions", "self", ".", "_update_config", ...
46.166667
18
def info(self): """ Return information of chord to display """ return """{} root={} quality={} appended={} on={}""".format(self._chord, self._root, self._quality, self._appended, self._on)
[ "def", "info", "(", "self", ")", ":", "return", "\"\"\"{}\nroot={}\nquality={}\nappended={}\non={}\"\"\"", ".", "format", "(", "self", ".", "_chord", ",", "self", ".", "_root", ",", "self", ".", "_quality", ",", "self", ".", "_appended", ",", "self", ".", "_...
28.285714
16.714286
def add_script_sequence(self): """ creates a script sequence based on the script iterator type selected and the selected scripts and sends it to the tree self.tree_loaded """ def empty_tree(tree_model): # COMMENT_ME def add_children_to_list(item, somelis...
[ "def", "add_script_sequence", "(", "self", ")", ":", "def", "empty_tree", "(", "tree_model", ")", ":", "# COMMENT_ME", "def", "add_children_to_list", "(", "item", ",", "somelist", ")", ":", "if", "item", ".", "hasChildren", "(", ")", ":", "for", "rownum", ...
44.755102
26.265306
def ast_scan_file(filename, re_fallback=True): '''Scans a file for imports using AST. In addition to normal imports, try to get imports via `__import__` or `import_module` calls. The AST parser should be able to resolve simple variable assignments in cases where these functions are called with vari...
[ "def", "ast_scan_file", "(", "filename", ",", "re_fallback", "=", "True", ")", ":", "try", ":", "with", "io", ".", "open", "(", "filename", ",", "'rb'", ")", "as", "fp", ":", "try", ":", "root", "=", "ast", ".", "parse", "(", "fp", ".", "read", "...
41.275862
18.655172
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken, knowledge_base): """Parse the yum output.""" _ = stderr, time_taken, args, knowledge_base # Unused. self.CheckReturn(cmd, return_val) packages = [] for line in stdout.decode("utf-8").splitlines()[1:]: # Ignore first lin...
[ "def", "Parse", "(", "self", ",", "cmd", ",", "args", ",", "stdout", ",", "stderr", ",", "return_val", ",", "time_taken", ",", "knowledge_base", ")", ":", "_", "=", "stderr", ",", "time_taken", ",", "args", ",", "knowledge_base", "# Unused.", "self", "."...
34.909091
15.954545
def export(self, file_path=None, export_format=None): """ Write the users to a file. """ with io.open(file_path, mode='w', encoding="utf-8") as export_file: if export_format == 'yaml': import yaml yaml.safe_dump(self.to_dict(), export_file, default_flow_style=...
[ "def", "export", "(", "self", ",", "file_path", "=", "None", ",", "export_format", "=", "None", ")", ":", "with", "io", ".", "open", "(", "file_path", ",", "mode", "=", "'w'", ",", "encoding", "=", "\"utf-8\"", ")", "as", "export_file", ":", "if", "e...
53
19.666667
def coherence_spectrogram(self, other, stride, fftlength=None, overlap=None, window='hann', nproc=1): """Calculate the coherence spectrogram between this `TimeSeries` and other. Parameters ---------- other : `TimeSeries` the second `Time...
[ "def", "coherence_spectrogram", "(", "self", ",", "other", ",", "stride", ",", "fftlength", "=", "None", ",", "overlap", "=", "None", ",", "window", "=", "'hann'", ",", "nproc", "=", "1", ")", ":", "from", ".", ".", "spectrogram", ".", "coherence", "im...
36.897436
22.051282
def transform(self, X, y=None, sample_weight=None): ''' Transforms the time series data with linear direct value interpolation If y is a time series and passed, it will be transformed as well The time dimension is removed from the data Parameters ---------- X : a...
[ "def", "transform", "(", "self", ",", "X", ",", "y", "=", "None", ",", "sample_weight", "=", "None", ")", ":", "check_ts_data", "(", "X", ",", "y", ")", "xt", ",", "xc", "=", "get_ts_data_parts", "(", "X", ")", "yt", "=", "y", "swt", "=", "sample...
37.454545
22.863636
def load(): """ Loads the built-in operators into the global test engine. """ for operator in operators: module, symbols = operator[0], operator[1:] path = 'grappa.operators.{}'.format(module) # Dynamically import modules operator = __import__(path, None, None, symbols) ...
[ "def", "load", "(", ")", ":", "for", "operator", "in", "operators", ":", "module", ",", "symbols", "=", "operator", "[", "0", "]", ",", "operator", "[", "1", ":", "]", "path", "=", "'grappa.operators.{}'", ".", "format", "(", "module", ")", "# Dynamica...
31.5
15.214286
def check_constraint(column, lenum, **kwargs): """ Returns a SQL CHECK constraint string given a column name and a :class:`~coaster.utils.classes.LabeledEnum`. Alembic may not detect the CHECK constraint when autogenerating migrations, so you may need to do this manually using t...
[ "def", "check_constraint", "(", "column", ",", "lenum", ",", "*", "*", "kwargs", ")", ":", "return", "CheckConstraint", "(", "str", "(", "column_constructor", "(", "column", ")", ".", "in_", "(", "lenum", ".", "keys", "(", ")", ")", ".", "compile", "("...
44.809524
25.666667
def get_result(self): """Perform the call and return a string with the time in hh:mm:ss""" result = get_json_from_remote_server(self.call) seconds = self._get_average_duration(result) if result else 0 return stringify_seconds(seconds)
[ "def", "get_result", "(", "self", ")", ":", "result", "=", "get_json_from_remote_server", "(", "self", ".", "call", ")", "seconds", "=", "self", ".", "_get_average_duration", "(", "result", ")", "if", "result", "else", "0", "return", "stringify_seconds", "(", ...
52.4
12.8
def get_from_archive(self, feed_id): """ Retrieves feed that was persisted as .xml file by its id (= filename) Note: No check on feed validity. file content is assumed correct :param feed_id: :return: the atom feed as string """ file_path = self.feed_repository + ...
[ "def", "get_from_archive", "(", "self", ",", "feed_id", ")", ":", "file_path", "=", "self", ".", "feed_repository", "+", "'/'", "+", "str", "(", "feed_id", ")", "+", "'.xml'", "if", "not", "os", ".", "path", ".", "isfile", "(", "file_path", ")", ":", ...
41.666667
11.166667
def _construct_state_machines(self): """ :return: dict in format <state_machine_common_name: instance_of_the_state_machine> """ state_machines = dict() for state_machine in [StateMachineRecomputing(self.logger, self), StateMachineContinuous(self.logger, self), ...
[ "def", "_construct_state_machines", "(", "self", ")", ":", "state_machines", "=", "dict", "(", ")", "for", "state_machine", "in", "[", "StateMachineRecomputing", "(", "self", ".", "logger", ",", "self", ")", ",", "StateMachineContinuous", "(", "self", ".", "lo...
59.444444
18.333333
async def create_collection(db, model_class: MongoCollectionMixin): ''' Creates a MongoDB collection and all the declared indices in the model's ``Meta`` class :param db: A database handle :type db: motor.motor_asyncio.AsyncIOMotorClient :param model_class: The model to cre...
[ "async", "def", "create_collection", "(", "db", ",", "model_class", ":", "MongoCollectionMixin", ")", ":", "name", "=", "model_class", ".", "get_collection_name", "(", ")", "if", "name", ":", "try", ":", "# create collection", "coll", "=", "await", "db", ".", ...
40.511628
24
def predict(self, df_data, graph=None, **kwargs): """Orient a graph using the method defined by the arguments. Depending on the type of `graph`, this function process to execute different functions: 1. If ``graph`` is a ``networkx.DiGraph``, then ``self.orient_directed_graph`` is execu...
[ "def", "predict", "(", "self", ",", "df_data", ",", "graph", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "graph", "is", "None", ":", "return", "self", ".", "create_graph_from_data", "(", "df_data", ",", "*", "*", "kwargs", ")", "elif", "isi...
46.37037
26.703704
def _rest_post(self, suburi, request_headers, request_body): """REST POST operation. The response body after the operation could be the new resource, or ExtendedError, or it could be empty. """ return self._rest_op('POST', suburi, request_headers, request_body)
[ "def", "_rest_post", "(", "self", ",", "suburi", ",", "request_headers", ",", "request_body", ")", ":", "return", "self", ".", "_rest_op", "(", "'POST'", ",", "suburi", ",", "request_headers", ",", "request_body", ")" ]
42.285714
19.142857
def preview(): # pragma: no coverage """launch an HTTP to preview the website""" Handler = http.server.SimpleHTTPRequestHandler socketserver.TCPServer.allow_reuse_address = True port = CONFIG['http_port'] httpd = socketserver.TCPServer(("", port), Handler) os.chdir(CONFIG['output_to']) try:...
[ "def", "preview", "(", ")", ":", "# pragma: no coverage", "Handler", "=", "http", ".", "server", ".", "SimpleHTTPRequestHandler", "socketserver", ".", "TCPServer", ".", "allow_reuse_address", "=", "True", "port", "=", "CONFIG", "[", "'http_port'", "]", "httpd", ...
38.785714
11.142857
def _querystring(self): """Additional keyword arguments""" kw = {} if self.status: kw["status"] = "all" if self.links: kw["links"] = "all" if self.include is not None: kw["include"] = self.include if self.subject_key_type != "SubjectN...
[ "def", "_querystring", "(", "self", ")", ":", "kw", "=", "{", "}", "if", "self", ".", "status", ":", "kw", "[", "\"status\"", "]", "=", "\"all\"", "if", "self", ".", "links", ":", "kw", "[", "\"links\"", "]", "=", "\"all\"", "if", "self", ".", "i...
27.642857
16.214286
def transitive_reduction(G): """ Returns a transitive reduction of a graph. The original graph is not modified. A transitive reduction H of G has a path from x to y if and only if there was a path from x to y in G. Deleting any edge of H destroys this property. A transitive reduction is not ...
[ "def", "transitive_reduction", "(", "G", ")", ":", "H", "=", "G", ".", "copy", "(", ")", "for", "a", ",", "b", ",", "w", "in", "G", ".", "edges_iter", "(", "data", "=", "True", ")", ":", "# Try deleting the edge, see if we still have a path", "# between th...
35.518519
18.407407
def call_hook(self, hook, *args, **kwargs): """ Calls each registered hook """ for function in self.hooks[hook]: function.__call__(*args, **kwargs)
[ "def", "call_hook", "(", "self", ",", "hook", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "function", "in", "self", ".", "hooks", "[", "hook", "]", ":", "function", ".", "__call__", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
31
2.666667
def validate_url(self, original_string): """Returns the original string if it was valid, raises an argument error if it's not. """ # nipped from stack overflow: http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python # I preferred ...
[ "def", "validate_url", "(", "self", ",", "original_string", ")", ":", "# nipped from stack overflow: http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python", "# I preferred this to the thorough regex approach for simplicity and", "# readability", ...
43.956522
21.478261
def makePics(self): """convert every .image we find to a ./swhlab/ image""" rescanNeeded=False for fname in smartSort(self.fnames): if fname in self.fnames2: continue ext=os.path.splitext(fname)[1].lower() if ext in [".jpg",".png"]: ...
[ "def", "makePics", "(", "self", ")", ":", "rescanNeeded", "=", "False", "for", "fname", "in", "smartSort", "(", "self", ".", "fnames", ")", ":", "if", "fname", "in", "self", ".", "fnames2", ":", "continue", "ext", "=", "os", ".", "path", ".", "splite...
49.761905
17.238095
def cloneInto(self, newStore, avatars): """ Create a copy of this LoginAccount and all associated LoginMethods in a different Store. Return the copied LoginAccount. """ la = LoginAccount(store=newStore, password=self.password, ...
[ "def", "cloneInto", "(", "self", ",", "newStore", ",", "avatars", ")", ":", "la", "=", "LoginAccount", "(", "store", "=", "newStore", ",", "password", "=", "self", ".", "password", ",", "avatars", "=", "avatars", ",", "disabled", "=", "self", ".", "dis...
42.9
12.9
def cudnnSetFilter4dDescriptor(wDesc, dataType, format, k, c, h, w): """" Initialize a filter descriptor. This function initializes a previously created filter descriptor object into a 4D filter. Filters layout must be contiguous in memory. Parameters ---------- wDesc : cudnnFilterDescript...
[ "def", "cudnnSetFilter4dDescriptor", "(", "wDesc", ",", "dataType", ",", "format", ",", "k", ",", "c", ",", "h", ",", "w", ")", ":", "status", "=", "_libcudnn", ".", "cudnnSetFilter4dDescriptor", "(", "wDesc", ",", "dataType", ",", "format", ",", "k", ",...
28.333333
20.518519
def get_component(id): """ Gets a Cachet component by id """ components = cachet.Components(endpoint=ENDPOINT) component = json.loads(components.get(id=id)) return component['data']
[ "def", "get_component", "(", "id", ")", ":", "components", "=", "cachet", ".", "Components", "(", "endpoint", "=", "ENDPOINT", ")", "component", "=", "json", ".", "loads", "(", "components", ".", "get", "(", "id", "=", "id", ")", ")", "return", "compon...
28.428571
8.428571
def interactive_console(self): """ Opens an interactive console Returns: lago.utils.CommandStatus: result of the virsh command execution """ if not self.running(): raise RuntimeError('VM %s is not running' % self._libvirt_.name) virsh_command = [ ...
[ "def", "interactive_console", "(", "self", ")", ":", "if", "not", "self", ".", "running", "(", ")", ":", "raise", "RuntimeError", "(", "'VM %s is not running'", "%", "self", ".", "_libvirt_", ".", "name", ")", "virsh_command", "=", "[", "\"virsh\"", ",", "...
30.470588
17.882353
def get_record(self, dns_type, name): """ Get a dns record :param dns_type: :param name: :return: """ try: record = [record for record in self.dns_records if record['type'] == dns_type and record['name'] == name][0] except...
[ "def", "get_record", "(", "self", ",", "dns_type", ",", "name", ")", ":", "try", ":", "record", "=", "[", "record", "for", "record", "in", "self", ".", "dns_records", "if", "record", "[", "'type'", "]", "==", "dns_type", "and", "record", "[", "'name'",...
32.4
16.266667
def parse_skypos(ra, dec): """ Function to parse RA and Dec input values and turn them into decimal degrees Input formats could be: ["nn","nn","nn.nn"] "nn nn nn.nnn" "nn:nn:nn.nn" "nnH nnM nn.nnS" or "nnD nnM nn.nnS" nn.nnnnnnnn "nn.nnnnnnn" """ ...
[ "def", "parse_skypos", "(", "ra", ",", "dec", ")", ":", "rval", "=", "make_val_float", "(", "ra", ")", "dval", "=", "make_val_float", "(", "dec", ")", "if", "rval", "is", "None", ":", "rval", ",", "dval", "=", "radec_hmstodd", "(", "ra", ",", "dec", ...
23.473684
17.157895
def get_rule_by_pk(self, id_rule): """ Get a rule by its identifier :param id_rule: Rule identifier. :return: Seguinte estrutura :: { 'rule': {'id': < id >, 'environment': < Environment Object >, 'content': < content >, 'n...
[ "def", "get_rule_by_pk", "(", "self", ",", "id_rule", ")", ":", "url", "=", "'rule/get_by_id/'", "+", "str", "(", "id_rule", ")", "code", ",", "xml", "=", "self", ".", "submit", "(", "None", ",", "'GET'", ",", "url", ")", "return", "self", ".", "resp...
34.08
17.6
def algorithm(G, method_name, **kwargs): """ Apply a ``method`` from NetworkX to all :ref:`networkx.Graph <networkx:graph>` objects in the :class:`.GraphCollection` ``G``. For options, see the `list of algorithms <http://networkx.github.io/documentation/networkx-1.9/reference/algorithms.html>`_...
[ "def", "algorithm", "(", "G", ",", "method_name", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "\"To be removed in 0.8. Use GraphCollection.analyze instead.\"", ",", "DeprecationWarning", ")", "return", "G", ".", "analyze", "(", "method_name", ...
30.313725
23.137255
def add_directory(self, path, ignore=None): """Add ``*.py`` files under the directory ``path`` to the archive. """ for root, dirs, files in os.walk(path): arc_prefix = os.path.relpath(root, os.path.dirname(path)) # py3 remove pyc cache dirs. if '__pycache__' i...
[ "def", "add_directory", "(", "self", ",", "path", ",", "ignore", "=", "None", ")", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "path", ")", ":", "arc_prefix", "=", "os", ".", "path", ".", "relpath", "(", "root", "...
37
12.85
def load(self, name): """Construct an object from a registered factory. Parameters ---------- name : str Name with which the factory was registered. """ try: return self._factories[name]() except KeyError: raise ValueError( ...
[ "def", "load", "(", "self", ",", "name", ")", ":", "try", ":", "return", "self", ".", "_factories", "[", "name", "]", "(", ")", "except", "KeyError", ":", "raise", "ValueError", "(", "\"no %s factory registered under name %r, options are: %r\"", "%", "(", "sel...
31.066667
19.466667
def _get_pretty_body(headers, body): """ Return a pretty printed body using the Content-Type header information :param headers: Headers for the request/response (dict) :param body: Body to pretty print (string) :return: Body pretty printed (string) """ if HEADER_CONTENT_TYPE in headers: ...
[ "def", "_get_pretty_body", "(", "headers", ",", "body", ")", ":", "if", "HEADER_CONTENT_TYPE", "in", "headers", ":", "if", "HEADER_REPRESENTATION_XML", "==", "headers", "[", "HEADER_CONTENT_TYPE", "]", ":", "xml_parsed", "=", "parseString", "(", "body", ")", "pr...
37.333333
15.904762
def generate_signature(secret, verb, url, nonce, data): """Generate a request signature compatible with BitMEX.""" # Parse the url so we can remove the base and extract just the path. parsedURL = urllib.parse.urlparse(url) path = parsedURL.path if parsedURL.query: path = path + '?' + parsedU...
[ "def", "generate_signature", "(", "secret", ",", "verb", ",", "url", ",", "nonce", ",", "data", ")", ":", "# Parse the url so we can remove the base and extract just the path.", "parsedURL", "=", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "path", "=...
40.8
17.866667
def magnetic_deformation(structure_A, structure_B): """ Calculates 'magnetic deformation proxy', a measure of deformation (norm of finite strain) between 'non-magnetic' (non-spin-polarized) and ferromagnetic structures. Adapted from Bocarsly et al. 2017, doi: 10.1021/acs.chemmater.6b04729 ...
[ "def", "magnetic_deformation", "(", "structure_A", ",", "structure_B", ")", ":", "# retrieve orderings of both input structures", "ordering_a", "=", "CollinearMagneticStructureAnalyzer", "(", "structure_A", ",", "overwrite_magmom_mode", "=", "\"none\"", ")", ".", "ordering", ...
35.605263
18.394737
def get_offset(cls, info): """Calculate the offset to the Xing header from the start of the MPEG header including sync based on the MPEG header's content. """ assert info.layer == 3 if info.version == 1: if info.mode != 3: return 36 else:...
[ "def", "get_offset", "(", "cls", ",", "info", ")", ":", "assert", "info", ".", "layer", "==", "3", "if", "info", ".", "version", "==", "1", ":", "if", "info", ".", "mode", "!=", "3", ":", "return", "36", "else", ":", "return", "21", "else", ":", ...
26.176471
17.529412
def get_docker_network(self, container_id, all_stats): """Return the container network usage using the Docker API (v1.0 or higher). Input: id is the full container id Output: a dict {'time_since_update': 3000, 'rx': 10, 'tx': 65}. with: time_since_update: number of seconds e...
[ "def", "get_docker_network", "(", "self", ",", "container_id", ",", "all_stats", ")", ":", "# Init the returned dict", "network_new", "=", "{", "}", "# Read the rx/tx stats (in bytes)", "try", ":", "netcounters", "=", "all_stats", "[", "\"networks\"", "]", "except", ...
45.754386
24.157895
def load_scrap(self, path): """ Load scraper settings from file :param path: Path to file :type path: str :rtype: None :raises WEBFileException: Failed to load settings :raises WEBParameterException: Missing parameters in file """ try: ...
[ "def", "load_scrap", "(", "self", ",", "path", ")", ":", "try", ":", "conf", "=", "self", ".", "load_settings", "(", "path", ")", "except", ":", "# Should only be IOError", "self", ".", "exception", "(", "\"Failed to load file\"", ")", "raise", "WEBFileExcepti...
35.258065
14.806452
def set_limits(self, limits, coord='data'): """Set the bounding box of the viewer extents. Parameters ---------- limits : tuple or None A tuple setting the extents of the viewer in the form of ``(ll_pt, ur_pt)``. """ if limits is not None: ...
[ "def", "set_limits", "(", "self", ",", "limits", ",", "coord", "=", "'data'", ")", ":", "if", "limits", "is", "not", "None", ":", "if", "len", "(", "limits", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"limits takes a 2 tuple, or None\"", ")", "# ...
31.388889
15.222222
def sha1(s): """ Returns a sha1 of the given string """ h = hashlib.new('sha1') h.update(s) return h.hexdigest()
[ "def", "sha1", "(", "s", ")", ":", "h", "=", "hashlib", ".", "new", "(", "'sha1'", ")", "h", ".", "update", "(", "s", ")", "return", "h", ".", "hexdigest", "(", ")" ]
21.166667
13.666667
def connect(self): """Connects to the Graphite server if not already connected.""" if self.sock is not None: return backoff = 0.01 while True: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(5) sock.connect((self.host, self.port)) ...
[ "def", "connect", "(", "self", ")", ":", "if", "self", ".", "sock", "is", "not", "None", ":", "return", "backoff", "=", "0.01", "while", "True", ":", "try", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", "....
30.4
16.466667
def register_message_callback(self, type_, from_, cb): """ Register a callback to be called when a message is received. :param type_: Message type to listen for, or :data:`None` for a wildcard match. :type type_: :class:`~.MessageType` or :data:`None` :para...
[ "def", "register_message_callback", "(", "self", ",", "type_", ",", "from_", ",", "cb", ")", ":", "if", "type_", "is", "not", "None", ":", "type_", "=", "self", ".", "_coerce_enum", "(", "type_", ",", "structs", ".", "MessageType", ")", "warnings", ".", ...
40.433333
24.266667
def parse(self, s): """Parses the input string, and returns a reference to the created AST's root""" with self.lock: try: return self.parser.parse(s, lexer=self.lexer) except InvalidIEMLObjectArgument as e: raise CannotParse(s, str(e)) ...
[ "def", "parse", "(", "self", ",", "s", ")", ":", "with", "self", ".", "lock", ":", "try", ":", "return", "self", ".", "parser", ".", "parse", "(", "s", ",", "lexer", "=", "self", ".", "lexer", ")", "except", "InvalidIEMLObjectArgument", "as", "e", ...
38.3
13.5
def to_event(self, event_type, field_name=None, depth=None): """Constructs an IonEvent from this _IonNature value. Args: event_type (IonEventType): The type of the resulting event. field_name (Optional[text]): The field name associated with this value, if any. depth ...
[ "def", "to_event", "(", "self", ",", "event_type", ",", "field_name", "=", "None", ",", "depth", "=", "None", ")", ":", "if", "self", ".", "ion_event", "is", "None", ":", "value", "=", "self", "if", "isinstance", "(", "self", ",", "IonPyNull", ")", "...
44.055556
24.055556
def notify(self, new_issues, existing_issues, fixed_issues): """Send notifications (email, slack, etc.) for any issues that are currently open or has just been closed Args: new_issues (`list` of :obj:`DomainHijackIssue`): List of newly discovered issues existing_issues (`list` o...
[ "def", "notify", "(", "self", ",", "new_issues", ",", "existing_issues", ",", "fixed_issues", ")", ":", "if", "len", "(", "new_issues", "+", "existing_issues", "+", "fixed_issues", ")", ">", "0", ":", "maxlen", "=", "max", "(", "len", "(", "x", "[", "'...
43.526316
19.894737
def switch_to(self, newstate): """Switch to a new state newstate : int or string Can be either the value of the state, or the label of the state""" if type(newstate) is int: if newstate in self._states: self._curcode = newstate ...
[ "def", "switch_to", "(", "self", ",", "newstate", ")", ":", "if", "type", "(", "newstate", ")", "is", "int", ":", "if", "newstate", "in", "self", ".", "_states", ":", "self", ".", "_curcode", "=", "newstate", "else", ":", "raise", "Exception", "(", "...
41.666667
15.933333
def diet(filename, configuration): ''' Squeeze files if there is a pipeline defined for them or leave them be otherwise. :param filename: filename of the file to process :param configuration: configuration dict describing commands and pipelines :type configuration: dict :return: has file ch...
[ "def", "diet", "(", "filename", ",", "configuration", ")", ":", "changed", "=", "False", "if", "not", "isfile", "(", "filename", ")", ":", "raise", "NotFileDietException", "(", "'Passed filename does not point to a file'", ")", "conf", "=", "copy", ".", "deepcop...
29.744186
20.209302
def init_database(self): """Initialize database, if it has not been initialized yet.""" with contextlib.closing(self.database.cursor()) as cursor: cursor.execute(""" CREATE TABLE IF NOT EXISTS users( id INTEGER PRIMARY KEY AUTOINCREMENT, name VAR...
[ "def", "init_database", "(", "self", ")", ":", "with", "contextlib", ".", "closing", "(", "self", ".", "database", ".", "cursor", "(", ")", ")", "as", "cursor", ":", "cursor", ".", "execute", "(", "\"\"\"\n CREATE TABLE IF NOT EXISTS users(\n ...
39.222222
10.555556
def _winreg_getShellFolder( name ): """Get a shell folder by string name from the registry""" k = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" ) try: # should check that it's valid? How? return _winreg.Que...
[ "def", "_winreg_getShellFolder", "(", "name", ")", ":", "k", "=", "_winreg", ".", "OpenKey", "(", "_winreg", ".", "HKEY_CURRENT_USER", ",", "r\"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\"", ")", "try", ":", "# should check that it's valid? How?", ...
34.181818
16.454545
def rsa_enc(data, modulus, exponent): """ Simple RAW RSA encryption method, returns byte string. Returns byte string of the same size as the modulus (left padded with 0) :param data: :param modulus: :param exponent: :return: """ modulus = to_long(modulus) exponent = to_long(expo...
[ "def", "rsa_enc", "(", "data", ",", "modulus", ",", "exponent", ")", ":", "modulus", "=", "to_long", "(", "modulus", ")", "exponent", "=", "to_long", "(", "exponent", ")", "data", "=", "to_long", "(", "data", ")", "return", "long_to_bytes", "(", "pow", ...
27.8
20.2
def x_rolls(self, number, count=0, func=sum): '''Iterator of number dice rolls. :param count: [0] Return list of ``count`` sums :param func: [sum] Apply func to list of individual die rolls func([]) ''' for x in range(number): yield self.roll(count, func)
[ "def", "x_rolls", "(", "self", ",", "number", ",", "count", "=", "0", ",", "func", "=", "sum", ")", ":", "for", "x", "in", "range", "(", "number", ")", ":", "yield", "self", ".", "roll", "(", "count", ",", "func", ")" ]
43
13.857143
def neg(x, context=None): """ Return -x. """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_neg, (BigFloat._implicit_convert(x),), context, )
[ "def", "neg", "(", "x", ",", "context", "=", "None", ")", ":", "return", "_apply_function_in_current_context", "(", "BigFloat", ",", "mpfr", ".", "mpfr_neg", ",", "(", "BigFloat", ".", "_implicit_convert", "(", "x", ")", ",", ")", ",", "context", ",", ")...
18.181818
17.090909
def get_host_ip(hostname, fallback=None): """ Resolves the IP for a given hostname, or returns the input if it is already an IP. """ if is_ip(hostname): return hostname ip_addr = ns_query(hostname) if not ip_addr: try: ip_addr = socket.gethostbyname(hostname) ...
[ "def", "get_host_ip", "(", "hostname", ",", "fallback", "=", "None", ")", ":", "if", "is_ip", "(", "hostname", ")", ":", "return", "hostname", "ip_addr", "=", "ns_query", "(", "hostname", ")", "if", "not", "ip_addr", ":", "try", ":", "ip_addr", "=", "s...
27.529412
14.235294
def sersic_constant(self): """ A parameter derived from Sersic index which ensures that effective radius contains 50% of the profile's total integrated light. """ return (2 * self.sersic_index) - (1. / 3.) + (4. / (405. * self.sersic_index)) + ( 46. / (25515. * self.sersi...
[ "def", "sersic_constant", "(", "self", ")", ":", "return", "(", "2", "*", "self", ".", "sersic_index", ")", "-", "(", "1.", "/", "3.", ")", "+", "(", "4.", "/", "(", "405.", "*", "self", ".", "sersic_index", ")", ")", "+", "(", "46.", "/", "(",...
64.857143
24.857143
def Unpack(self, msg): """Unpacks the current Any message into specified message.""" descriptor = msg.DESCRIPTOR if not self.Is(descriptor): return False msg.ParseFromString(self.value) return True
[ "def", "Unpack", "(", "self", ",", "msg", ")", ":", "descriptor", "=", "msg", ".", "DESCRIPTOR", "if", "not", "self", ".", "Is", "(", "descriptor", ")", ":", "return", "False", "msg", ".", "ParseFromString", "(", "self", ".", "value", ")", "return", ...
31
12.571429
def __open(self, url, headers=None, data=None, baseurl=""): """Use raw urlopen command.""" headers = headers or {} if not baseurl: baseurl = self.baseurl req = Request("%s%s" % (baseurl, url), headers=headers) _LOGGER.debug(url) try: req.data = ur...
[ "def", "__open", "(", "self", ",", "url", ",", "headers", "=", "None", ",", "data", "=", "None", ",", "baseurl", "=", "\"\"", ")", ":", "headers", "=", "headers", "or", "{", "}", "if", "not", "baseurl", ":", "baseurl", "=", "self", ".", "baseurl", ...
33.346154
15.038462
def bar(self, subset=None, axis=0, color='#d65f5f', width=100, align='left', vmin=None, vmax=None): """ Draw bar chart in the cell backgrounds. Parameters ---------- subset : IndexSlice, optional A valid slice for `data` to limit the style application to....
[ "def", "bar", "(", "self", ",", "subset", "=", "None", ",", "axis", "=", "0", ",", "color", "=", "'#d65f5f'", ",", "width", "=", "100", ",", "align", "=", "'left'", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ")", ":", "if", "align", "n...
41.304348
21.246377
def destroy(self, request, pk=None): '''For DELETE actions, archive the organization, don't delete.''' org = self.get_object() org.archived = True org.save() return Response(status=status.HTTP_204_NO_CONTENT)
[ "def", "destroy", "(", "self", ",", "request", ",", "pk", "=", "None", ")", ":", "org", "=", "self", ".", "get_object", "(", ")", "org", ".", "archived", "=", "True", "org", ".", "save", "(", ")", "return", "Response", "(", "status", "=", "status",...
40.5
16.5
def _json_to_term_model(term_data): """ Returns a term model created from the passed json data. param: term_data loaded json data """ strptime = datetime.strptime day_format = "%Y-%m-%d" datetime_format = "%Y-%m-%dT%H:%M:%S" term = TermModel() term.year = term_data["Year"] term...
[ "def", "_json_to_term_model", "(", "term_data", ")", ":", "strptime", "=", "datetime", ".", "strptime", "day_format", "=", "\"%Y-%m-%d\"", "datetime_format", "=", "\"%Y-%m-%dT%H:%M:%S\"", "term", "=", "TermModel", "(", ")", "term", ".", "year", "=", "term_data", ...
39.070796
22.787611
def collect_namespaces(metadata): # type: (Mapping[Text, Any]) -> Dict[Text, Text] """Walk through the metadata object, collecting namespace declarations.""" namespaces = {} # type: Dict[Text, Text] if "$import_metadata" in metadata: for value in metadata["$import_metadata"].values(): ...
[ "def", "collect_namespaces", "(", "metadata", ")", ":", "# type: (Mapping[Text, Any]) -> Dict[Text, Text]", "namespaces", "=", "{", "}", "# type: Dict[Text, Text]", "if", "\"$import_metadata\"", "in", "metadata", ":", "for", "value", "in", "metadata", "[", "\"$import_meta...
48.3
11.5
def _clear_ignore(endpoint_props): ''' Both _clear_dict and _ignore_keys in a single iteration. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS and prop_val is not None )
[ "def", "_clear_ignore", "(", "endpoint_props", ")", ":", "return", "dict", "(", "(", "prop_name", ",", "prop_val", ")", "for", "prop_name", ",", "prop_val", "in", "six", ".", "iteritems", "(", "endpoint_props", ")", "if", "prop_name", "not", "in", "_DO_NOT_C...
33
24.555556
def logical_or(self, other): """logical_or(t) = self(t) or other(t).""" return self.operation(other, lambda x, y: int(x or y))
[ "def", "logical_or", "(", "self", ",", "other", ")", ":", "return", "self", ".", "operation", "(", "other", ",", "lambda", "x", ",", "y", ":", "int", "(", "x", "or", "y", ")", ")" ]
46.666667
11.333333
def contains_content_items(self, request, pk, course_run_ids, program_uuids): """ Return whether or not the specified content is available to the EnterpriseCustomer. Multiple course_run_ids and/or program_uuids query parameters can be sent to this view to check for their existence in th...
[ "def", "contains_content_items", "(", "self", ",", "request", ",", "pk", ",", "course_run_ids", ",", "program_uuids", ")", ":", "enterprise_customer", "=", "self", ".", "get_object", "(", ")", "# Maintain plus characters in course key.", "course_run_ids", "=", "[", ...
54.227273
33.318182
def path_args(self): """the path converted to list (eg /foo/bar becomes [foo, bar])""" self._path_args = [] path = self.path path_args = list(filter(None, path.split('/'))) return path_args
[ "def", "path_args", "(", "self", ")", ":", "self", ".", "_path_args", "=", "[", "]", "path", "=", "self", ".", "path", "path_args", "=", "list", "(", "filter", "(", "None", ",", "path", ".", "split", "(", "'/'", ")", ")", ")", "return", "path_args"...
37.333333
13.166667
def _lookup_handler(name): """ Look up the implementation of a named handler. Broken out for testing purposes. :param name: The name of the handler to look up. :returns: A factory function for the log handler. """ # Look up and load the handler factory for ep in pkg_resources.iter_en...
[ "def", "_lookup_handler", "(", "name", ")", ":", "# Look up and load the handler factory", "for", "ep", "in", "pkg_resources", ".", "iter_entry_points", "(", "'bark.handler'", ",", "name", ")", ":", "try", ":", "# Load and return the handler factory", "return", "ep", ...
30
19.3
def pic_loggedrequiredremoterelease_v1(self): """Update the receiver link sequence.""" log = self.sequences.logs.fastaccess rec = self.sequences.receivers.fastaccess log.loggedrequiredremoterelease[0] = rec.d[0]
[ "def", "pic_loggedrequiredremoterelease_v1", "(", "self", ")", ":", "log", "=", "self", ".", "sequences", ".", "logs", ".", "fastaccess", "rec", "=", "self", ".", "sequences", ".", "receivers", ".", "fastaccess", "log", ".", "loggedrequiredremoterelease", "[", ...
44.6
3.8
def get_attrib(xml, name, tag=None, cast=str, default=None): """Returns the specified attribute from the XML element, raising a ValueError if it is not availaible. :arg xml: the XMLElement instance to get the attribute from. :arg name: the name of the attribute in xml.attrib dictionary. :arg ta...
[ "def", "get_attrib", "(", "xml", ",", "name", ",", "tag", "=", "None", ",", "cast", "=", "str", ",", "default", "=", "None", ")", ":", "if", "name", "in", "xml", ".", "attrib", ":", "return", "cast", "(", "xml", ".", "attrib", "[", "name", "]", ...
44.928571
19.928571
def post_structure(entry, site): """ A post structure with extensions. """ author = entry.authors.all()[0] return {'title': entry.title, 'description': six.text_type(entry.html_content), 'link': '%s://%s%s' % (PROTOCOL, site.domain, entry.ge...
[ "def", "post_structure", "(", "entry", ",", "site", ")", ":", "author", "=", "entry", ".", "authors", ".", "all", "(", ")", "[", "0", "]", "return", "{", "'title'", ":", "entry", ".", "title", ",", "'description'", ":", "six", ".", "text_type", "(", ...
44.896552
10.965517
def get_locations(self, url): """Get valid location header values from responses. :param url: a URL address. If a HEAD request sent to it fails because the address has invalid schema, times out or there is a connection error, the generator yields nothing. :returns: valid redirec...
[ "def", "get_locations", "(", "self", ",", "url", ")", ":", "if", "not", "is_valid_url", "(", "url", ")", ":", "raise", "InvalidURLError", "(", "'{} is not a valid URL'", ".", "format", "(", "url", ")", ")", "try", ":", "response", "=", "self", ".", "sess...
42.483871
17.580645
def PMIS(S): """C/F splitting using the Parallel Modified Independent Set method. Parameters ---------- S : csr_matrix Strength of connection matrix indicating the strength between nodes i and j (S_ij) Returns ------- splitting : ndarray Array of length of S of ones...
[ "def", "PMIS", "(", "S", ")", ":", "S", "=", "remove_diagonal", "(", "S", ")", "weights", ",", "G", ",", "S", ",", "T", "=", "preprocess", "(", "S", ")", "return", "MIS", "(", "G", ",", "weights", ")" ]
25.6
24.428571
def clear( # type: ignore self, ch: int = ord(" "), fg: Tuple[int, int, int] = ..., bg: Tuple[int, int, int] = ..., ) -> None: """Reset all values in this console to a single value. `ch` is the character to clear the console with. Defaults to the space char...
[ "def", "clear", "(", "# type: ignore", "self", ",", "ch", ":", "int", "=", "ord", "(", "\" \"", ")", ",", "fg", ":", "Tuple", "[", "int", ",", "int", ",", "int", "]", "=", "...", ",", "bg", ":", "Tuple", "[", "int", ",", "int", ",", "int", "]...
35.28125
18.125
def update_fw(self, nids, fw_type, fw_ver, fw_path=None): """Update firwmare of all node_ids in nids.""" fw_bin = None if fw_path: fw_bin = load_fw(fw_path) if not fw_bin: return self.ota.make_update(nids, fw_type, fw_ver, fw_bin)
[ "def", "update_fw", "(", "self", ",", "nids", ",", "fw_type", ",", "fw_ver", ",", "fw_path", "=", "None", ")", ":", "fw_bin", "=", "None", "if", "fw_path", ":", "fw_bin", "=", "load_fw", "(", "fw_path", ")", "if", "not", "fw_bin", ":", "return", "sel...
36.875
13.875
def AddHash(self, sha1, md5, crc, file_name, file_size, product_code_list, op_system_code_list, special_code): """Adds a new file from the NSRL hash database. We create a new subject in: aff4:/files/nsrl/<sha1> with all the other arguments as attributes. Args: sha1: SHA1 dige...
[ "def", "AddHash", "(", "self", ",", "sha1", ",", "md5", ",", "crc", ",", "file_name", ",", "file_size", ",", "product_code_list", ",", "op_system_code_list", ",", "special_code", ")", ":", "file_store_urn", "=", "self", ".", "PATH", ".", "Add", "(", "sha1"...
36.147059
16.205882
def find_types_added_to_unions( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> List[DangerousChange]: """Find types added to union. Given two schemas, returns a list containing descriptions of any dangerous changes in the new_schema related to adding types to a union type. """ old_ty...
[ "def", "find_types_added_to_unions", "(", "old_schema", ":", "GraphQLSchema", ",", "new_schema", ":", "GraphQLSchema", ")", "->", "List", "[", "DangerousChange", "]", ":", "old_type_map", "=", "old_schema", ".", "type_map", "new_type_map", "=", "new_schema", ".", ...
41.275862
16.586207
def filter_cols(model, *filtered_columns): """Return columnsnames for a model except named ones. Useful for defer() for example to retain only columns of interest """ m = sa.orm.class_mapper(model) return list( {p.key for p in m.iterate_properties if hasattr(p, "columns")}.difference( ...
[ "def", "filter_cols", "(", "model", ",", "*", "filtered_columns", ")", ":", "m", "=", "sa", ".", "orm", ".", "class_mapper", "(", "model", ")", "return", "list", "(", "{", "p", ".", "key", "for", "p", "in", "m", ".", "iterate_properties", "if", "hasa...
31.727273
20.090909
def reverseDict(d): """ Helper for generating fullToTag Makes dict of value to key """ retD = {} for k in d: retD[d[k]] = k return retD
[ "def", "reverseDict", "(", "d", ")", ":", "retD", "=", "{", "}", "for", "k", "in", "d", ":", "retD", "[", "d", "[", "k", "]", "]", "=", "k", "return", "retD" ]
18.111111
14.555556
def inference_q(self, next_action_arr): ''' Infernce Q-Value. Args: next_action_arr: `np.ndarray` of action. Returns: `np.ndarray` of Q-Values. ''' q_arr = next_action_arr.reshape((next_action_arr.shape[0], -1)) self._...
[ "def", "inference_q", "(", "self", ",", "next_action_arr", ")", ":", "q_arr", "=", "next_action_arr", ".", "reshape", "(", "(", "next_action_arr", ".", "shape", "[", "0", "]", ",", "-", "1", ")", ")", "self", ".", "__q_arr_list", ".", "append", "(", "q...
35.47619
17.666667
def characterize(cls, record): """Load the record in a concrete subclass of this type. """ classes = list(cls.__subclasses__()) if not isabstract(cls): classes.append(cls) for subclass in classes: entity = subclass(record) if entity.is_valid():...
[ "def", "characterize", "(", "cls", ",", "record", ")", ":", "classes", "=", "list", "(", "cls", ".", "__subclasses__", "(", ")", ")", "if", "not", "isabstract", "(", "cls", ")", ":", "classes", ".", "append", "(", "cls", ")", "for", "subclass", "in",...
38.272727
9.181818
def ajax_upload(request, folder_id=None): """ Receives an upload from the uploader. Receives only one file at a time. """ folder = None if folder_id: try: # Get folder folder = Folder.objects.get(pk=folder_id) except Folder.DoesNotExist: return Jso...
[ "def", "ajax_upload", "(", "request", ",", "folder_id", "=", "None", ")", ":", "folder", "=", "None", "if", "folder_id", ":", "try", ":", "# Get folder", "folder", "=", "Folder", ".", "objects", ".", "get", "(", "pk", "=", "folder_id", ")", "except", "...
40.368932
16
def isSurrounded(self): """ Returns if the object is separating and applying to a malefic considering bad aspects. """ malefics = [const.MARS, const.SATURN] return self.__sepApp(malefics, aspList=[0, 90, 180])
[ "def", "isSurrounded", "(", "self", ")", ":", "malefics", "=", "[", "const", ".", "MARS", ",", "const", ".", "SATURN", "]", "return", "self", ".", "__sepApp", "(", "malefics", ",", "aspList", "=", "[", "0", ",", "90", ",", "180", "]", ")" ]
36.142857
10.857143
def requires_user(fn): """ Requires that the calling Subject be *either* authenticated *or* remembered via RememberMe services before allowing access. This method essentially ensures that subject.identifiers IS NOT None """ @functools.wraps(fn) def wrap(*args, **...
[ "def", "requires_user", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "wrap", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "subject", "=", "WebYosai", ".", "get_current_subject", "(", ")", "if", "subject", ".", ...
40.9
21.7
def match_rule_patterns(fixed_text, cur=0): """Matches given text at cursor position with rule patterns Returns a dictionary of four elements: - "matched" - Bool: depending on if match found - "found" - string/None: Value of matched pattern's 'find' key or none - "replaced": string Replaced string...
[ "def", "match_rule_patterns", "(", "fixed_text", ",", "cur", "=", "0", ")", ":", "pattern", "=", "exact_find_in_pattern", "(", "fixed_text", ",", "cur", ",", "RULE_PATTERNS", ")", "# if len(pattern) == 1:", "if", "len", "(", "pattern", ")", ">", "0", ":", "r...
40.4
21.9
def plot_hdd(HDD, B, M, s): """ Function to make hysteresis, deltaM and DdeltaM plots Parameters: _______________ Input HDD : dictionary with figure numbers for the keys: 'hyst' : hysteresis plot normalized to maximum value 'deltaM' : Delta M plot 'Ddelt...
[ "def", "plot_hdd", "(", "HDD", ",", "B", ",", "M", ",", "s", ")", ":", "hpars", ",", "deltaM", ",", "Bdm", "=", "plot_hys", "(", "HDD", "[", "'hyst'", "]", ",", "B", ",", "M", ",", "s", ")", "# Moff is the \"fixed\" loop data", "DdeltaM", "=", "[",...
36
15.702128
def _check_for_cycle(self, variable, period): """ Raise an exception in the case of a circular definition, where evaluating a variable for a given period loops around to evaluating the same variable/period pair. Also guards, as a heuristic, against "quasicircles", where the evaluation of...
[ "def", "_check_for_cycle", "(", "self", ",", "variable", ",", "period", ")", ":", "previous_periods", "=", "[", "_period", "for", "(", "_name", ",", "_period", ")", "in", "self", ".", "computation_stack", "if", "_name", "==", "variable", ".", "name", "]", ...
66.375
32.75
def sign_file(self, filepath): """Signs file if possible""" if not GPG_PRESENT: return signed_data = sign(filepath) signature = signed_data.data if signature is None or not signature: statustext = _('Error signing file. ') + signed_data.stderr ...
[ "def", "sign_file", "(", "self", ",", "filepath", ")", ":", "if", "not", "GPG_PRESENT", ":", "return", "signed_data", "=", "sign", "(", "filepath", ")", "signature", "=", "signed_data", ".", "data", "if", "signature", "is", "None", "or", "not", "signature"...
29.638889
20.305556
def quantileclip(arrays, masks=None, dtype=None, out=None, zeros=None, scales=None, weights=None, fclip=0.10): """Combine arrays using the sigma-clipping, with masks. Inputs and masks are a list of array objects. All input arrays have the same shape. If present, the masks ...
[ "def", "quantileclip", "(", "arrays", ",", "masks", "=", "None", ",", "dtype", "=", "None", ",", "out", "=", "None", ",", "zeros", "=", "None", ",", "scales", "=", "None", ",", "weights", "=", "None", ",", "fclip", "=", "0.10", ")", ":", "return", ...
48.782609
23.913043
def getHostCaPath(self, name): ''' Gets the path to the CA certificate that issued a given host keypair. Args: name (str): The name of the host keypair. Examples: Get the path to the CA cert which issue the cert for "myhost": mypath = cdir.getHo...
[ "def", "getHostCaPath", "(", "self", ",", "name", ")", ":", "cert", "=", "self", ".", "getHostCert", "(", "name", ")", "if", "cert", "is", "None", ":", "return", "None", "return", "self", ".", "_getCaPath", "(", "cert", ")" ]
25.55
24.15
def ibatch(size, iterable=None, rest=False): """ add example :param size: :param iterable: :param rest: :return: """ @iterflow def exact_size(it): it = iter(it) while True: yield [it.next() for _ in xrange(size)] @iterflow def at_most(it): ...
[ "def", "ibatch", "(", "size", ",", "iterable", "=", "None", ",", "rest", "=", "False", ")", ":", "@", "iterflow", "def", "exact_size", "(", "it", ")", ":", "it", "=", "iter", "(", "it", ")", "while", "True", ":", "yield", "[", "it", ".", "next", ...
22.59375
18.21875
def push(self, index=None): """Push built documents to ElasticSearch. If ``index`` is specified, only that index will be pushed. """ for ind in self.indexes: if index and not isinstance(ind, index): continue ind.push()
[ "def", "push", "(", "self", ",", "index", "=", "None", ")", ":", "for", "ind", "in", "self", ".", "indexes", ":", "if", "index", "and", "not", "isinstance", "(", "ind", ",", "index", ")", ":", "continue", "ind", ".", "push", "(", ")" ]
31.444444
14.777778
def parse(cls, fptr, offset, length): """Parse data reference box. Parameters ---------- fptr : file Open file object. offset : int Start position of box in bytes. length : int Length of the box in bytes. Returns -----...
[ "def", "parse", "(", "cls", ",", "fptr", ",", "offset", ",", "length", ")", ":", "num_bytes", "=", "offset", "+", "length", "-", "fptr", ".", "tell", "(", ")", "read_buffer", "=", "fptr", ".", "read", "(", "num_bytes", ")", "# Read the number of data ref...
32.545455
19.840909
def cycle_list(self,*args): ''' return the list of cycles contained if the dataset ''' noargs = len(args) == 0 return np.unique(self.cycle) if noargs else np.unique(self.cycle.compress(args[0]))
[ "def", "cycle_list", "(", "self", ",", "*", "args", ")", ":", "noargs", "=", "len", "(", "args", ")", "==", "0", "return", "np", ".", "unique", "(", "self", ".", "cycle", ")", "if", "noargs", "else", "np", ".", "unique", "(", "self", ".", "cycle"...
39
24.333333
def get_table_metadata(self, resource, resource_class): """ Get metadata for a given resource: class :param resource: The name of the resource :param resource_class: The name of the class to get metadata from :return: list """ return self._make_metadata_request(me...
[ "def", "get_table_metadata", "(", "self", ",", "resource", ",", "resource_class", ")", ":", "return", "self", ".", "_make_metadata_request", "(", "meta_id", "=", "resource", "+", "':'", "+", "resource_class", ",", "metadata_type", "=", "'METADATA-TABLE'", ")" ]
47.875
19.875
def get_default_config(self): """ Return the default config for the handler """ config = super(MySQLHandler, self).get_default_config() config.update({ }) return config
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "MySQLHandler", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "}", ")", "return", "config" ]
21.7
18.9
def neighbors(self, node_id): """Find all the nodes where there is an edge from the specified node to that node. Returns a list of node ids.""" node = self.get_node(node_id) flattened_nodes_list = [] for a, b in [self.get_edge(edge_id)['vertices'] for edge_id in node['edges']]: ...
[ "def", "neighbors", "(", "self", ",", "node_id", ")", ":", "node", "=", "self", ".", "get_node", "(", "node_id", ")", "flattened_nodes_list", "=", "[", "]", "for", "a", ",", "b", "in", "[", "self", ".", "get_edge", "(", "edge_id", ")", "[", "'vertice...
45.666667
7.333333
def get_instance_by_bin_uuid(model, bin_uuid): """Get an instance by binary uuid. :param model: a string, model name in rio.models. :param bin_uuid: a 16-bytes binary string. :return: None or a SQLAlchemy instance. """ try: model = get_model(model) except ImportError: return...
[ "def", "get_instance_by_bin_uuid", "(", "model", ",", "bin_uuid", ")", ":", "try", ":", "model", "=", "get_model", "(", "model", ")", "except", "ImportError", ":", "return", "None", "return", "model", ".", "query", ".", "filter_by", "(", "*", "*", "{", "...
29.307692
16.307692