code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
from os import path
from fortpy import settings
return path.join(settings.cache_directory, "history") | def histpath(self) | Returns the full path to the console history file. | 15.956861 | 10.004521 | 1.594965 |
from sys import exc_info
from traceback import format_exception
e = exc_info()
self.lasterr = '\n'.join(format_exception(e[0], e[1], e[2])) | def _store_lasterr(self) | Stores the information about the last unhandled exception. | 2.652693 | 2.394642 | 1.107762 |
if line == "":
return ""
command = line.split()[0]
if "!" in command:
value = command.split("!")[1]
try:
ihist = int(value)
import readline
if ihist <= readline.get_current_history_length():
... | def precmd(self, line) | Makes sure that the command specified in the line is valid given the current
status of loaded unit tests and analysis group. | 5.04563 | 4.646683 | 1.085856 |
from os import chdir, path
fullpath = path.abspath(path.expanduser(arg))
if path.isdir(fullpath):
chdir(fullpath)
else:
msg.err("'{}' is not a valid directory.".format(arg)) | def do_cd(self, arg) | Imitates the bash shell 'cd' command. | 3.069841 | 2.91949 | 1.051499 |
#We need to save the full paths to the staging directories for the tests that are loaded
#so far; then when the session is restored, we can reparse the results.
from os import path
import json
fullpath = path.expanduser(arg)
data = {
"fonts": self.cur... | def do_fontsave(self, arg) | Saves the session variables to a file so that the same analysis can be continued later. | 8.335251 | 7.365993 | 1.131586 |
branches = []
for pos, scale in enumerate(scales):
angle = -sum(angles)/2 + sum(angles[:pos]) + shift_angle
branches.append([scale, angle])
return branches | def generate_branches(scales=None, angles=None, shift_angle=0) | Generates branches with alternative system.
Args:
scales (tuple/array): Indicating how the branch/es length/es develop/s from age to age.
angles (tuple/array): Holding the branch and shift angle in radians.
shift_angle (float): Holding the rotation angle for all branches.
Returns:
... | 4.527918 | 5.324824 | 0.850341 |
rec = [self.pos[0], self.pos[1]]*2
for age in self.nodes:
for node in age:
# Check max/min for x/y coords
for i in range(2):
if rec[0+i] > node.pos[i]:
rec[0+i] = node.pos[i]
elif rec[2+i... | def get_rectangle(self) | Gets the coordinates of the rectangle, in which the tree can be put.
Returns:
tupel: (x1, y1, x2, y2) | 3.682535 | 3.544249 | 1.039017 |
rec = self.get_rectangle()
return (int(rec[2]-rec[0]), int(rec[3]-rec[1])) | def get_size(self) | Get the size of the tree.
Returns:
tupel: (width, height) | 3.913678 | 4.047936 | 0.966833 |
if age is None:
age = self.age
return self.length * pow(self.branches[pos][0], age) | def get_branch_length(self, age=None, pos=0) | Get the length of a branch.
This method calculates the length of a branch in specific age.
The used formula: length * scale^age.
Args:
age (int): The age, for which you want to know the branch length.
Returns:
float: The length of the branch | 6.016144 | 7.049865 | 0.85337 |
return log(length/self.length, min(self.branches[0][0])) | def get_steps_branch_len(self, length) | Get, how much steps will needed for a given branch length.
Returns:
float: The age the tree must achieve to reach the given branch length. | 21.369848 | 31.601501 | 0.676229 |
if age is None:
age = self.age
return age if self.comp == 1 else int((pow(self.comp, age+1) - 1) / (self.comp - 1)) | def get_node_sum(self, age=None) | Get sum of all branches in the tree.
Returns:
int: The sum of all nodes grown until the age. | 4.98874 | 5.474768 | 0.911224 |
if age is None:
age = self.age
return pow(self.comp, age) | def get_node_age_sum(self, age=None) | Get the sum of branches grown in an specific age.
Returns:
int: The sum of all nodes grown in an age. | 9.443692 | 12.631598 | 0.747624 |
nodes = []
for age, level in enumerate(self.nodes):
nodes.append([])
for node in level:
nodes[age].append(node.get_tuple())
return nodes | def get_nodes(self) | Get the tree nodes as list.
Returns:
list: A 2d-list holding the grown nodes coordinates as tupel for every age.
Example:
[
[(10, 40)],
[(20, 80), (100, 30)],
[(100, 90), (120, 40), ...],
...
... | 4.730334 | 3.669619 | 1.289053 |
branches = []
for age, level in enumerate(self.nodes):
branches.append([])
for n, node in enumerate(level):
if age == 0:
p_node = Node(self.pos[:2])
else:
p_node = self._get_node_parent(age-1, n)
... | def get_branches(self) | Get the tree branches as list.
Returns:
list: A 2d-list holding the grown branches coordinates as tupel for every age.
Example:
[
[(10, 40, 90, 30)],
[(90, 30, 100, 40), (90, 30, 300, 60)],
[(100, 40, 120, 70), (100, 40... | 4.609645 | 4.225377 | 1.090943 |
pos = self.pos
self.pos = (pos[0]+delta[0], pos[1]+delta[1], pos[2]+delta[0], pos[3]+delta[1])
# Move all nodes
for age in self.nodes:
for node in age:
node.move(delta) | def move(self, delta) | Move the tree.
Args:
delta (tupel): The adjustment of the position. | 3.208724 | 3.402108 | 0.943157 |
self.nodes.append([])
for n, node in enumerate(self.nodes[self.age]):
if self.age == 0:
p_node = Node(self.pos[:2])
else:
p_node = self._get_node_parent(self.age-1, n)
angle = node.get_node_angle(p_node)
for i in r... | def grow(self, times=1) | Let the tree grow.
Args:
times (integer): Indicate how many times the tree will grow. | 3.833113 | 3.938673 | 0.973199 |
if canvas.__module__ in SUPPORTED_CANVAS:
drawer = SUPPORTED_CANVAS[canvas.__module__]
drawer(self, canvas, stem_color, leaf_color, thickness, ages).draw() | def draw_on(self, canvas, stem_color, leaf_color, thickness, ages=None) | Draw the tree on a canvas.
Args:
canvas (object): The canvas, you want to draw the tree on. Supported canvases: svgwrite.Drawing and PIL.Image (You can also add your custom libraries.)
stem_color (tupel): Color or gradient for the stem of the tree.
leaf_color (tupel): Color ... | 3.783466 | 4.582505 | 0.825633 |
tot_angle = angle - self.branches[pos][1]
if self.sigma[1] != 0:
tot_angle += gauss(0, self.sigma[1]) * pi
return tot_angle | def __get_total_angle(self, angle, pos) | Get the total angle. | 6.24615 | 5.841054 | 1.069353 |
return self.nodes[age][int(pos / self.comp)] | def _get_node_parent(self, age, pos) | Get the parent node of node, whch is located in tree's node list.
Returns:
object: The parent node. | 15.509326 | 28.945415 | 0.535813 |
# Import models here to avoid circular import fail.
from faq.models import Topic, Question
field_lookups = {}
if model == Topic:
field_lookups['sites__pk'] = settings.SITE_ID
if model == Question:
field_lookups['topic__sites__pk'] = settings.SITE_ID
if status:
... | def _field_lookups(model, status=None) | Abstraction of field lookups for managers.
Returns a dictionary of field lookups for a queryset. The lookups
will always filter by site. Optionally, if ``status`` is passed to
the function the objects will also be filtered by the given status.
This function saves from having to make two different on-s... | 3.403811 | 2.99125 | 1.137923 |
from os import path
from numpy.ctypeslib import load_library
libpath = path.abspath(lib)
libkey = libpath.lower()
if libkey not in compilers:
compilers[libkey] = detect_compiler(libpath)
if compilers[libkey] == False:
raise ValueError("Couldn't auto-detect the compi... | def static_symbol(module, method, lib, bindc=False) | Returns the symbol for the specified *fortran* module and subroutine/function
that has been compiled into a shared library.
:arg lib: the full path to the shared library *.so file. | 3.918677 | 3.87501 | 1.011269 |
from os import waitpid, path
from subprocess import Popen, PIPE
command = "nm {0}".format(path.abspath(libpath))
child = Popen(command, shell=True, executable="/bin/bash", stdout=PIPE)
# Need to do this so that we are sure the process is done before moving on
waitpid(child.pid, 0)
conte... | def detect_compiler(libpath) | Determines the compiler used to compile the specified shared library by
using the system utilities.
:arg libpath: the full path to the shared library *.so file. | 4.083733 | 4.18828 | 0.975038 |
if not self.deallocated:
#Release/deallocate the pointer in fortran.
method = self._deallocator()
if method is not None:
dealloc = static_symbol("ftypes_dealloc", method, self.libpath, True)
if dealloc is None:
retu... | def clean(self) | Deallocates the fortran-managed memory that this ctype references. | 6.847996 | 5.955531 | 1.149855 |
lookup = {
"c_bool": "logical",
"c_double": "double",
"c_double_complex": "complex",
"c_char": "char",
"c_int": "int",
"c_float": "float",
"c_short": "short",
"c_long": "long"
}
c... | def _deallocator(self) | Returns the name of the subroutine in ftypes_dealloc.f90 that can
deallocate the array for this Ftype's pointer.
:arg ctype: the string c-type of the variable. | 3.656111 | 3.513018 | 1.040732 |
#First we *copy* the arrays that we currently have pointers to. This is not
#the optimal solution; however, because of limitations in ctypes, we don't
#know anything better at the moment.
for key in self.result:
self.result[key] = self.result[key].copy()
#No... | def cleanup(self) | Cleans up this result so that all its pointers reference memory controlled
*outside* of the shared library loaded with ctypes. | 11.829906 | 9.628199 | 1.228673 |
self.result[varname] = result
setattr(self, varname, result)
if pointer is not None:
self._finalizers[varname] = pointer | def add(self, varname, result, pointer=None) | Adds the specified python-typed result and an optional Ftype pointer
to use when cleaning up this object.
:arg result: a python-typed representation of the result.
:arg pointer: an instance of Ftype with pointer information for deallocating
the c-pointer. | 3.780679 | 4.448181 | 0.849938 |
row_info = {}
try:
start = utilities.parse_profile_date(soup.find('series_start').text)
except ValueError:
start = None
except:
if not self.session.suppress_parse_exceptions:
raise
if start is not None:
try:
row_info['aired'] = (start, utilities.parse_p... | def parse_entry_media_attributes(self, soup) | Args:
soup: a bs4 element containing a row from the current media list
Return a dict of attributes of the media the row is about. | 2.624254 | 2.589232 | 1.013526 |
# parse the media object first.
media_attrs = self.parse_entry_media_attributes(soup)
media_id = media_attrs[u'id']
del media_attrs[u'id']
media = getattr(self.session, self.type)(media_id).set(media_attrs)
entry_info = {}
try:
entry_info[u'started'] = utilities.parse_profile_dat... | def parse_entry(self, soup) | Given:
soup: a bs4 element containing a row from the current media list
Return a tuple:
(media object, dict of this row's parseable attributes) | 2.297007 | 2.219024 | 1.035143 |
stats = {}
for row in soup.children:
try:
key = row.name.replace(u'user_', u'')
if key == u'id':
stats[key] = int(row.text)
elif key == u'name':
stats[key] = row.text
elif key == self.verb + u'ing':
try:
stats[key] = int(row.te... | def parse_stats(self, soup) | Given:
soup: a bs4 element containing the current media list's stats
Return a dict of this media list's stats. | 2.7149 | 2.642712 | 1.027316 |
logger = getLoggerWithNullHandler('commando.load_python_object')
(module_name, _, object_name) = name.rpartition(".")
if module_name == '':
(module_name, object_name) = (object_name, module_name)
try:
logger.debug('Loading module [%s]' % module_name)
module = __import__(modu... | def load_python_object(name) | Loads a python module from string | 2.59482 | 2.605782 | 0.995793 |
logger = logging.getLogger(logger_name)
logger.setLevel(logging.INFO)
if not logger.handlers:
handler = logging.StreamHandler(sys.stdout)
if sys.platform == 'win32':
formatter = logging.Formatter(
fmt="%(asctime)s %(name)s %(message)s",
... | def getLoggerWithConsoleHandler(logger_name=None) | Gets a logger object with a pre-initialized console handler. | 2.261967 | 2.264201 | 0.999013 |
logger = logging.getLogger(logger_name)
if not logger.handlers:
logger.addHandler(NullHandler())
return logger | def getLoggerWithNullHandler(logger_name) | Gets the logger initialized with the `logger_name`
and a NullHandler. | 2.036561 | 2.203148 | 0.924387 |
args, kwargs = self.__process__(*args, **kwargs)
return check_call(args, **kwargs) | def call(self, *args, **kwargs) | Delegates to `subprocess.check_call`. | 8.724614 | 4.919289 | 1.773552 |
args, kwargs = self.__process__(*args, **kwargs)
return check_output(args, **kwargs) | def get(self, *args, **kwargs) | Delegates to `subprocess.check_output`. | 8.87701 | 4.630292 | 1.91716 |
args, kwargs = self.__process__(*args, **kwargs)
return Popen(args, **kwargs) | def open(self, *args, **kwargs) | Delegates to `subprocess.Popen`. | 7.910472 | 5.147858 | 1.536653 |
html = get_tag_html(tag_id)
t = template.Template(html)
c = template.RequestContext(request)
return HttpResponse(t.render(c)) | def tag(request, tag_id=None) | The view used to render a tag after the page has loaded. | 3.522954 | 3.176606 | 1.109031 |
if age == self.tree.age:
return self.leaf_color
color = self.stem_color
tree = self.tree
if len(color) == 3:
return color
diff = [color[i+3]-color[i] for i in range(3)]
per_age = [diff[i]/(tree.age-1) for i in range(3)]
return t... | def _get_color(self, age) | Get the fill color depending on age.
Args:
age (int): The age of the branch/es
Returns:
tuple: (r, g, b) | 3.677794 | 3.854663 | 0.954115 |
for age, level in enumerate(self.tree.get_branches()):
if age in self.ages:
thickness = self._get_thickness(age)
color = self._get_color(age)
for branch in level:
self._draw_branch(branch, color, thickness, age) | def draw(self) | Draws the tree.
Args:
ages (array): Contains the ages you want to draw. | 5.04526 | 4.267515 | 1.182248 |
assert self._message, "need to supply a message for the \"create\" command"
if not self._revisions:
self._revisions.append("1")
# get the migration folder
rev_folder = self._revisions[-1]
full_rev_path = os.path.join(self._migration_path, rev_folder)
... | def _cmd_create(self) | Create a migration in the current or new revision folder | 2.790598 | 2.666414 | 1.046573 |
revision = self._get_revision()
if not self._rev:
self._log(0, "upgrading current revision")
else:
self._log(0, "upgrading from revision %s" % revision)
for rev in self._revisions[int(revision) - 1:]:
sql_files = glob.glob(os.path.join(self._m... | def _cmd_up(self) | Upgrade to a revision | 4.357928 | 4.035023 | 1.080025 |
revision = self._get_revision()
if not self._rev:
self._log(0, "downgrading current revision")
else:
self._log(0, "downgrading to revision %s" % revision)
# execute from latest to oldest revision
for rev in reversed(self._revisions[int(revision) -... | def _cmd_down(self) | Downgrade to a revision | 4.469977 | 4.124095 | 1.083869 |
assert self._revisions, "no migration revision exist"
revision = self._rev or self._revisions[-1]
# revision count must be less or equal since revisions are ordered
assert revision in self._revisions, "invalid revision specified"
return revision | def _get_revision(self) | Validate and return the revision to use for current command | 12.481277 | 11.311979 | 1.103368 |
media_type = cls.__name__.lower()
p = session.session.get(u'http://myanimelist.net/' + media_type + '.php?o=9&c[]=a&c[]=d&cv=2&w=1').text
soup = utilities.get_clean_dom(p)
latest_entry = soup.find(u"div", {u"class": u"hoverinfo"})
if not latest_entry:
raise MalformedMediaPageError(0, p, u... | def newest(cls, session) | Fetches the latest media added to MAL.
:type session: :class:`myanimelist.session.Session`
:param session: A valid MAL session
:rtype: :class:`.Media`
:return: the newest media on MAL
:raises: :class:`.MalformedMediaPageError` | 6.818483 | 5.974288 | 1.141305 |
media_info = self.parse_sidebar(media_page)
try:
synopsis_elt = media_page.find(u'h2', text=u'Synopsis').parent
utilities.extract_tags(synopsis_elt.find_all(u'h2'))
media_info[u'synopsis'] = synopsis_elt.text.strip()
except:
if not self.session.suppress_parse_exceptions:
... | def parse(self, media_page) | Parses the DOM and returns media attributes in the main-content area.
:type media_page: :class:`bs4.BeautifulSoup`
:param media_page: MAL media page's DOM
:rtype: dict
:return: media attributes. | 3.18278 | 3.227163 | 0.986247 |
media_info = self.parse_sidebar(media_page)
verb_progressive = self.consuming_verb + u'ing'
status_stats = {
verb_progressive: 0,
'completed': 0,
'on_hold': 0,
'dropped': 0,
'plan_to_' + self.consuming_verb: 0
}
try:
consuming_elt = media_page.find(u'span', {... | def parse_stats(self, media_page) | Parses the DOM and returns media statistics attributes.
:type media_page: :class:`bs4.BeautifulSoup`
:param media_page: MAL media stats page's DOM
:rtype: dict
:return: media stats attributes. | 1.760062 | 1.783347 | 0.986943 |
media_info = self.parse_sidebar(character_page)
try:
character_title = filter(lambda x: u'Characters' in x.text, character_page.find_all(u'h2'))
media_info[u'characters'] = {}
if character_title:
character_title = character_title[0]
curr_elt = character_title.find_next_si... | def parse_characters(self, character_page) | Parses the DOM and returns media character attributes in the sidebar.
:type character_page: :class:`bs4.BeautifulSoup`
:param character_page: MAL character page's DOM
:rtype: dict
:return: character attributes. | 3.372203 | 3.313923 | 1.017587 |
media_page = self.session.session.get(u'http://myanimelist.net/' + self.__class__.__name__.lower() + u'/' + str(self.id)).text
self.set(self.parse(utilities.get_clean_dom(media_page)))
return self | def load(self) | Fetches the MAL media page and sets the current media's attributes.
:rtype: :class:`.Media`
:return: current media object. | 6.671135 | 5.293528 | 1.260244 |
stats_page = self.session.session.get(u'http://myanimelist.net/' + self.__class__.__name__.lower() + u'/' + str(self.id) + u'/' + utilities.urlencode(self.title) + u'/stats').text
self.set(self.parse_stats(utilities.get_clean_dom(stats_page)))
return self | def load_stats(self) | Fetches the MAL media statistics page and sets the current media's statistics attributes.
:rtype: :class:`.Media`
:return: current media object. | 5.624256 | 4.876266 | 1.153394 |
characters_page = self.session.session.get(u'http://myanimelist.net/' + self.__class__.__name__.lower() + u'/' + str(self.id) + u'/' + utilities.urlencode(self.title) + u'/characters').text
self.set(self.parse_characters(utilities.get_clean_dom(characters_page)))
return self | def load_characters(self) | Fetches the MAL media characters page and sets the current media's character attributes.
:rtype: :class:`.Media`
:return: current media object. | 5.590459 | 4.945054 | 1.130515 |
fortdir = os.path.dirname(fortpy.__file__)
xmlpath = os.path.join(fortdir, "isense", "builtin.xml")
if not os.path.isfile(xmlpath):
return {}
changed_time = os.path.getmtime(xmlpath)
cached = serializer.load_module("builtin.xml", changed_time)
if cached is None:
result = _l... | def load(parser, serializer) | Returns a dictionary of builtin functions for Fortran. Checks the
cache first to see if we have a serialized version. If we don't, it
loads it from the XML file.
:arg parser: the DocParser instance for parsing the XML tags.
:arg serializer: a Serializer instance from the CodeParser to cache
the l... | 3.737018 | 3.438636 | 1.086773 |
if "builtin" in config.isense and "uppercase" in config.isense["builtin"]:
if config.isense["builtin"]["uppercase"] == "true":
return symbol.upper()
else:
return symbol.lower()
else:
#Make it lowercase by default
return symbol.lower() | def _isense_builtin_symbol(symbol) | Returns the symbol with modifications according to settings in the
<isense> configuration section. | 4.262106 | 3.373969 | 1.263232 |
#First we need to get hold of the fortpy directory so we can locate
#the isense/builtin.xml file.
result = {}
el = ET.parse(xmlpath).getroot()
if el.tag == "builtin":
for child in el:
anexec = _parse_xml(child, parser)
result[anexec.name.lower()] = anexec
r... | def _load_builtin_xml(xmlpath, parser) | Loads the builtin function specifications from the builtin.xml file.
:arg parser: the DocParser instance for parsing the XML tags. | 8.640398 | 8.638184 | 1.000256 |
name, modifiers, dtype, kind = _parse_common(child)
#Handle the symbol modification according to the isense settings.
name = _isense_builtin_symbol(name)
if child.tag == "subroutine":
parent = Subroutine(name, modifiers, None)
elif child.tag == "function":
parent = Function(na... | def _parse_xml(child, parser) | Parses the specified child XML tag and creates a Subroutine or
Function object out of it. | 4.407906 | 3.91514 | 1.125862 |
summary = DocElement(tag, parser, parent)
parent.docstring.append(summary) | def _parse_summary(tag, parser, parent) | Parses a <summary> tag and adds it the Executable parent instance.
:arg parser: an instance of DocParser to create the DocElement with. | 12.224948 | 13.100179 | 0.933189 |
usage = DocElement(tag, parser, parent)
parent.docstring.append(usage) | def _parse_usage(tag, parser, parent) | Parses a <usage> tag and adds it the Executable parent instance.
:arg parser: an instance of DocParser to create the DocElement with. | 12.484668 | 11.187113 | 1.115987 |
name, modifiers, dtype, kind = _parse_common(tag)
if "default" in tag.attrib:
default = tag.attrib["default"]
else:
default = None
if "dimension" in tag.attrib:
dimension = tag.attrib["dimension"]
else:
dimension = None
result = ValueElement(name, modifiers,... | def _parse_parameter(tag, parser, parent) | Creates a ValueElement instance from the specified <parameter> XML tag. | 3.881088 | 3.230494 | 1.201391 |
if "modifiers" in tag.attrib:
modifiers = re.split(",\s*", tag.attrib["modifiers"].strip())
if "" in modifiers:
modifiers.remove("")
else:
modifiers = None
if "name" in tag.attrib:
name = tag.attrib["name"]
if "type" in tag.attrib:
dtype = tag.at... | def _parse_common(tag) | Returns a tuple of (name, modifiers, dtype, kind)
for the specified tag. Any missing attributes will have values of None. | 2.293438 | 1.861459 | 1.232064 |
tag_id = get_tag_id()
set_lazy_tag_data(tag_id, tag, args, kwargs)
return render_to_string('lazy_tags/lazy_tag.html', {
'tag_id': tag_id,
'STATIC_URL': settings.STATIC_URL,
}) | def lazy_tag(tag, *args, **kwargs) | Lazily loads a template tag after the page has loaded. Requires jQuery
(for now).
Usage:
{% load lazy_tags %}
{% lazy_tag 'tag_lib.tag_name' arg1 arg2 kw1='test' kw2='hello' %}
Args:
tag (str): the tag library and tag name separated by a period. For a
template tag name... | 3.127285 | 4.02794 | 0.776398 |
req = urllib2.Request(url + urllib.urlencode(params))
if auth:
req.add_header('AUTHORIZATION', 'Basic ' + auth)
return urllib2.urlopen(req) | def make_request(self, url, params, auth=None) | Prepares a request from a url, params, and optionally authentication. | 2.880213 | 2.889467 | 0.996798 |
allsubs = []
xnames = []
drange = list(range(8)) if suffix is None else list(range(1,8))
for D in drange:
xname, sub = fpy(D, dtype, kind, suffix)
xnames.append(xname)
allsubs.append(sub)
return (xnames, '\n'.join(allsubs)) | def fpy_interface_sub(fpy, dtype, kind, suffix=None) | Generates the interface for reading/writing values for variables of the specified suffix
for dimensions 0 through 7.
:arg fpy: the generating function that accepts the dimension and type information
and returns the (xnames, subtext).
:arg suffix: one of [None, "_f", "_p"] corresponding to "allocatabl... | 4.031656 | 3.979305 | 1.013156 |
modprocs = []
subtext = []
for dtype, combos in list(typedict.items()):
for tcombo in combos:
kind, suffix = tcombo
xnames, sub = fpy_interface_sub(fpy, dtype, kind, suffix)
modprocs.extend(xnames)
subtext.append(sub)
subtext.append("\n")
... | def fpy_interface(fpy, static, interface, typedict) | Splices the full list of subroutines and the module procedure list
into the static.f90 file.
:arg static: the string contents of the static.f90 file.
:arg interface: the name of the interface *field* being replaced.
:arg typedict: the dictionary of dtypes and their kind and suffix combos. | 9.915308 | 8.163905 | 1.21453 |
if not args["reparse"]:
settings.use_filesystem_cache = False
c = CodeParser()
if args["verbose"]:
c.verbose = True
if args["reparse"]:
c.reparse(args["source"])
else:
c.parse(args["source"])
return c | def _parse() | Parses the specified Fortran source file from which the wrappers will
be constructed for ctypes. | 5.617672 | 5.498498 | 1.021674 |
cparser = _parse()
dependencies = ["{}_c".format(m) for m in cparser.modules]
originals = list(cparser.modules.keys())
writers = {}
for modname, module in list(cparser.modules.items()):
msg.info("Writing wrapper module for {}".format(modname))
fwriter = f90.WrapperModule(module,... | def writef90() | Writes the F90 module file from the specified code parser for *all* the modules
inside of it. | 4.723081 | 4.502981 | 1.048879 |
#Regex for extracting modules from the code
self._RX_MODULE = r"(\n|^)\s*module\s+(?P<name>[a-z0-9_]+)(?P<contents>.+?)end\s*module"
self.RE_MODULE = re.compile(self._RX_MODULE, re.I | re.DOTALL)
self._RX_PROGRAM = r"(\n|^)\s*program\s+(?P<name>[a-z0-9_]+)(?P<contents>.+?)end\s*... | def setup_regex(self) | Sets up compiled regex objects for parsing code elements. | 3.184653 | 3.122557 | 1.019886 |
#First find out if we are passed the CONTAINS section separating executables from
#the type and member definitions. In order for this code to be reached, the lines
#that are being changed are *between* definitions that already exist. The likelihood
#is that they are *new* defini... | def rt_update(self, statement, element, mode, linenum, lineparser) | Performs a real-time update of the specified statement that is in the body of the
module.
:arg statement: the lines of code that was added/removed/changed on the
element after it had alread been parsed. The lines together form a single
continuous code statement.
:ar... | 9.136251 | 9.218217 | 0.991108 |
#This is the same deal as with _rt_parse_types() below.
if mode == "insert":
enew, start, end = self.xparser.parse_signature(statement, element, element)
if enew is not None:
enew.start, enew.end = lineparser.absolute_charindex(statement, start, end)
... | def _rt_parse_execs(self, statement, element, mode, lineparser) | As part of parse_line(), checks for new executable declarations in the statement. | 7.210674 | 6.624211 | 1.088533 |
if mode == "insert":
#Since we got to this point, there is *no* code element that owns the current
#line which is being replaced; we are merely checking to see if the new line
#being entered matches a type definition, do the same thing as "insert"
tnew, s... | def _rt_parse_types(self, statement, element, mode, lineparser) | As part of parse_line(), checks for new type declarations in the statement. | 10.17979 | 9.745709 | 1.044541 |
if module:
result = self._parse_modules(string, parent, filepath)
else:
result = self._parse_programs(string, parent, filepath)
return result | def parse(self, string, parent, module=True, filepath=None) | Extracts modules *and* programs from a fortran code file.
:arg string: the contents of the fortran code file.
:arg parent: the instance of CodeParser that will own the return Module.
:arg module: when true, the code file will be searched for modules; otherwise
it will be searched for ... | 2.835315 | 3.140881 | 0.902713 |
#First, get hold of the docstrings for all the modules so that we can
#attach them as we parse them.
moddocs = self.docparser.parse_docs(string)
#Now look for modules in the file and then match them to their decorators.
matches = self.RE_PROGRAM.finditer(string)
... | def _parse_programs(self, string, parent, filepath=None) | Extracts a PROGRAM from the specified fortran code file. | 6.484355 | 6.367648 | 1.018328 |
matches = self.RE_PUBLIC.finditer(contents)
result = {}
start = 0
for public in matches:
methods = public.group("methods")
#We need to keep track of where the public declarations start so that the unit
#testing framework can insert public stat... | def _process_publics(self, contents) | Extracts a list of public members, types and executables that were declared using
the public keyword instead of a decoration. | 8.095792 | 7.716116 | 1.049206 |
#First, get hold of the name and contents of the module so that we can process the other
#parts of the module.
modifiers = []
#We need to check for the private keyword before any type or contains declarations
if self.RE_PRIV.search(contents):
modifiers.appen... | def _process_module(self, name, contents, parent, match, filepath=None) | Processes a regex match for a module to create a CodeElement. | 6.563566 | 6.216167 | 1.055886 |
result = {}
for ruse in self.RE_USE.finditer(string):
#We also handle comments for individual use cases, the "only" section
#won't pick up any comments.
name = ruse.group("name").split("!")[0].strip()
if name.lower() == "mpi":
cont... | def _parse_use(self, string) | Extracts use dependencies from the innertext of a module. | 5.458201 | 5.088912 | 1.072567 |
if key in dictionary:
dictionary[key] += 1
else:
dictionary[key] = 1 | def _dict_increment(self, dictionary, key) | Increments the value of the dictionary at the specified key. | 2.342006 | 1.99625 | 1.173203 |
#We need to get hold of the text before the module's main CONTAINS keyword
#so that we don't find variables from executables and claim them as
#belonging to the module.
icontains = module.contains_index
ichar = module.charindex(icontains, 0)
module.preamble = mod... | def _parse_members(self, contents, module) | Extracts any module-level members from the code. They must appear before
any type declalations. | 7.137555 | 6.953053 | 1.026535 |
self._RX_CONTAINS = r"^\s*contains[^\n]*?$"
self.RE_CONTAINS = re.compile(self._RX_CONTAINS, re.M | re.I)
#Setup a regex that can extract information about both functions and subroutines
self._RX_EXEC = r"\n[ \t]*((?P<type>character|real|type|logical|integer|complex)?" + \
... | def setup_regex(self) | Sets up compiled regex objects for parsing the executables from a module. | 3.758352 | 3.672531 | 1.023368 |
#If the signature changes, the user might not have had a chance to add the
#detailed member information for it yet. Here
#we will just update the modifiers and attributes. Also, since all the mods
#etc. will be overwritten, we don't need to handle replace separately.
sma... | def parse_signature(self, statement, element, module=None) | Parses the specified line as a new version of the signature for 'element'.
:arg statement: the string that has the new signature.
:arg element: the code element whose signature will be changed. | 5.744533 | 5.846959 | 0.982482 |
if element.incomplete:
#We need to check for the end_token so we can close up the incomplete
#status for the instance.
if element.end_token in statement:
element.incomplete = False
return
#The line can either be related to an ... | def parse_line(self, statement, element, mode) | Parses the contents of the specified line and adds its representation
to the specified element (if applicable).
:arg statement: the lines of code that was added/removed/changed on the
element after it had alread been parsed. The lines together form a single
continuous code statemen... | 11.676663 | 11.763182 | 0.992645 |
#Because of embedded types, we have to examine the entire module for
#executable definitions.
self.parse_block(module.refstring, module, module, 0)
#Now we can set the value of module.contains as the text after the start of
#the *first* non-embedded executable.
... | def parse(self, module) | Extracts all the subroutine and function definitions from the specified module. | 6.805134 | 6.6145 | 1.028821 |
for anexec in self.RE_EXEC.finditer(contents):
x = self._process_execs(anexec, parent, module)
parent.executables[x.name.lower()] = x
if isinstance(parent, Module) and "public" in x.modifiers:
parent.publics[x.name.lower()] = 1
... | def parse_block(self, contents, parent, module, depth) | Extracts all executable definitions from the specified string and adds
them to the specified parent. | 5.669935 | 5.505947 | 1.029784 |
#Get the matches that must be present for every executable.
name = execmatch.group("name").strip()
modifiers = execmatch.group("modifiers")
if modifiers is None:
modifiers = []
else:
modifiers = re.split(",[ \t]*", modifiers)
codetype = ex... | def _process_execs(self, execmatch, parent, module) | Processes the regex match of an executable from the match object. | 5.319988 | 5.220519 | 1.019053 |
for assign in self.RE_ASSIGN.finditer(contents):
assignee = assign.group("assignee").strip()
target = re.split(r"[(%\s]", assignee)[0].lower()
#We only want to include variables that we know are in the scope of the
#current executable. This excludes func... | def _process_assignments(self, anexec, contents, mode="insert") | Extracts all variable assignments from the body of the executable.
:arg mode: for real-time update; either 'insert', 'delete' or 'replace'. | 5.714338 | 5.895146 | 0.969329 |
#At this point we don't necessarily know which module the executables are
#in, so we just extract the names. Once all the modules in the library
#have been parsed, we can do the associations at that level for linking.
for dmatch in self.RE_DEPEND.finditer(contents):
... | def _process_dependencies(self, anexec, contents, mode="insert") | Extracts a list of subroutines and functions that are called from
within this executable.
:arg mode: specifies whether the matches should be added, removed
or merged into the specified executable. | 9.493067 | 9.540403 | 0.995038 |
#First remove the escaped quotes, we will add them back at the end.
unquoted = text.replace('""', "_FORTPYDQ_").replace("''", "_FORTPYSQ_")
for cmatch in self.RE_CONST.finditer(unquoted):
string = cmatch.string[cmatch.start():cmatch.end()]
newstr = string.replace... | def _depend_exec_clean(self, text) | Cleans any string constants in the specified dependency text to remove
embedded ! etc. that break the parsing. | 4.726731 | 4.318191 | 1.094609 |
for i in range(len(dependlist)):
#Since we are looping over all the elements and some will
#be lists of parameters, we need to skip any items that are lists.
if isinstance(dependlist[i], list):
continue
key = dependlist[i].lower()
... | def _process_dependlist(self, dependlist, anexec, isSubroutine, mode="insert") | Processes a list of nested dependencies recursively. | 4.96841 | 4.856269 | 1.023092 |
if dependlist[i] in anexec.dependencies:
all_depends = anexec.dependencies[dependlist[i]]
if len(all_depends) > 0:
clean_args = all_depends[0].clean(dependlist[i + 1])
for idepend in range(len(all_depends)):
#Make sure we match... | def _remove_dependency(self, dependlist, i, isSubroutine, anexec) | Removes the specified dependency from the executable if it exists
and matches the call signature. | 4.654195 | 4.18182 | 1.112959 |
#First determine if the reference is to a derived type variable
lkey = key.lower()
if "%" in key:
#Find the type of the base variable and then perform a tree
#search at the module level to determine if the final reference
#is a valid executable
... | def _add_dependency(self, key, dependlist, i, isSubroutine, anexec) | Determines whether the item in the dependency list is a valid function
call by excluding local variables and members. | 5.576867 | 5.438437 | 1.025454 |
#The documentation for the parameters is stored outside of the executable
#We need to get hold of them from docblocks from the parent text
key = "{}.{}".format(parent.name, anexec.name)
if key in docblocks:
docs = self.docparser.to_doc(docblocks[key][0], anexec.name)... | def _process_docs(self, anexec, docblocks, parent, module, docsearch) | Associates the docstrings from the docblocks with their parameters. | 6.423436 | 6.017514 | 1.067457 |
#First get the variables declared in the body of the executable, these can
#be either locals or parameter declarations.
members = self.vparser.parse(contents, anexec)
#If the name matches one in the parameter list, we can connect them
for param in list(params):
... | def _parse_members(self, contents, anexec, params, mode="insert") | Parses the local variables for the contents of the specified executable. | 4.301297 | 4.13815 | 1.039425 |
character_info = {}
error_tag = character_page.find(u'div', {'class': 'badresult'})
if error_tag:
# MAL says the character does not exist.
raise InvalidCharacterError(self.id)
try:
full_name_tag = character_page.find(u'div', {'id': 'contentWrapper'}).find(u'h1')
if not ful... | def parse_sidebar(self, character_page) | Parses the DOM and returns character attributes in the sidebar.
:type character_page: :class:`bs4.BeautifulSoup`
:param character_page: MAL character page's DOM
:rtype: dict
:return: Character attributes
:raises: :class:`.InvalidCharacterError`, :class:`.MalformedCharacterPageError` | 2.054168 | 2.018482 | 1.01768 |
character_info = self.parse_sidebar(character_page)
second_col = character_page.find(u'div', {'id': 'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1]
name_elt = second_col.find(u'div', {'class': 'normal_header'})
try:
name_jpn_node = name_elt.find(u'small')
if... | def parse(self, character_page) | Parses the DOM and returns character attributes in the main-content area.
:type character_page: :class:`bs4.BeautifulSoup`
:param character_page: MAL character page's DOM
:rtype: dict
:return: Character attributes. | 2.683752 | 2.698614 | 0.994493 |
character_info = self.parse_sidebar(favorites_page)
second_col = favorites_page.find(u'div', {'id': 'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1]
try:
character_info[u'favorites'] = []
favorite_links = second_col.find_all('a', recursive=False)
for link in... | def parse_favorites(self, favorites_page) | Parses the DOM and returns character favorites attributes.
:type favorites_page: :class:`bs4.BeautifulSoup`
:param favorites_page: MAL character favorites page's DOM
:rtype: dict
:return: Character favorites attributes. | 4.681539 | 4.815143 | 0.972253 |
character_info = self.parse_sidebar(picture_page)
second_col = picture_page.find(u'div', {'id': 'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1]
try:
picture_table = second_col.find(u'table', recursive=False)
character_info[u'pictures'] = []
if picture_table... | def parse_pictures(self, picture_page) | Parses the DOM and returns character pictures attributes.
:type picture_page: :class:`bs4.BeautifulSoup`
:param picture_page: MAL character pictures page's DOM
:rtype: dict
:return: character pictures attributes. | 3.45937 | 3.538145 | 0.977735 |
character_info = self.parse_sidebar(clubs_page)
second_col = clubs_page.find(u'div', {'id': 'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1]
try:
clubs_header = second_col.find(u'div', text=u'Related Clubs')
character_info[u'clubs'] = []
if clubs_header:
... | def parse_clubs(self, clubs_page) | Parses the DOM and returns character clubs attributes.
:type clubs_page: :class:`bs4.BeautifulSoup`
:param clubs_page: MAL character clubs page's DOM
:rtype: dict
:return: character clubs attributes. | 2.882814 | 2.929427 | 0.984088 |
character = self.session.session.get(u'http://myanimelist.net/character/' + str(self.id)).text
self.set(self.parse(utilities.get_clean_dom(character)))
return self | def load(self) | Fetches the MAL character page and sets the current character's attributes.
:rtype: :class:`.Character`
:return: Current character object. | 8.665375 | 7.261126 | 1.193393 |
character = self.session.session.get(u'http://myanimelist.net/character/' + str(self.id) + u'/' + utilities.urlencode(self.name) + u'/favorites').text
self.set(self.parse_favorites(utilities.get_clean_dom(character)))
return self | def load_favorites(self) | Fetches the MAL character favorites page and sets the current character's favorites attributes.
:rtype: :class:`.Character`
:return: Current character object. | 6.415346 | 5.422614 | 1.183073 |
character = self.session.session.get(u'http://myanimelist.net/character/' + str(self.id) + u'/' + utilities.urlencode(self.name) + u'/pictures').text
self.set(self.parse_pictures(utilities.get_clean_dom(character)))
return self | def load_pictures(self) | Fetches the MAL character pictures page and sets the current character's pictures attributes.
:rtype: :class:`.Character`
:return: Current character object. | 7.006649 | 5.732788 | 1.222206 |
character = self.session.session.get(u'http://myanimelist.net/character/' + str(self.id) + u'/' + utilities.urlencode(self.name) + u'/clubs').text
self.set(self.parse_clubs(utilities.get_clean_dom(character)))
return self | def load_clubs(self) | Fetches the MAL character clubs page and sets the current character's clubs attributes.
:rtype: :class:`.Character`
:return: Current character object. | 6.211997 | 5.265709 | 1.179708 |
if minlen < 1 or maxlen < minlen:
raise ValueError()
for cur in range(minlen, maxlen + 1):
# string product generator
str_generator = product(self.charset, repeat=cur)
for each in str_generator:
# yield the produced word
... | def generate(self, minlen, maxlen) | Generates words of different length without storing
them into memory, enforced by itertools.product | 6.265098 | 5.556831 | 1.127459 |
curlen = utils.get_pattern_length(pattern)
if curlen > 0:
str_generator = product(self.charset, repeat=curlen)
pattern = pattern + self.delimiter
fstring = utils.pattern_to_fstring(pattern)
for each in str_generator:
yield fstring... | def generate_with_pattern(self, pattern=None) | Algorithm that creates the list
based on a given pattern
The pattern must be like string format patter:
e.g: a@b will match an 'a' follow by any character follow by a 'b' | 6.296239 | 6.305779 | 0.998487 |
comments_page = session.session.get(u'http://myanimelist.net/comments.php?' + urllib.urlencode({'id': int(user_id)})).text
comments_page = bs4.BeautifulSoup(comments_page)
username_elt = comments_page.find('h1')
if "'s Comments" not in username_elt.text:
raise InvalidUserError(user_id, messag... | def find_username_from_user_id(session, user_id) | Look up a MAL username's user ID.
:type session: :class:`myanimelist.session.Session`
:param session: A valid MAL session.
:type user_id: int
:param user_id: The user ID for which we want to look up a username.
:raises: :class:`.InvalidUserError`
:rtype: str
:return: The given user's use... | 4.969263 | 4.387078 | 1.132705 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.