code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
user_info = self.parse_sidebar(reviews_page)
second_col = reviews_page.find(u'div', {u'id': u'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1]
try:
user_info[u'reviews'] = {}
reviews = second_col.find_all(u'div', {u'class': u'borderDark'}, recursive=False)
if... | def parse_reviews(self, reviews_page) | Parses the DOM and returns user reviews attributes.
:type reviews_page: :class:`bs4.BeautifulSoup`
:param reviews_page: MAL user reviews page's DOM
:rtype: dict
:return: User reviews attributes. | 2.70388 | 2.720507 | 0.993888 |
user_info = self.parse_sidebar(recommendations_page)
second_col = recommendations_page.find(u'div', {u'id': u'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1]
try:
recommendations = second_col.find_all(u"div", {u"class": u"spaceit borderClass"})
if recommendations:... | def parse_recommendations(self, recommendations_page) | Parses the DOM and returns user recommendations attributes.
:type recommendations_page: :class:`bs4.BeautifulSoup`
:param recommendations_page: MAL user recommendations page's DOM
:rtype: dict
:return: User recommendations attributes. | 2.922896 | 2.949687 | 0.990917 |
user_info = self.parse_sidebar(clubs_page)
second_col = clubs_page.find(u'div', {u'id': u'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1]
try:
user_info[u'clubs'] = []
club_list = second_col.find(u'ol')
if club_list:
clubs = club_list.find_all(u'li'... | def parse_clubs(self, clubs_page) | Parses the DOM and returns user clubs attributes.
:type clubs_page: :class:`bs4.BeautifulSoup`
:param clubs_page: MAL user clubs page's DOM
:rtype: dict
:return: User clubs attributes. | 3.287639 | 3.433668 | 0.957471 |
user_info = self.parse_sidebar(friends_page)
second_col = friends_page.find(u'div', {u'id': u'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1]
try:
user_info[u'friends'] = {}
friends = second_col.find_all(u'div', {u'class': u'friendHolder'})
if friends:
... | def parse_friends(self, friends_page) | Parses the DOM and returns user friends attributes.
:type friends_page: :class:`bs4.BeautifulSoup`
:param friends_page: MAL user friends page's DOM
:rtype: dict
:return: User friends attributes. | 2.803938 | 2.899317 | 0.967103 |
user_profile = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username)).text
self.set(self.parse(utilities.get_clean_dom(user_profile)))
return self | def load(self) | Fetches the MAL user page and sets the current user's attributes.
:rtype: :class:`.User`
:return: Current user object. | 7.884254 | 6.845347 | 1.151768 |
page = 0
# collect all reviews over all pages.
review_collection = []
while True:
user_reviews = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/reviews&' + urllib.urlencode({u'p': page})).text
parse_result = self.parse_reviews(utili... | def load_reviews(self) | Fetches the MAL user reviews page and sets the current user's reviews attributes.
:rtype: :class:`.User`
:return: Current user object. | 4.351329 | 4.010333 | 1.085029 |
user_recommendations = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/recommendations').text
self.set(self.parse_recommendations(utilities.get_clean_dom(user_recommendations)))
return self | def load_recommendations(self) | Fetches the MAL user recommendations page and sets the current user's recommendations attributes.
:rtype: :class:`.User`
:return: Current user object. | 6.439857 | 5.219278 | 1.23386 |
user_clubs = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/clubs').text
self.set(self.parse_clubs(utilities.get_clean_dom(user_clubs)))
return self | def load_clubs(self) | Fetches the MAL user clubs page and sets the current user's clubs attributes.
:rtype: :class:`.User`
:return: Current user object. | 6.350905 | 4.928638 | 1.288572 |
user_friends = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/friends').text
self.set(self.parse_friends(utilities.get_clean_dom(user_friends)))
return self | def load_friends(self) | Fetches the MAL user friends page and sets the current user's friends attributes.
:rtype: :class:`.User`
:return: Current user object. | 6.58509 | 5.403364 | 1.218702 |
if nocolor:
# import sys
# sys.stdout.write(text + "" if ("end" in kwargs and kwargs["end"] == "") else '\n')
# sys.stdout.flush()
print(text, **kwargs)
else:
if color is None:
cprint(text, **kwargs)
else:
cprint(text, color, **kwargs) | def printer(text, color=None, **kwargs) | Prints using color or standard print() depending on the value
of 'nocolor'. | 2.989734 | 2.991256 | 0.999491 |
stext = text if text[-1] != split else text[0:-1]
words = stext.split(split)
for i, word in enumerate(words):
col = icols[cols[i]]
printer(word, col, end="")
if i < len(words)-1:
printer(split, end="")
else:
printer(split) | def arb(text, cols, split) | Prints a line of text in arbitrary colors specified by the numeric
values contained in msg.cenum dictionary. | 3.789792 | 4.099438 | 0.924466 |
if level == 1:
#We only affect printability using the quiet setting.
return quiet is None or quiet == False
else:
return ((isinstance(verbosity, int) and level <= verbosity) or
(isinstance(verbosity, bool) and verbosity == True)) | def will_print(level=1) | Returns True if the current global status of messaging would print a
message using any of the printing functions in this module. | 8.896522 | 8.306396 | 1.071045 |
if will_print(level):
printer(("WARNING: " if prefix else "") + msg, "yellow") | def warn(msg, level=0, prefix=True) | Prints the specified message as a warning; prepends "WARNING" to
the message, so that can be left off. | 11.171327 | 12.667128 | 0.881915 |
if will_print(level) or verbosity is None:
printer(("ERROR: " if prefix else "") + msg, "red") | def err(msg, level=-1, prefix=True) | Prints the specified message as an error; prepends "ERROR" to
the message, so that can be left off. | 12.158488 | 14.311122 | 0.849583 |
from os import getenv
if getenv(envar) is not None:
self._vardict[envar] = getenv(envar) | def getenvar(self, envar) | Retrieves the value of an environment variable if it exists. | 6.926754 | 6.301347 | 1.09925 |
from os import path
import xml.etree.ElementTree as ET
#Make sure the file exists and then import it as XML and read the values out.
uxpath = path.expanduser(filepath)
if path.isfile(uxpath):
tree = ET.parse(uxpath)
root = tree.getroot()
... | def load_xml(self, filepath) | Loads the values of the configuration variables from an XML path. | 3.575427 | 3.322755 | 1.076043 |
isense = {}
for child in tag:
if child.tag in isense:
isense[child.tag].update(child.attrib)
else:
isense[child.tag] = child.attrib
self._vardict["isense"] = isense | def _load_isense(self, tag) | Loads isense configuration as a dict of dicts into vardict. | 3.235811 | 2.298041 | 1.408074 |
for child in tag:
if child.tag == "server":
self._vardict["server"] = child.attrib
elif child.tag == "codes":
self._load_codes(child, True)
elif child.tag == "mappings":
self._load_mapping(child, True)
elif ... | def _load_ssh(self, tag) | Loads the SSH configuration into the vardict. | 3.746861 | 3.190782 | 1.174277 |
import re
includes = []
for child in tag:
if child.tag == "include" and "path" in child.attrib:
incl = { "path": child.attrib["path"] }
if "modules" in child.attrib:
incl["modules"] = re.split(",\s*", child.attrib["modules"... | def _load_includes(self, tag, ssh=False) | Extracts all additional libraries that should be included when linking
the unit testing executables. | 3.080051 | 3.02714 | 1.017479 |
codes = []
for code in tag:
if code.tag == "trunk":
codes.append(code.attrib["value"])
if ssh == False:
self._vardict["codes"] = codes
else:
self._vardict["ssh.codes"] = codes | def _load_codes(self, tag, ssh=False) | Extracts all the paths to additional code directories to
be considered.
:arg tag: the ET tag for the <codes> element. | 5.025666 | 5.637218 | 0.891515 |
mappings = {}
for mapping in tag:
if mapping.tag == "map":
mappings[mapping.attrib["module"]] = mapping.attrib["file"]
if ssh == False:
self._vardict["mappings"] = mappings
else:
self._vardict["ssh.mappings"] = mappings | def _load_mapping(self, tag, ssh=False) | Extracts all the alternate module name mappings to
be considered.
:arg tag: the ET tag for the <mappings> element. | 4.409156 | 3.958023 | 1.113979 |
if name in xml.attrib:
return cast(xml.attrib[name])
elif default is not None:
return default
elif tag is not None:
raise ValueError("'{}' is a required attribute of <{}> tag.".format(name, tag)) | 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 tag: the name of the tag to display with the ValueError if the attribu... | 2.502192 | 2.980224 | 0.839598 |
from fortpy.code import config
from os import path
if config.symlink:
from os import symlink, remove
if path.isfile(target) or path.islink(target):
remove(target)
elif path.isdir(target):
msg.warn("Cannot auto-delete directory '{}' for symlinking.".format... | def symlink(source, target, isfile=True) | Creates a symlink at target *file* pointing to source.
:arg isfile: when True, if symlinking is disabled in the global config, the file
is copied instead with fortpy.utility.copyfile; otherwise fortpy.utility.copy
is used and the target is considered a directory. | 4.378786 | 3.769267 | 1.161707 |
from os import path, waitpid
from subprocess import Popen, PIPE
#Append any trailing / that we need to get rsync to work correctly.
source = path.join(src, "")
desti = path.join(dst, "")
if not path.isdir(desti):
from os import mkdir
mkdir(desti)
prsync = Popen("rs... | def copytree(src, dst) | Recursively copies the source directory to the destination
only if the files are newer or modified by using rsync. | 4.235548 | 4.189732 | 1.010936 |
import fortpy
from os import path
fortdir = path.dirname(fortpy.__file__)
return path.join(fortdir, "templates") | def get_fortpy_templates_dir() | Gets the templates directory from the fortpy package. | 3.56666 | 3.105273 | 1.148582 |
#If they didn't specify a custom templates directory, use the default
#one that shipped with the package.
from os import path
if fortpy_templates is not None:
obj.fortpy_templates = path.abspath(path.expanduser(fortpy_templates))
else:
from fortpy.utility import get_fortpy_templ... | def set_fortpy_templates(obj, fortpy_templates=None) | Sets the directory path for the fortpy templates. If no directory
is specified, use the default one that shipped with the package. | 3.437474 | 2.857857 | 1.202815 |
from os import path
xbase = path.abspath(path.expanduser(base))
if not path.isdir(xbase):
return path.join(xbase, relpath)
if relpath[0:2] == "./":
return path.join(xbase, relpath[2::])
else:
from os import chdir, getcwd
cd = getcwd()
chdir(xbase)
... | def get_dir_relpath(base, relpath) | Returns the absolute path to the 'relpath' taken relative to the base
directory.
:arg base: the base directory to take the path relative to.
:arg relpath: the path relative to 'base' in terms of '.' and '..'. | 2.75011 | 3.256484 | 0.844503 |
result = []
builder = []
length = 0
if limit is not None:
sline = line[0:limit]
else:
sline = line
for word in sline.split():
if length <= chars:
builder.append(word)
length += len(word) + 1
else:
result.append(' '... | def wrap_line(line, limit=None, chars=80) | Wraps the specified line of text on whitespace to make sure that none of the
lines' lengths exceeds 'chars' characters. | 2.307003 | 2.37556 | 0.971141 |
lineno, column = err.position
if "<doc>" in content:
#Adjust the position since we are taking the <doc> part out of the tags
#since we may have put that in ourselves.
column -= 5
start = lineno - (1 if lineno == 1 else 2)
lines = []
tcontent = content.replace("<doc>", ""... | def x_parse_error(err, content, source) | Explains the specified ParseError instance to show the user where the error
happened in their XML. | 6.156456 | 5.816434 | 1.058459 |
try:
tree = ET.XML(content)
except ET.ParseError as err:
x_parse_error(err, content, source)
return tree | def XML(content, source=None) | Parses the XML text using the ET.XML function, but handling the ParseError in
a user-friendly way. | 4.013203 | 3.674836 | 1.092077 |
try:
tree = ET.fromstring(content)
except ET.ParseError as err:
x_parse_error(err, content, source)
return tree | def XML_fromstring(content, source=None) | Parses the XML string into a node tree. If an ParseError exception is raised,
the error message is formatted nicely to show the badly formed XML to the user. | 3.546818 | 3.541237 | 1.001576 |
result = []
if type(element).__name__ in ["Subroutine", "Function"]:
_format_executable(result, element)
elif type(element).__name__ == "CustomType":
_format_type(result, element)
elif isinstance(element, ValueElement):
_format_value_element(result, element)
return '\n'... | def format(element) | Formats all of the docstrings in the specified element and its
children into a user-friendly paragraph format for printing.
:arg element: an instance of fortpy.element.CodeElement. | 3.738056 | 4.463614 | 0.837451 |
rlines = []
rlines.append(element.signature)
_format_summary(rlines, element)
rlines.append("")
rlines.append("PARAMETERS")
for p in element.ordered_parameters:
_format_value_element(rlines, p)
rlines.append("")
_format_generic(rlines, element, ["summary"])
#Subroutin... | def _format_executable(lines, element, spacer="") | Performs formatting specific to a Subroutine or Function code
element for relevant docstrings. | 3.301733 | 3.091377 | 1.068046 |
rlines = []
rlines.append(element.signature)
_format_summary(rlines, element)
rlines.append("")
_format_generic(rlines, element, ["summary"])
if len(element.executables) > 0:
rlines.append("\nEMBEDDED PROCEDURES")
for key, value in list(element.executables.items()):
... | def _format_type(lines, element, spacer="") | Formats a derived type for full documentation output. | 3.471189 | 3.368044 | 1.030625 |
lines.append(spacer + element.definition())
_format_summary(lines, element)
_format_generic(lines, element, ["summary"]) | def _format_value_element(lines, element, spacer="") | Formats a member or parameter for full documentation output. | 9.494054 | 7.500843 | 1.265732 |
summary = spacer + element.summary
if element.summary == "":
summary = spacer + "No description given in XML documentation for this element."
lines.append(summary) | def _format_summary(lines, element, spacer=" ") | Adds the element's summary tag to the lines if it exists. | 6.283844 | 5.098179 | 1.232566 |
for doc in element.docstring:
if doc.doctype.lower() not in printed:
lines.append(spacer + doc.__str__()) | def _format_generic(lines, element, printed, spacer="") | Generically formats all remaining docstrings and custom XML
tags that don't appear in the list of already printed documentation.
:arg printed: a list of XML tags for the element that have already
been handled by a higher method. | 8.422357 | 6.342247 | 1.327977 |
result = []
for p in executable.ordered_parameters:
atypes = p.argtypes
if atypes is not None:
result.extend(p.argtypes)
else:
print(("No argtypes for: {}".format(p.definition())))
if type(executable).__name__ == "Function":
result.extend(executa... | def _py_ex_argtype(executable) | Returns the code to create the argtype to assign to the methods argtypes
attribute. | 5.3002 | 5.380435 | 0.985088 |
ctype = parameter.ctype
if ctype is None:
raise ValueError("Can't bind ctypes py_parameter for parameter"
" {}".format(parameter.definition()))
return ctype.lower() | def _py_ctype(parameter) | Returns the ctypes type name for the specified fortran parameter. | 9.27941 | 8.305475 | 1.117264 |
pytype = parameter.pytype
if pytype is None:
raise ValueError("Can't pre-determine type for parameter: {}".format(parameter.definition()))
return pytype | def _py_pytype(parameter) | Returns the name of the *python* type for the fortran parameter. | 6.144228 | 5.62392 | 1.092517 |
count = 0
allparams = executable.ordered_parameters
if type(executable).__name__ == "Function":
allparams = allparams + [executable]
for p in allparams:
value = _py_clean(p, tab)
if value is not None:
count += 1
lines.append(value)
... | def _py_code_clean(lines, tab, executable) | Appends all the code lines needed to create the result class instance and populate
its keys with all output variables. | 4.90694 | 4.89823 | 1.001778 |
splice = ', '.join(["{0}_{1:d}".format(parameter.lname, i)
for i in range(parameter.D)])
return "{2}{0}_ft = Ftype({0}_o, [{1}], libpath)".format(parameter.lname, splice, tab) | def _py_ftype(parameter, tab) | Returns the code to declare an Ftype object that handles memory
deallocation for Fortran return arrays that were allocated by the
method called in ctypes. | 10.008079 | 8.993255 | 1.112843 |
if "out" in parameter.direction:
if parameter.D > 0:
if ":" in parameter.dimension and ("allocatable" in parameter.modifiers or
"pointer" in parameter.modifiers):
if parameter.D == 1:
clarray = "as_array({0}_... | def _py_clean(parameter, tab) | Returns the code line to clean the output value of the specified parameter. | 6.617562 | 6.47026 | 1.022766 |
if parameter.direction == "(out)":
result = []
checks = ["{0}_{1:d}.value==0".format(parameter.lname, i) for i in range(parameter.D)]
spacing = len(tab) + 2 + 3 + 3 + 2
result.append("{}if not all([{}]):".format(tab, present_params(checks, spacing, linecont=", ")))
for l... | def _py_check_optional(parameter, tab, assign) | Returns the code to check for actual values when an out parameter is pure
out/optional and doesn't have anything changed.
:arg assign: the actual variable assignment value if the conditions pass. | 5.759181 | 5.686379 | 1.012803 |
allparams = executable.ordered_parameters
if type(executable).__name__ == "Function":
allparams = allparams + [executable]
for p in allparams:
_py_code_parameter(lines, p, "invar", lparams, tab)
if p.direction == "(out)":
#We need to reverse the order of the indices... | def _py_code_variables(lines, executable, lparams, tab) | Adds the variable code lines for all the parameters in the executable.
:arg lparams: a list of the local variable declarations made so far that need to be passed
to the executable when it is called. | 3.125939 | 3.426562 | 0.912267 |
mdict = {
"invar": _py_invar,
"outvar": _py_outvar,
"indices": _py_indices
}
line = mdict[position](parameter, lparams, tab)
if line is not None:
value, blank = line
lines.append(tab + value)
if blank:
lines.append("") | def _py_code_parameter(lines, parameter, position, lparams, tab) | Appends the code to produce the parameter at the specified position in the executable.
:arg position: one of ['invar', 'outvar', 'indices'].
:arg lparams: a list of the local variable declarations made so far that need to be passed
to the executable when it is called. | 4.057823 | 3.792743 | 1.069891 |
if ("in" in parameter.direction and parameter.D > 0):
if parameter.direction == "(inout)" and ":" not in parameter.dimension:
wstr = ", writeable"
else:
wstr = ""
pytype = _py_pytype(parameter)
lparams.append("{}_a".format(parameter.lname))
return... | def _py_invar(parameter, lparams, tab) | Returns the code to create the local input parameter that is coerced to have the
correct type for ctypes interaction. | 4.772213 | 4.679904 | 1.019725 |
if ("out" in parameter.direction and parameter.D > 0 and ":" in parameter.dimension and
("allocatable" in parameter.modifiers or "pointer" in parameter.modifiers)):
lparams.append("byref({}_o)".format(parameter.lname))
blank = True if parameter.direction == "(inout)" else False
... | def _py_outvar(parameter, lparams, tab) | Returns the code to produce a ctypes output variable for interacting with fortran. | 9.700671 | 8.840136 | 1.097344 |
if parameter.D > 0 and ":" in parameter.dimension:
if "in" in parameter.direction:
indexstr = "{0}_{1:d} = c_int({0}_a.shape[{1:d}])"
else:
indexstr = "{0}_{1:d} = c_int(0)"
lparams.extend(["byref({}_{})".format(parameter.lname, i) for i in range(parameter.D)])
... | def _py_indices(parameter, lparams, tab) | Returns the code to produce py ctypes for the indices of the specified parameter
that has D > 0. | 5.17674 | 4.682508 | 1.105548 |
mdict = {
'indices': _ctypes_indices,
'variable': _ctypes_variables,
'out': _ctypes_out,
'regular': _ctypes_regular,
'saved': _ctypes_saved,
'assign': _ctypes_assign,
'clean': _ctypes_clean
}
line = mdict[position](parameter)
if line is not No... | def _ctypes_code_parameter(lines, parameter, position) | Returns the code for the specified parameter being written into a subroutine wrapper.
:arg position: one of ['indices', 'variable', 'out', 'regular', 'saved', 'assign', 'clean'] | 3.998679 | 2.574269 | 1.553326 |
ctype = parameter.ctype
if ctype is None:
if parameter.kind is not None:
return "{}({})".format(parameter.dtype, parameter.kind)
else:
return parameter.dtype
else:
return"{}({})".format(parameter.dtype, ctype) | def _ctypes_dtype(parameter) | Determines the ISO_C data type to use for describing the specified parameter. | 3.68415 | 3.473856 | 1.060536 |
params = parameter.ctypes_parameter()
if parameter.direction == "(inout)" and ("allocatable" in parameter.modifiers or
"pointer" in parameter.modifiers):
return ', '.join(params[1:-1])
else:
return ', '.join(params[1::]) | def _ctypes_splice(parameter) | Returns a list of variable names that define the size of each dimension. | 9.402412 | 9.349895 | 1.005617 |
if (parameter.dimension is not None and ":" in parameter.dimension):
splice = _ctypes_splice(parameter)
if "out" in parameter.direction:
#Even for pure out variables, the ctypes pointer is passed in and will
#have a value already.
return ("integer, intent(ino... | def _ctypes_indices(parameter) | Returns code for parameter variable declarations specifying the size of each
dimension in the specified parameter. | 9.136718 | 8.464286 | 1.079443 |
if parameter.dimension is not None and ":" in parameter.dimension:
#For arrays that provide input (including 'inout'), we pass the output separately
#through a c-pointer. They will always be input arrays. For pure (out) parameters
#we use *only* a c-ptr, but it needs intent (inout) sinc... | def _ctypes_variables(parameter) | Returns the local parameter definition for implementing a Fortran wrapper subroutine
for this parameter's parent executable. | 8.050872 | 7.98315 | 1.008483 |
if (parameter.dimension is not None and ":" in parameter.dimension
and "out" in parameter.direction and ("allocatable" in parameter.modifiers or
"pointer" in parameter.modifiers)):
if parameter.direction == "(inout)":
return ("type(C_PTR... | def _ctypes_out(parameter) | Returns a parameter variable declaration for an output variable for the specified
parameter. | 6.531087 | 6.25362 | 1.044369 |
if ("pointer" in parameter.modifiers or "allocatable" in parameter.modifiers
or "target" in parameter.modifiers or parameter.dtype == "logical"):
return (parameter.definition(local=True), False) | def _ctypes_regular(parameter) | Returns the code lines to define a *local* variable with the fortran types
that has a matching signature to the wrapped executable. | 10.266374 | 8.812532 | 1.164974 |
if ("out" in parameter.direction and parameter.dimension is not None and
":" in parameter.dimension and ("allocatable" in parameter.modifiers or
"pointer" in parameter.modifiers)):
stype = _ctypes_dtype(parameter)
name = "{}_t({})".format(paramete... | def _ctypes_saved(parameter) | Returns local variable declarations that create allocatable variables that can persist
long enough to return their value through ctypes. | 8.746324 | 8.371056 | 1.044829 |
#If the array is set to only have intent(out), we don't want to allocate or assign
#a value to it; otherwise we do.
if (parameter.direction != "(out)" and ("allocate" in parameter.modifiers
or "pointer" in parameter.modifiers
... | def _ctypes_assign(parameter) | Returns the Fortran code lines to allocate and assign values to the *original*
parameter ValueElement that exists now only as a local variable so that the
signatures match for the compiler. | 5.608749 | 5.101372 | 1.099459 |
if ("out" in parameter.direction and parameter.dimension is not None
and ":" in parameter.dimension and ("pointer" in parameter.modifiers or
"allocatable" in parameter.modifiers)):
params = parameter.ctypes_parameter()
result = []
spac... | def _ctypes_clean(parameter) | Returns the lines of code required to assign the correct values to the integers
representing the indices of the output arrays in the ctypes wrapper subroutine. | 4.292675 | 4.097208 | 1.047707 |
result = []
for p in executable.ordered_parameters:
result.extend(p.ctypes_parameter())
if type(executable).__name__ == "Function":
result.extend(executable.ctypes_parameter()) #This method inherits from ValueElement.
return result | def _ctypes_ex_parameters(executable) | Returns a list of the parameters to form the wrapper executable to interact
with ctypes. | 8.329119 | 7.904311 | 1.053744 |
result = []
for p in executable.ordered_parameters:
_ctypes_code_parameter(result, p, "indices")
_ctypes_code_parameter(result, p, "variable")
_ctypes_code_parameter(result, p, "out")
if type(executable).__name__ == "Function":
#For functions, we still create a subrouti... | def _ctypes_ex_variables(executable) | Returns a list of the local variable definitions required to construct the
ctypes interop wrapper. | 4.416314 | 4.341693 | 1.017187 |
result = []
for p in executable.ordered_parameters:
_ctypes_code_parameter(result, p, "regular")
_ctypes_code_parameter(result, p, "saved")
if type(executable).__name__ == "Function":
_ctypes_code_parameter(result, executable, "regular")
_ctypes_code_parameter(result, e... | def _ctypes_ex_compatvars(executable) | Returns a list of code lines for signature matching variables, and
pointer saving variables. | 4.143487 | 3.672268 | 1.128318 |
result = []
for p in executable.ordered_parameters:
_ctypes_code_parameter(result, p, "assign")
if type(executable).__name__ == "Function":
_ctypes_code_parameter(result, executable, "assign")
return result | def _ctypes_ex_assign(executable) | Return a list of code lines to allocate and assign the local parameter definitions
that match those in the signature of the wrapped executable. | 5.891354 | 5.296917 | 1.112223 |
result = []
for p in executable.ordered_parameters:
_ctypes_code_parameter(result, p, "clean")
if type(executable).__name__ == "Function":
_ctypes_code_parameter(result, executable, "clean")
return result | def _ctypes_ex_clean(executable) | Return a list of code lines to take care of assigning pointers for output variables
interacting with ctypes. | 6.439151 | 6.097482 | 1.056034 |
if self.library is not None:
return "ftypes.{}.so".format(self.library)
else:
return "{}.so".format(self.name) | def libname(self) | Returns the name of the shared library file compiled for the wrapper
subroutines coded in fortran. | 5.279315 | 4.619968 | 1.142717 |
from os import path
return path.join(self.dirpath, self.libname) | def libpath(self) | Returns the full path to the shared *wrapper* library created for the
module. | 5.698541 | 5.296186 | 1.075971 |
from os import path
if self.link is None or not path.isfile(self.link):
self.makelib(remake, True, compiler, debug, profile) | def _check_lib(self, remake, compiler, debug, profile) | Makes sure that the linked library with the original code exists. If it doesn't
the library is compiled from scratch. | 5.920688 | 4.752017 | 1.245931 |
self._check_lib(remake, compiler, debug, profile)
from os import path
if self.link is None or not path.isfile(self.link):
msg.err("Can't create shared library; missing compiled original code: {}".format(self.link))
exit(0)
if remake or n... | def make(self, remake=False, dependencies=None,
compiler="gfortran", debug=False, profile=False) | Generates a makefile to compile the wrapper module and link it with the shared
library that can be compiled with self.makelib(). | 5.636557 | 5.636458 | 1.000018 |
from os import path
options = ""
if debug:
options += " DEBUG=true"
if profile:
options += " GPROF=true"
from os import system
codestr = "cd {}; make -f '{}' F90={} FAM={}" + options
code = system(codestr.format(dirpath, makename,... | def _compile(self, dirpath, makename, compiler, debug, profile) | Compiles the makefile at the specified location with 'compiler'.
:arg dirpath: the full path to the directory where the makefile lives.
:arg compiler: one of ['ifort', 'gfortran'].
:arg makename: the name of the make file to compile. | 7.403308 | 7.373291 | 1.004071 |
if self.link is None or remake:
from os import path
if self.library is not None:
outpath = path.join(self.dirpath, "{}.a".format(self.library))
else:
outpath = path.join(self.dirpath, "{}.a".format(self.name))
if not remak... | def makelib(self, remake=False, full=True, compiler="gfortran", debug=False, profile=False) | Generates a makefile for the code files that reside in the same directory as the source
that was parsed by the code parser.
:arg full: when True, the shared library is compiled for *all* the code files in the directory
not just the one's that are dependencies of the source module. | 4.201043 | 4.341286 | 0.967696 |
from os import path
if not path.isfile(outpath) and path.isfile(self.link):
from shutil import copy
copy(self.link, outpath) | def _copy_so(self, outpath) | Copies the shared library in self.so into the working directory for the wrapper
module if it doesn't already exist. | 3.940655 | 3.588824 | 1.098035 |
#The only complication with the whole process is that we need to get the list of
#dependencies for the current module. For full lib, we compile *all* the files in
#the directory, otherwise only those that are explicitly required.
result = []
if full:
found = ... | def _get_lib_modules(self, full) | Returns a list of the modules in the same folder as the one being wrapped for
compilation as a linked library.
:arg full: when True, all the code files in the source file's directory are considered
as dependencies; otherwise only those explicitly needed are kept. | 5.814983 | 5.713118 | 1.01783 |
#The only complication with the whole process is that we need to get the list of
#dependencies for the current module. For full lib, we compile *all* the files in
#the directory, otherwise only those that are explicitly required.
from os import path
modules = self.module... | def _get_dependencies(self) | Gets a list of the module names that should be included in the shared lib compile
as dependencies for the current wrapper module. | 7.104108 | 6.538998 | 1.086422 |
if len(self.needs) > 0:
return
for execname, executable in list(self.module.executables.items()):
skip = False
#At the moment we can't handle executables that use special derived types.
if not execname in self.module.publics or not execut... | def _find_executables(self) | Finds the list of executables that pass the requirements necessary to have
a wrapper created for them. | 6.66924 | 6.207192 | 1.074438 |
from os import path, mkdir
if not path.isdir(self.dirpath):
mkdir(self.dirpath)
#Copy the ftypes.py module shipped with fortpy to the local directory.
ftypes = path.join(get_fortpy_templates(), "ftypes.py")
from shutil import copy
copy... | def _check_dir(self) | Makes sure that the working directory for the wrapper modules exists. | 3.867602 | 3.655275 | 1.058088 |
self._check_dir()
#We make it so that the write py method can be called independently (as opposed
#to first needing the F90 write method to be called).
self._find_executables()
lines = []
lines.append('')
lines.append("from ctypes import *")
... | def write_py(self) | Writes a python module file to the current working directory for the library. | 4.963206 | 4.842843 | 1.024854 |
executable = self.module.executables[execname]
#The 5 in the formatting indent comes from 1 space, 3 from the 'def'
#and 1 from '('.
inparams = []
for p in executable.ordered_parameters:
if "in" in p.direction:
inparams.append(p.l... | def _write_executable_py(self, execname, lines) | Writes the python executable definition for interacting with ctypes.
:arg execname: the name of the executable to write.
:arg lines: the lines of python code are appended to this list. | 6.69166 | 6.708057 | 0.997556 |
#The only complication we have here is that we don't want to break words up.
words = text.split()
result = []
line = []
cumline = 0
for word in words:
if len(word) + 1 + cumline < 90:
line.append(word)
cumline += len(wo... | def _format_docstring(self, text) | Formats the specified text for display within 90 characters. Returns a list
of *un-joined* lines.
:arg text: the text to format. | 3.38243 | 3.257987 | 1.038196 |
from os import path
self._check_dir()
#Find the list of executables that we actually need to write wrappers for.
self._find_executables()
lines = []
lines.append("!!<summary>Auto-generated Fortran module for interaction with ctypes\n"
... | def write_f90(self) | Writes the F90 module file to the specified directory. | 5.679695 | 5.501449 | 1.0324 |
executable = self.module.executables[execname]
#The 14 in the formatting indent comes from 4 spaces, 2 from "_c", 1 from the spacing
#between 'subroutine' and name of the executable, 10 from subroutine, 1 from the ("
cparams = present_params(_ctypes_ex_parameters(ex... | def _write_executable_f90(self, execname, lines) | Appends the Fortran code to write the wrapper executable to the specified 'lines' list.
:arg execname: the name of the executable in the self.module.executables to write. | 8.143783 | 8.202867 | 0.992797 |
result = list(modules)
for i, module in enumerate(modules):
#It is possible that the parser couldn't find it, if so
#we can't create the executable!
if module in self.module.parent.modules:
modneeds = self.module.parent.modules[module].needs
... | def _process_module_needs(self, modules) | Adds the module and its dependencies to the result list in dependency order. | 5.132925 | 4.905342 | 1.046395 |
from os import chdir, getcwd, path
cd = getcwd()
chdir(coderoot)
result = path.abspath(relpath)
chdir(cd)
return result | def coderelpath(coderoot, relpath) | Returns the absolute path of the 'relpath' relative to the specified code directory. | 2.985775 | 2.774188 | 1.07627 |
global paramiko
if paramiko is none:
import paramiko
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(self.server, username=self.user, pkey=self.pkey) | def _setup_ssh(self) | Initializes the connection to the server via SSH. | 2.544651 | 2.316997 | 1.098254 |
if self.is_ssh(path):
return path
else:
return os.path.abspath(path) | def abspath(self, path) | Returns the absolute path to the specified relative or user-relative
path. For ssh paths, just return the full ssh path. | 4.387541 | 3.072974 | 1.427783 |
if self.is_ssh(path):
remotepath = self._get_remote(path)
remotedir = os.path.dirname(remotepath)
return self._get_tramp_path(remotedir)
else:
return os.path.dirname(path) | def dirname(self, path) | Returns the full path to the parent directory of the specified
file path. | 3.607472 | 3.527063 | 1.022798 |
if self.is_ssh(filepath):
self._check_ssh()
remotepath = self._get_remote(filepath)
stdin, stdout, stderr = self.ssh.exec_command("touch {}".format(remotepath))
stdin.close()
else:
os.system("touch {}".format(filepath)) | def touch(self, filepath) | Touches the specified file so that its modified time changes. | 3.056553 | 3.130934 | 0.976243 |
if ssh:
self._check_ssh()
stdin, stdout, stderr = self.ssh.exec_command("cd; pwd")
stdin.close()
remotepath = filepath.replace("~", stdout.read().split()[0])
return self._get_tramp_path(remotepath)
else:
return os.path.expa... | def expanduser(self, filepath, ssh=False) | Replaces the user root ~ with the full path on the file system.
Works for local disks and remote servers. For remote servers, set
ssh=True. | 3.983167 | 3.791083 | 1.050667 |
if self.is_ssh(filepath):
self._check_ftp()
remotepath = self._get_remote(filepath)
try:
self.ftp.stat(remotepath)
except IOError as e:
if e.errno == errno.ENOENT:
return False
else:
... | def exists(self, filepath) | Determines if the specified file/folder exists, even if it
is on a remote server. | 2.694704 | 2.659347 | 1.013295 |
if self.is_ssh(filepath):
self._check_ftp()
source = self._get_remote(filepath)
mtime = self.ftp.stat(source).st_mtime
else:
mtime = os.path.getmtime(filepath)
return mtime | def getmtime(self, filepath) | Gets the last time that the file was modified. | 3.756237 | 3.729278 | 1.007229 |
target = self._read_check(filepath)
if os.path.isfile(target):
with open(target) as f:
string = f.read()
#If we got this file via SSH, delete it from the temp folder
if self.is_ssh(filepath):
os.remove(target)
else:
... | def read(self, filepath) | Returns the entire file as a string even if it is on a remote
server. | 5.520523 | 4.631924 | 1.191842 |
target = self._read_check(filepath)
if os.path.isfile(target):
with open(target) as f:
lines = f.readlines()
#If we got this file via SSH, delete it from the temp folder
if self.is_ssh(filepath):
os.remove(target)
els... | def readlines(self, filepath) | Returns the list of strings extracted from the file using either
open() if it is a local file, or by copying over the network using
sftp over SSH. | 5.116763 | 4.746315 | 1.078049 |
if self.is_ssh(filepath):
self._check_ftp()
#First we need to generate a file path on the local system to
#copy the file to.
source = self._get_remote(filepath)
target = self._get_hashed_path(filepath)
self.ftp.get(source, target)
... | def _read_check(self, filepath) | Returns the path of a file on the *local* system that can be read
from. If the filepath is on a remote server, the file is first copied
locally. | 8.043388 | 6.130535 | 1.312021 |
if self.is_ssh(dirpath):
self._check_ftp()
remotepath = self._get_remote(dirpath)
return self._sftp_walk(remotepath)
else:
return os.walk(dirpath) | def walk(self, dirpath) | Performs an os.walk on a local or SSH filepath. | 3.948832 | 3.172538 | 1.244692 |
#Get all the files and folders in the current directory over SFTP.
path = remotepath # We need this instance of path for the yield to work.
files=[]
folders=[]
for f in self.ftp.listdir_attr(remotepath):
if S_ISDIR(f.st_mode):
folders.append(s... | def _sftp_walk(self, remotepath) | Performs the same function as os.walk but over the SSH channel. | 4.672608 | 4.542313 | 1.028685 |
return self._get_path('%s.pkl' % hashlib.md5(path.encode("utf-8")).hexdigest()) | def _get_hashed_path(self, path) | Returns an md5 hash for the specified file path. | 5.148881 | 4.994242 | 1.030964 |
tempdir = settings._temp_directory
if not os.path.exists(tempdir):
os.makedirs(tempdir)
return os.path.join(tempdir, filename) | def _get_path(self, filename) | Creates the cache directory if it doesn't already exist. Returns the
full path to the specified file inside the cache directory. | 3.487332 | 3.080497 | 1.132068 |
keypath = self.config.server["pkey"]
with open(os.path.expanduser(keypath)) as f:
pkey = paramiko.RSAKey.from_private_key(f)
return pkey | def _get_pkey(self) | Gets an RSAKey object for the private key file so that we can
copy files without logging in with user/password. | 4.014707 | 3.361317 | 1.194385 |
if self._pkey is None:
self._pkey = self._get_pkey()
return self._pkey | def pkey(self) | Returns the private key for quick authentication on the SSH server. | 3.912949 | 3.235607 | 1.20934 |
#The +2 is spacing is for the tab indent at the start of the line.
#The +3 is for indent and the extra parenthesis at the start of the call.
line = []
length = 0
result = []
for param in paramlist:
extra = len(list(param))
if length + extra + 2 + spacing > maxchars:
... | def present_params(paramlist, spacing = 0, maxchars=90, linecont=", &") | Creates the (paramlist) for a method call formatted nicely for calls
with lots of parameters. | 4.808361 | 4.730088 | 1.016548 |
setattr(func, name, self.values)
return func | def metarate(self, func, name='values') | Set the values object to the function object's namespace | 10.029893 | 8.428641 | 1.189977 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.