code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
procs = contents.split("module procedure")
stripped = [p.strip() for p in procs if p.strip() != ""]
for embed in stripped:
#We want to first extract the name of the procedure, then find its element
#instance to append to the Interface instance's procedures list.
... | def _parse_procedures(self, contents, iface) | Parses the list of procedures or signatures defined in the generic, operator
or assignment interface.
:arg contents: the text between the interface ... end interface keywords.
:arg iface: the fortpy.elements.Interface instance that will own the parsed
procedures/signatures. | 7.801761 | 7.280852 | 1.071545 |
from fortpy import config
import sys
from os import path
includes = sys.modules["config"].includes
linklibs = False
if extralinks is not None and len(extralinks) > 0:
for i, link in enumerate(extralinks):
lines.append("LBD{0:d} = {1}".format(i, link))
lines.ap... | def _add_explicit_includes(lines, dependencies=None, extralinks=None) | Adds any relevant libraries that need to be explicitly included according
to the fortpy configuration file. Libraries are appended to the specified
collection of lines. Returns true if relevant libraries were added. | 3.925863 | 3.612852 | 1.086638 |
base =
if extralinks is not None and len(extralinks) > 0:
from os import path
libs = []
for i, link in enumerate(extralinks):
#We can only include *directories* for the -I specification.
if path.isdir(link):
libs.append("-I$(LBD{0:d})".format... | def _make_compiler_include(precompile, extralinks) | Returns the include statement for the compiler to use. | 8.02221 | 7.710862 | 1.040378 |
linktxt = "$(LIBS) " if linklibs else ""
redirect = "" if verbose else " > /dev/null"
base =
return base.format(linktxt, identifier, redirect) | def _make_exe(linklibs, identifier, verbose) | Generates the script to run the compiling. | 11.700206 | 11.888816 | 0.984136 |
module, method = identifier.split(".")
redirect = "| tee -a" if verbose else " >>"
return .format(module, method, redirect) | def _make_info(identifier, verbose) | Generates the script for displaying compile-time info. | 16.563601 | 12.963772 | 1.277684 |
if mapped in parser.mappings:
return parser.mappings[mapped]
else:
return mapped + ".f90" | def _get_mapping(parser, mapped) | Gets the original file name for a module that was mapped
when the module name does not coincide with the file name
that the module was defined in. | 6.140894 | 5.025375 | 1.221977 |
subtags = ietf.split('-')
language_subtag = subtags.pop(0).lower()
if len(language_subtag) == 2:
language = cls.fromalpha2(language_subtag)
else:
language = cls(language_subtag)
while subtags:
subtag = subtags.pop(0)
if len... | def fromietf(cls, ietf) | Create a :class:`Language` by from an IETF language code
:param string ietf: the ietf code
:return: the corresponding :class:`Language` instance
:rtype: :class:`Language` | 2.810785 | 2.69195 | 1.044145 |
overrides = overrides or {}
for key, value in iteritems(overrides):
current = self.get(key)
if isinstance(value, dict) and isinstance(current, dict):
current.patch(value)
else:
self[key] = value | def patch(self, overrides) | Patches the config with the given overrides.
Example:
If the current dictionary looks like this:
a: 1,
b: {
c: 3,
d: 4
}
and `patch` is called with the following overrides:
b: {
d: 2,
e: 4
},
c: 5
... | 2.511104 | 3.462852 | 0.725155 |
# Read the controller information.
self.controller_info = customer_details(self._user_token)
self.controller_status = status_schedule(self._user_token)
if self.controller_info is None or self.controller_status is None:
return False
# Only supports one cont... | def update_controller_info(self) | Pulls controller information.
:returns: True if successfull, otherwise False.
:rtype: boolean | 2.862679 | 2.849752 | 1.004536 |
if hasattr(self, 'controller_id'):
if len(self.controller_info['controllers']) > 1:
raise TypeError(
'Only one controller per account is supported.'
)
return self.controller_id
raise AttributeError('No controllers assi... | def controller(self) | Check if multiple controllers are connected.
:returns: Return the controller_id of the active controller.
:rtype: string | 5.969669 | 5.083196 | 1.174393 |
# Check if the relay number is valid.
if (relay < 0) or (relay > (self.num_relays - 1)):
# Invalid relay index specified.
return None
else:
if attribute is None:
# Return all the relay attributes.
return self.relays[re... | def relay_info(self, relay, attribute=None) | Return information about a relay.
:param relay: The relay being queried.
:type relay: int
:param attribute: The attribute being queried, or all attributes for
that relay if None is specified.
:type attribute: string or None
:returns: The attribute being... | 2.877147 | 2.864773 | 1.004319 |
if zone is None:
zone_cmd = 'suspendall'
relay_id = None
else:
if zone < 0 or zone > (len(self.relays) - 1):
return None
else:
zone_cmd = 'suspend'
relay_id = self.relays[zone]['relay_id']
#... | def suspend_zone(self, days, zone=None) | Suspend or unsuspend a zone or all zones for an amount of time.
:param days: Number of days to suspend the zone(s)
:type days: int
:param zone: The zone to suspend. If no zone is specified then suspend
all zones
:type zone: int or None
:returns: The response... | 3.191256 | 2.954241 | 1.080229 |
if zone is None:
zone_cmd = 'runall'
relay_id = None
else:
if zone < 0 or zone > (len(self.relays) - 1):
return None
else:
zone_cmd = 'run'
relay_id = self.relays[zone]['relay_id']
if minute... | def run_zone(self, minutes, zone=None) | Run or stop a zone or all zones for an amount of time.
:param minutes: The number of minutes to run.
:type minutes: int
:param zone: The zone number to run. If no zone is specified then run
all zones.
:type zone: int or None
:returns: The response from set_z... | 3.107851 | 2.73626 | 1.135802 |
self.update_controller_info()
if self.running is None or not self.running:
return None
return int(self.running[0]['relay']) | def list_running_zones(self) | Returns the currently active relay.
:returns: Returns the running relay number or None if no relays are
active.
:rtype: string | 11.464792 | 7.412127 | 1.546762 |
self.update_controller_info()
if self.running is None or not self.running:
return False
if int(self.running[0]['relay']) == zone:
return True
return False | def is_zone_running(self, zone) | Returns the state of the specified zone.
:param zone: The zone to check.
:type zone: int
:returns: Returns True if the zone is currently running, otherwise
returns False if the zone is not running.
:rtype: boolean | 6.987227 | 7.427931 | 0.940669 |
self.update_controller_info()
if zone < 0 or zone > (self.num_relays-1):
return None
if self.is_zone_running(zone):
return int(self.running[0]['time_left'])
return 0 | def time_remaining(self, zone) | Returns the amount of watering time left in seconds.
:param zone: The zone to check.
:type zone: int
:returns: If the zone is not running returns 0. If the zone doesn't
exist returns None. Otherwise returns number of seconds left
in the watering cycle.
... | 6.072986 | 5.288773 | 1.148279 |
if self._cache is None:
self._cache = django_cache.get_cache(self.cache_name)
return self._cache | def cache(self) | Memoize access to the cache backend. | 3.455799 | 2.432841 | 1.420479 |
#We need to handle docstrings separately because they are XML and slight
#insertions/changes can't be handled using only one line. We have to get
#hold of the entire XML block and parse it all at once again.
if op.state[0] is None:
linenum, statement, length = op.cur... | def parse(self, op, mode=None) | Handles the parsing of the specified operation using the current
statements from the buffer/cache. If 'comment' is not None, the
statement in comment is parsed instead.
:arg mode: override the 'insert', 'replace' or 'delete' specifier. | 9.896342 | 9.336904 | 1.059917 |
search = string[start:end]
abs_start = self.refstring.index(search)
return abs_start, (end - start) + abs_start | def absolute_charindex(self, string, start, end) | Finds the absolute character index of the specified regex match
start and end indices in the *buffer* refstring. | 5.358951 | 4.52398 | 1.184565 |
#Make sure that we have chars and lines to work from
if len(context.bufferstr) > 0 and len(self._chars) == 0:
#Add one for the \n that we split on for each line
self._chars = [ len(x) + 1 for x in context.bufferstr ]
#Remove the last line break since it doesn... | def charindex(self, line, char, context) | Determines the absolute character index for the specified line
and char using the *buffer's* code string. | 5.298854 | 5.119805 | 1.034972 |
#We assume here that the entire operation is associated with a single
#code element. Since the sequence matcher groups operations by contiguous
#lines of code to change, this is a safe assumption.
if self._element is None:
line = self.icached[0]
#If we ar... | def element(self) | Returns the instance of the element who owns the first line
number for the operation in the cached source code. | 11.927129 | 10.056243 | 1.186042 |
#This is needed since the decorating documentation
#for types and executables is in the body of the module, but when they
#get edited, the edit belongs to the type/executable because the character
#falls within the absstart and end attributes.
if self._docelement is None... | def docelement(self) | Returns the instance of the element whose body owns the docstring
in the current operation. | 8.493482 | 7.643541 | 1.111197 |
#If we have more statements in the buffer than the cached, it doesn't matter,
#we just run the first few replacements of the cache concurrently and do
#what's left over from the buffer.
#REVIEW
if self.mode == "insert": #then self.icached[0] == self.icached[1]:
... | def handle(self) | Handles the real time update of some code from the cached representation
of the module. | 4.634363 | 4.482505 | 1.033878 |
#Docstrings have to be continuous sets of lines that start with !!
#When they change in any way (i.e. any of the three modes), we
#have to reparse the entire block because it has XML dependencies
#Because of that, the cached version of the docstrings is actually
#pointl... | def _handle_docstrings(self) | Searches through the lines affected by this operation to find
blocks of adjacent docstrings to parse for the current element. | 8.703686 | 8.334238 | 1.044329 |
result = {}
for block, docline, doclength, key in blocks:
doctext = "<doc>{}</doc>".format(" ".join(block))
try:
docs = ET.XML(doctext)
docstart = self.parser.charindex(docline, 0, self.context)
if not key in result:
... | def _docstring_parse(self, blocks) | Parses the XML from the specified blocks of docstrings. | 7.088642 | 6.661216 | 1.064166 |
#If there are no lines to look at, we have nothing to do here.
if self.ibuffer[0] == self.ibuffer[1]:
return []
lines = self.context.bufferstr[self.ibuffer[0]:self.ibuffer[1]]
docblock = []
result = []
self._doclines = []
#We need to keep tr... | def _docstring_getblocks(self) | Gets the longest continuous block of docstrings from the buffer
code string if any of those lines are docstring lines. | 3.517559 | 3.500489 | 1.004877 |
decormatch = self.docparser.RE_DECOR.match(line)
if decormatch is not None:
key = "{}.{}".format(self.docelement.name, decormatch.group("name"))
else:
key = self.element.name
return key | def _docstring_key(self, line) | Returns the key to use for the docblock immediately preceding
the specified line. | 6.178761 | 5.952327 | 1.038041 |
#For new instances, their length is being updated by the module
#updater and will include *all* statements, so we don't want to
#keep changing the endpoints.
if self.bar_extent:
return
original = self.element.end
if self.mode == "insert":... | def _update_extent(self) | Updates the extent of the element being altered by this operation
to include the code that has changed. | 7.93017 | 7.224044 | 1.097747 |
lines = self.context.bufferstr[self.ibuffer[0]:self.ibuffer[1]]
return self._get_statements(lines, self.ibuffer[0]) | def _get_buffered(self) | Gets a list of the statements that are new for the real time update. | 8.385125 | 6.346705 | 1.321178 |
lines = self.context.cachedstr[self.icached[0]:self.icached[1]]
return self._get_statements(lines, self.icached[0]) | def _get_cached(self) | Gets a list of statements that the operation will affect during the real
time update. | 11.030875 | 9.432794 | 1.169418 |
result = []
statement = []
nocomment = [l.split("!")[0] for l in lines]
length = 0
for i in range(len(nocomment)):
line = nocomment[i].strip()
linenum = start + i
length += len(lines[i]) + 1
if len(line) == 0 or line[-1] ... | def _get_statements(self, lines, start) | Returns a list of complete Fortran statements for the specified lines by
dealing with comments and line continuations. Returns a list of tuples of
the form (linenum, statement, orginal character length).
:arg start: the start index in the overall document for these lines. | 3.790097 | 3.441698 | 1.101229 |
#Get a list of all the operations that need to be performed and then
#execute them.
self._operations = self._get_operations(context)
for i in range(len(self._operations)):
self._operations[i].handle()
self.update_extent(self._operations[i])
#Las... | def update(self, context) | Updates all references in the cached representation of the module
with their latest code from the specified source code string that
was extracted from the emacs buffer.
:arg context: the buffer context information. | 7.260538 | 6.228271 | 1.165739 |
#Operations represent continuous lines of code.
#The last operation to be executed is still the current one.
line, col = operation.start
operation.context.module.update_elements(line, col, operation.length,
operation.docdelta) | def update_extent(self, operation) | Updates the extent of the *module* and its elements using the
specified operation which has already been executed. | 25.156433 | 20.262611 | 1.24152 |
#Most of the time, the real-time update is going to fire with
#incomplete statements that don't result in any changes being made
#to the module instances. The SequenceMatches caches hashes for the
#second argument. Logically, we want to turn the cached version into
#the ... | def _get_operations(self, context) | Returns a list of operations that need to be performed to turn the
cached source code into the one in the buffer. | 7.26119 | 6.90303 | 1.051885 |
#Essentially, we want to look in the rest of the statements that are
#part of the current operation to see how many more of them pertain
#to the new instance that was added.
#New signatures only result in instances being added if mode is "insert"
#or "replace". In both... | def update_instance_extent(self, instance, module, operation) | Updates a new instance that was added to a module to be complete
if the end token is present in any remaining, overlapping operations. | 7.513592 | 7.039451 | 1.067355 |
ibuffer, icache = operation.state
length = operation.buffered[ibuffer][2]
result = None
for i in range(len(operation.buffered) - ibuffer - 1):
linenum, statement, charlength = operation.buffered[i + ibuffer + 1]
length += charlength
... | def _find_end_token(self, end_token, operation) | Looks for a statement in the operation's list that matches the specified
end token. Returns the index of the statement in the operation that matches. | 6.629577 | 6.453654 | 1.027259 |
default = kwargs.get('default')
coherent = kwargs.get('coherent', False)
for key in keys:
yield self.get(key, default=default) | def mget(self, *keys, **kwargs) | Retrieve values for a set of keys.
Args:
keys (str list): the list of keys whose value should be retrieved
Keyword arguements:
default (object): the value to use for non-existent keys
coherent (bool): whether all fetched values should be "coherent",
... | 4.8521 | 4.226372 | 1.148053 |
for key, value in values.items():
self.set(key, value) | def mset(self, values) | Set the value of several keys at once.
Args:
values (dict): maps a key to its value. | 3.186415 | 3.818608 | 0.834444 |
#This is where the context information is extremely useful in
#limiting the extent of the search space we need to examine.
if self._names is None:
attribute = self.get_attribute()
if self.context.module is not None:
symbol = self.context.symbol
... | def names(self) | Returns a list of possible completions for the symbol under the
cursor in the current user context. | 8.403943 | 7.903738 | 1.063287 |
#The important thing to keep track of here is that '(' can be
#pushed in the following places:
# - in a subroutine/function definition
# - when calling a function or subroutine, this includes calls within
# the argument list of a function, e.g. function(a, fnb(c,d), e)... | def bracket_complete(self) | Returns a function call signature for completion whenever
a bracket '(' is pressed. | 10.537351 | 10.197502 | 1.033327 |
if symbol != fullsymbol:
#We have a sym%sym%... chain and the completion just needs to
#be the signature of the member method.
target, targmod = self._get_chain_parent_symbol(symbol, fullsymbol)
if symbol in target.executables:
child = ta... | def _bracket_complete_sig(self, symbol, fullsymbol) | Returns the call signature and docstring for the executable
immediately preceding a bracket '(' that was typed. | 6.997758 | 6.956061 | 1.005994 |
if variable is not None:
#Look for <dimension> descriptors that are children of the variable
#in its docstrings.
dims = variable.doc_children("dimension", ["member", "parameter", "local"])
descript = str(variable)
if len(dims) > 0:
... | def _bracket_dim_suggest(self, variable) | Returns a dictionary of documentation for helping complete the
dimensions of a variable. | 9.39236 | 8.43894 | 1.112979 |
#Check the variables first, then the functions.
match = self._bracket_exact_var(self.context.exact_match)
if match is None:
match = self._bracket_exact_exec(self.context.exact_match)
return match | def get_definition(self) | Checks variable and executable code elements based on the current
context for a code element whose name matches context.exact_match
perfectly. | 10.84761 | 5.776311 | 1.877947 |
if isinstance(self.element, Executable):
if symbol in self.element.parameters:
return self.element.parameters[symbol]
if symbol in self.element.members:
return self.element.members[symbol]
if symbol in self.element.module.memb... | def _bracket_exact_var(self, symbol) | Checks local first and then module global variables for an exact
match to the specified symbol name. | 3.241775 | 3.016483 | 1.074687 |
if symbol in self.context.module.executables:
return self.context.module.executables[symbol]
if symbol in self.context.module.interfaces:
return self.context.module.interfaces[symbol]
if symbol in cache.builtin:
return cache.builtin[symbol]
... | def _bracket_exact_exec(self, symbol) | Checks builtin, local and global executable collections for the
specified symbol and returns it as soon as it is found. | 4.496355 | 4.066686 | 1.105656 |
if iexec is not None:
summary = iexec.summary
if isinstance(iexec, Function):
summary = iexec.returns + "| " + iexec.summary
elif isinstance(iexec, Subroutine) and len(iexec.modifiers) > 0:
summary = ", ".join(iexec.modifiers) + " | " ... | def _compile_signature(self, iexec, call_name) | Compiles the signature for the specified executable and returns
as a dictionary. | 4.586912 | 4.401868 | 1.042038 |
#See if we are calling a function inside a module or other function.
result = []
if (self.context.el_section == "body" and
self.context.el_call in [ "sub", "fun" ]):
#Do a signature completion for the function/subroutine call.
result = self.signature(... | def in_function_call(self) | This function is called whenever the cursor/buffer goes idle for
a second. The real workhorse of the intellisense. Decides what kind
of intellisense is needed and returns the relevant response. | 11.024949 | 9.44037 | 1.167851 |
#We can't really do anything sensible without the name of the function
#whose signature we are completing.
iexec, execmod = self.context.parser.tree_find(self.context.el_name,
self.context.module, "executables")
if iexec is None:
... | def signature(self) | Gets completion or call signature information for the current cursor. | 9.006728 | 8.169371 | 1.1025 |
#Find out where in the signature the cursor is at the moment.
call_index = self.context.call_arg_index
if call_index is not None:
#We found the index of the parameter whose docstring we want
#to return.
param = iexec.get_parameter(call_index)
... | def _signature_index(self, iexec) | Determines where in the call signature the cursor is to decide which
parameter needs to have its information returned for the intellisense. | 5.125088 | 4.78797 | 1.070409 |
if self._possible is None:
self._possible = []
for possible in self.names:
c = Completion(self.context, self.names[possible], len(self.context.symbol))
self._possible.append(c)
return self._possible | def complete(self) | Gets a list of completion objects for the symbol under the cursor. | 5.789725 | 4.872297 | 1.188295 |
lsymbol = symbol.lower()
lname = name.lower()
return lsymbol == lname[:len(symbol)] or "_" + lsymbol in lname | def _symbol_in(self, symbol, name) | Checks whether the specified symbol is part of the name for completion. | 6.88465 | 4.735114 | 1.453957 |
if symbol != fullsymbol:
#We have a sym%sym%... chain and the completion just needs to
#be a member variable or method of the type being referenced.
return self._complete_type_chain(symbol, fullsymbol)
if self.context.el_section == "params":
#The... | def _complete_el(self, symbol, attribute, fullsymbol) | Suggests a list of completions based on the el_* attributes
of the user_context. | 7.360277 | 7.030066 | 1.046971 |
#We are only interested in the type of the variable immediately preceding our symbol
#in the chain so we can list its members.
chain = fullsymbol.split("%")
#We assume that if symbol != fullsymbol, we have at least a % at the end that
#tricked the symbol regex.
... | def _get_chain_parent_symbol(self, symbol, fullsymbol) | Gets the code element object for the parent of the specified
symbol in the fullsymbol chain. | 7.287843 | 7.103297 | 1.02598 |
target, targmod = self._get_chain_parent_symbol(symbol, fullsymbol)
if target is None:
return {}
result = {}
#We might know what kind of symbol to limit the completion by depending on whether
#it was preceded by a "call " for example. Check the context's el_... | def _complete_type_chain(self, symbol, fullsymbol) | Suggests completion for the end of a type chain. | 3.190518 | 3.144416 | 1.014661 |
#Return a list of valid parameters for the function being called
fncall = self.context.el_name
iexec, execmod = self.context.parser.tree_find(fncall, self.context.module, "executables")
if iexec is None:
#Try the interfaces as a possible executable to complete.
... | def _complete_sig(self, symbol, attribute) | Suggests completion for calling a function or subroutine. | 5.335463 | 4.977631 | 1.071888 |
#The cursor is after a %(,\s and the user is looking for a list
#of possibilities that is a bit smarter that regular AC.
if self.context.el_call in ["sub", "fun", "assign", "arith"]:
if symbol == "":
#The only possibilities are local vars, global vars or func... | def _complete_word(self, symbol, attribute) | Suggests context completions based exclusively on the word
preceding the cursor. | 16.015179 | 14.549989 | 1.1007 |
interface_execs = []
for ikey in module.interfaces:
interface_execs.extend(module.interfaces[ikey].procedures)
return {k: module.executables[k] for k in module.executables if
("{}.{}".format(module.name, k) not in interface_execs and
not m... | def _generic_filter_execs(self, module) | Filters the specified dict of executables to include only those that are not referenced
in a derived type or an interface.
:arg module: the module whose executables should be filtered. | 4.788291 | 4.578471 | 1.045827 |
result = {}
#Also add the subroutines from the module and its dependencies.
moddict = self._generic_filter_execs(self.context.module)
self._cond_update(result, moddict, symbol)
self._cond_update(result, self.context.module.interfaces, symbol)
for depend in self.c... | def _complete_values(self, symbol = "") | Compiles a list of possible symbols that can hold a value in
place. These consist of local vars, global vars, and functions. | 4.837113 | 4.723972 | 1.023951 |
if symbol != "":
added = 0
for key in second:
if self._symbol_in(symbol, key) and (maxadd == -1 or added <= maxadd):
first[key] = second[key]
added += 1
else:
first.update(second) | def _cond_update(self, first, second, symbol, maxadd = -1) | Overwrites the keys and values in the first dictionary with those
of the second as long as the symbol matches part of the key.
:arg maxadd: specifies a limit on the number of entries from the second
dict that will be added to the first. | 3.114291 | 3.321179 | 0.937707 |
attributes = ['dependencies', 'publics', 'members',
'types', 'executables']
#Find the correct attribute based on the type of the context
if self.context.el_type in [Function, Subroutine]:
attribute = attributes[4]
elif self.context.el_type ... | def get_attribute(self) | Gets the appropriate module attribute name for a collection
corresponding to the context's element type. | 7.954106 | 5.782979 | 1.375434 |
result = ""
if "type" in dimension.attrib:
result += "[R" if dimension.attrib["type"] == "row" else "[C"
else:
result += "[C"
if "index" in dimension.attrib:
result += ":" + dimension.attrib["index"]
result += "] " + re.sub("\s+", " "... | def format_dimension(dimension) | Formats the specified <dimension> XML tag for string output. | 3.221631 | 3.043773 | 1.058433 |
#We can only process references if the XML tag has inner-XML
if xml.text is not None:
matches = parser.RE_REFS.finditer(xml.text)
if matches:
for match in matches:
#Handle "special" references to this.name and param.name here.
... | def parse(self, parser, xml) | Parses the rawtext to extract contents and references. | 7.822974 | 7.454293 | 1.049459 |
conf = getattr(settings, 'FILESERVICE_CONFIG', {})
dir = conf.get('store_dir', './fileservice_store')
return os.path.normpath(dir) + os.sep | def get_fileservice_dir() | example settings file
FILESERVICE_CONFIG = {
'store_dir': '/var/lib/geoserver_data/fileservice_store'
} | 4.828483 | 3.17942 | 1.518668 |
args = vars(bparser.parse_known_args()[0])
if args["examples"]:
function()
exit(0)
if args["verbose"]:
from msg import set_verbosity
set_verbosity(args["verbose"])
args.update(vars(parser.parse_known_args()[0]))
return args | def exhandler(function, parser) | If -examples was specified in 'args', the specified function
is called and the application exits.
:arg function: the function that prints the examples.
:arg parser: the initialized instance of the parser that has the
additional, script-specific parameters. | 4.602385 | 5.374597 | 0.856322 |
import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("-examples", action="store_true",
help="See detailed help and examples for this script.")
parser.add_argument("-verbose", action="store_true",
help="See verbose outpu... | def _common_parser() | Returns a parser with common command-line options for all the scripts
in the fortpy suite. | 3.951828 | 3.787183 | 1.043474 |
if not updateParams:
updateParams = {}
policies = self.defaultPolicies
if len(updateParams) > 0:
for k,v in updateParams.items():
k = k.replace('-','_')
c = globals()[k](v)
try:
policies[k] = c.update_policy(self.defaultPolicies[k])
except Exception, e:
raise
return [globals(... | def _getHeaders(self, updateParams=None) | create headers list for flask wrapper | 3.231962 | 3.146779 | 1.02707 |
for k,v in updateParams.items():
k = k.replace('-','_')
c = globals()[k](v)
try:
self.defaultPolicies[k] = getattr(c,func)(self.defaultPolicies[k])
except Exception, e:
raise | def policyChange(self, updateParams, func) | update defaultPolicy dict | 3.865216 | 3.460378 | 1.116992 |
def decorator(f):
_headers = self._getHeaders(updateParams)
@wraps(f)
def decorated_function(*args, **kwargs):
resp = make_response(f(*args, **kwargs))
self._setRespHeader(resp, _headers)
resp.has_secure_headers = True
return resp
return decorated_function
return decorator | def wrapper(self, updateParams=None) | create wrapper for flask app route | 3.18908 | 3.024733 | 1.054334 |
if settings.use_filesystem_cache == False:
return None
try:
pickle_changed_time = self._index[path]
except KeyError:
return None
if (changed_time is not None and
pickle_changed_time < changed_time):
# the pick... | def load_module(self, path, changed_time, parser=None) | Attempts to load the specified module from a serialized, cached
version. If that fails, the method returns none. | 3.816202 | 3.75183 | 1.017158 |
#First, get a list of the module paths that have already been
#pickled. We will add to that list of pickling this module.
if settings.use_filesystem_cache == False:
return
self.__index = None
try:
files = self._index
except KeyError:
... | def save_module(self, path, module, change_time=None) | Saves the specified module and its contents to the file system
so that it doesn't have to be parsed again unless it has changed. | 5.573288 | 5.60661 | 0.994057 |
if self.__index is None:
try:
with open(self._get_path('index.json')) as f:
data = json.load(f)
except (IOError, ValueError):
self.__index = {}
else:
# 0 means version is not defined (= always delete... | def _index(self) | Keys a list of file paths that have been pickled in this directory.
The index is stored in a json file in the same directory as the
pickled objects. | 3.69132 | 3.733315 | 0.988752 |
data = {'version': self.version, 'index': self._index}
with open(self._get_path('index.json'), 'w') as f:
json.dump(data, f)
self.__index = None | def _flush_index(self) | Writes the current list of file paths in the index to the json file
and then sets self.__index = None. | 3.782222 | 2.677563 | 1.412561 |
dir = self._cache_directory()
if not os.path.exists(dir):
os.makedirs(dir)
return os.path.join(dir, file) | def _get_path(self, file) | Creates the cache directory if it doesn't already exist. Returns the
full path to the specified file inside the cache directory. | 2.928312 | 2.314735 | 1.265074 |
if settings.unit_testing_mode or settings.use_test_cache:
return os.path.join(settings.cache_directory.replace("Fortpy", "Fortpy_Testing"), self.py_tag)
else:
return os.path.join(settings.cache_directory, self.py_tag) | def _cache_directory(self) | Returns the full path to the cache directory as specified in settings. | 6.111291 | 5.291743 | 1.154873 |
if '.' not in tag:
raise ValueError('Tag string must be in the format "tag_lib.tag_name"')
lib = tag.rpartition('.')[0]
tag_name = tag.rpartition('.')[-1]
return lib, tag_name | def get_lib_and_tag_name(tag) | Takes a tag string and returns the tag library and tag name. For example,
"app_tags.tag_name" is returned as "app_tags", "tag_name" and
"app_tags.sub.tag_name" is returned as "app_tags.sub", "tag_name" | 3.181522 | 3.237279 | 0.982777 |
tag_data = get_lazy_tag_data(tag_id)
tag = tag_data['tag']
args = tag_data['args']
kwargs = tag_data['kwargs']
lib, tag_name = get_lib_and_tag_name(tag)
args_str = ''
if args:
for arg in args:
if isinstance(arg, six.string_types):
args_str += "'{0}' ... | def get_tag_html(tag_id) | Returns the Django HTML to load the tag library and render the tag.
Args:
tag_id (str): The tag id for the to return the HTML for. | 1.8628 | 1.839073 | 1.012902 |
# on anime list pages, sometimes tds won't be properly opened.
html = re.sub(r'[\s]td class=', "<td class=", html)
# on anime list pages, if the user doesn't specify progress, MAL will try to close a span it didn't open.
def anime_list_closing_span(match):
return match.group(u'count') + '/' + match.group... | def fix_bad_html(html) | Fixes for various DOM errors that MAL commits.
Yes, I know this is a cardinal sin, but there's really no elegant way to fix this. | 4.589742 | 4.545845 | 1.009657 |
try:
if text == u"Unknown" or text == u"?" or text == u"Not available":
return None
if text == u"Now":
return datetime.datetime.now()
seconds_match = re.match(r'(?P<seconds>[0-9]+) second(s)? ago', text)
if seconds_match:
return datetime.datetime.now() - datetime.timedelta(second... | def parse_profile_date(text, suppress=False) | Parses a MAL date on a profile page.
May raise ValueError if a malformed date is found.
If text is "Unknown" or "?" or "Not available" then returns None.
Otherwise, returns a datetime.date object. | 1.433867 | 1.402128 | 1.022636 |
for child in kids:
key = child.tag.lower()
if key != "defaults":
if key not in xmlglobals:
xmlglobals[key] = {}
if "identifier" in child.attrib:
xmlglobals[key][child.attrib["identifier"]] = child
elif "name" in child.attrib:
... | def _update_globals(kids, xmlglobals) | Updates the specified 'xmlglobals' dictionary with the specific
*and* supported global tag definitions. | 2.112871 | 2.059623 | 1.025853 |
for key, val in xmlglobals.items():
if key != "defaults":
for name, tag in val.items():
_update_from_globals(tag, xmlglobals, None) | def _set_global_defaults(xmlglobals) | Sets the default attributes on tags that were specified in <global>
tags in the XML file. | 6.330544 | 6.413678 | 0.987038 |
if "ignores" in testtag.attrib:
from xml.etree.ElementTree import Element
for varname in re.split("[\s,]+", testtag.attrib["ignores"]):
#For ignored variables, the order does not matter. However,
#if the user included the caret, just remove it.
if varname[0] ... | def _handle_ignores(testtag) | Checks if the specified test tag has attribute "ignores"; if it
does, a <global ignore="true" /> tag is created for each variable
name in the list. | 5.049996 | 4.100734 | 1.231486 |
if atag.tag != "auto":
return
if "names" in atag.attrib:
i = -1
for name in re.split("[\s,]+", atag.attrib["names"]):
if name[0] == '^':
name = name[1::]
insert = True
i += 1
else:
insert = Fals... | def _expand_autotag(atag, container) | Expands the contents of the specified auto tag within its parent container. | 4.062348 | 4.057253 | 1.001256 |
#Regex for grabbing out valid XML tags that represent known docstrings that we can work with.
self.keywords = [ "summary", "usage", "errors", "member", "group", "local",
"comments", "parameter" ]
#Regex for extracting the contents of docstrings minus the !! an... | def setup_regex(self) | Sets up the patterns and regex objects for parsing the docstrings. | 6.292898 | 6.207118 | 1.01382 |
from fortpy.utility import XML
result = {}
if container is None:
#We are working with the code file at the module level. Extract the module
#docstrings and XML and return the dictionary with module names as keys.
for module in self.RE_MODDOCS.finditer... | def parse_docs(self, string, container = None) | Parses the docstrings from the specified string that is the contents of container.
Returns a dictionary with keys as parent.code_element_name and the values
a list of XML elements for corresponding docstrings.
:arg container: the instance of the element who owns the string. | 6.738165 | 6.391691 | 1.054207 |
if group.name in code_el.groups and add:
msg.warn("duplicate group names in code element {}".format(code_el.name))
else:
code_el.groups[group.name] = group
kids = self.to_doc(list(group.xml), group.decorates)
for child in kids:
child.group = ... | def _process_docgroup(self, group, code_el, add=True) | Explodes the group members into a list; adds the group to the
specified code element and updates the group value for each
of the docstring elements in the group.
:arg add: when true, docgroups must be unique in the code element;
otherwise, existing groups are overwritten. | 6.339104 | 5.998299 | 1.056817 |
#Paramdocs has a list of docstrings for summary, usage, parameters, etc.
#check which belong to parameters and associate them, otherwise append
#them to the executable.
for doc in docs:
if doc.doctype == "parameter":
if doc.pointsto is not None and do... | def process_execdocs(self, docs, anexec, key, add=True) | Associates parameter documentation with parameters for the executable
and any remaining docs with the executable itself.
- key: the module.executable identifier for the function or subroutine. | 4.36592 | 4.211469 | 1.036674 |
#Keep track of the changes that took place in the lengths of the
#docstrings that got added/updated on the elements children.
delta = 0
for t in anexec.types:
key = "{}.{}".format(anexec.name, t)
if key in xlist:
docs = self.to_doc(xlist[... | def process_embedded(self, xlist, anexec, add=True) | Processes the specified xml list and executable to link *embedded*
types and executables to their docstrings.
:arg xlist: a list of XML elements returned by parse_docs().
:arg add: when true, docstrings are only appended, never overwritten. | 2.780619 | 2.708144 | 1.026762 |
#Now we need to associate the members with their docstrings
#Some of the members may be buried inside a group tag and
#need to be handled separately.
remainingdocs = []
expandeddocs = []
#Process any groups that are in the doc list.
for doc in do... | def process_memberdocs(self, docs, codeEl, add=True) | Associates member type DocElements with their corresponding members
in the specified code element. The element must have a dictionary of
members already. | 5.400712 | 5.350393 | 1.009405 |
if ((doc.doctype == "member" or doc.doctype == "local") and
doc.pointsto is not None and
doc.pointsto in members):
if add:
members[doc.pointsto].docstring.append(doc)
else:
members[doc.pointsto].overwrite_docs(doc)
... | def _process_docstrings(self, doc, members, add=True) | Adds the docstrings from the list of DocElements to their
respective members.
Returns true if the doc element belonged to a member. | 4.632905 | 4.049873 | 1.143963 |
result = []
for xitem in xmllist:
if xitem.tag != "group":
#The docstring allows a single string to point to multiple
#names in a comma-separated list in the names attribute.
if "name" in list(xitem.keys()):
names =... | def to_doc(self, xmllist, decorates) | Converts the specified xml list to a list of docstring elements. | 4.442982 | 4.41679 | 1.00593 |
#The easiest way to do this is to look at one line at a time and see if it is a docstring
#When we find a group of docstrings that suddenly ends, the next item is the code element
#that they were decorating (which may or may not be pertinent).
from fortpy.utility import XML
... | def _parse_docblocks(self, string, container) | Parses all the docstrings out of the specified string.
Returns a dictionary of docstrings with the key as parent.code_element_name
and the value a list of XML elements that contain docstrings. | 6.245193 | 5.967103 | 1.046604 |
match = self.RE_DECOR.match(line)
if match is not None:
return "{}.{}".format(container.name, match.group("name"))
else:
return container.name | def _parse_docline(self, line, container) | Parses a single line of code following a docblock to see if
it as a valid code element that can be decorated. If so, return
the name of the code element. | 4.378409 | 3.777852 | 1.158968 |
result = {}
from fortpy.utility import XML_fromstring
xmlroot = XML_fromstring(xmlstring, source)
if xmlroot.tag == "fortpy" and "mode" in xmlroot.attrib and \
xmlroot.attrib["mode"] == "docstring":
#First, cycle through the kids to find the <global> tag ... | def parsexml(self, xmlstring, modules, source=None) | Parses the docstrings out of the specified xml file.
:arg source: the path to the file from which the XML string was extracted. | 5.240782 | 5.346807 | 0.980171 |
for kdecor in xmldict:
modname, memname = kdecor.split(".")
if modname in modules:
module = modules[modname]
#We only need to check the members, types and executables
memname = memname.lower()
if memname in module.m... | def _xml_update_modules(self, xmldict, modules) | Updates the docstrings in the specified modules by looking for
docstrings in the xmldict. | 3.697104 | 3.563513 | 1.037488 |
#This keeps track of how many character were added/removed by
#updating the docstrings in xmldict.
delta = 0
for kdecor in xmldict:
if "." in kdecor:
modname, memname = kdecor.split(".")
else:
modname, memname = module.name... | def rt_update_module(self, xmldict, module) | Updates the members, executables and types in the specified module
to have the latest docstring information from the xmldict. | 5.913779 | 5.27346 | 1.121423 |
#see how many characters have to be added/removed from the end
#of the current doc limits.
delta = element.docend - docend
element.docstart = docstart
element.docend = docend
element.start += delta
element.end += delta
return delta | def _rt_update_docindices(self, element, docstart, docend) | Updates the docstart, docend, start and end attributes for the
specified element using the new limits for the docstring. | 6.376696 | 5.390041 | 1.183051 |
self.term.stream.write(self.term.enter_fullscreen)
self.term.stream.write(self.term.hide_cursor) | def enter_fullscreen(self) | Invoke before printing out anything.
This method should be replaced by or merged to blessings package | 4.987679 | 3.98864 | 1.250471 |
self.term.stream.write(self.term.exit_fullscreen)
self.term.stream.write(self.term.normal_cursor) | def exit_fullscreen(self) | Invoke before printing out anything.
This method should be replaced by or merged to blessings package | 5.615638 | 4.478441 | 1.253927 |
if not isinstance(tbl, Table):
logging.error("unable to paint table: invalid object")
return False
self.term.stream.write(self.term.clear)
self.term.stream.write(str(tbl))
return True | def paint(self, tbl) | Paint the table on terminal
Currently only print out basic string format | 5.526715 | 5.062461 | 1.091705 |
#Make sure we have a parser for that key. If we don't, then set
#one up if we know what parameters to use; otherwise return the
#default parser.
if key not in _parsers:
if key == "ssh":
_parsers["ssh"] = CodeParser(True, False)
else:
key = "default"
retu... | def parser(key = "default") | Returns the parser for the given key, (e.g. 'ssh') | 6.60383 | 5.683498 | 1.161931 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.