code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
return self._pipeline.history(name=self.data.name, offset=offset) | def history(self, offset=0) | The pipeline history allows users to list pipeline instances.
:param offset: number of pipeline instances to be skipped.
:return: an array of pipeline instances :class:`yagocd.resources.pipeline.PipelineInstance`.
:rtype: list of yagocd.resources.pipeline.PipelineInstance | 11.923245 | 20.639627 | 0.577687 |
return self._pipeline.get(name=self.data.name, counter=counter) | def get(self, counter) | Gets pipeline instance object.
:param counter pipeline counter:
:return: A pipeline instance object :class:`yagocd.resources.pipeline.PipelineInstance`.
:rtype: yagocd.resources.pipeline.PipelineInstance | 10.798785 | 16.899727 | 0.638992 |
self._pipeline.pause(name=self.data.name, cause=cause) | def pause(self, cause) | Pause the current pipeline.
:param cause: reason for pausing the pipeline. | 11.876667 | 12.268448 | 0.968066 |
return self._pipeline.schedule(
name=self.data.name,
materials=materials,
variables=variables,
secure_variables=secure_variables
) | def schedule(self, materials=None, variables=None, secure_variables=None) | Scheduling allows user to trigger a specific pipeline.
:param materials: material revisions to use.
:param variables: environment variables to set.
:param secure_variables: secure environment variables to set.
:return: a text confirmation. | 3.909457 | 4.293263 | 0.910603 |
return self._pipeline.schedule_with_instance(
name=self.data.name,
materials=materials,
variables=variables,
secure_variables=secure_variables,
backoff=backoff,
max_tries=max_tries
) | def schedule_with_instance(
self,
materials=None,
variables=None,
secure_variables=None,
backoff=0.5,
max_tries=20
) | Schedule pipeline and return instance.
Credits of implementation comes to `gaqzi`:
https://github.com/gaqzi/py-gocd/blob/master/gocd/api/pipeline.py#L122
:warning: Replace this with whatever is the official way as soon as gocd#990 is fixed. \
https://github.com/gocd/gocd/issues/990
... | 2.423152 | 2.887395 | 0.839217 |
return PipelineEntity.get_url(server_url=self._session.server_url, pipeline_name=self.data.name) | def pipeline_url(self) | Returns url for accessing pipeline entity. | 9.335773 | 6.172204 | 1.512551 |
stages = list()
for data in self.data.stages:
stages.append(StageInstance(session=self._session, data=data, pipeline=self))
return stages | def stages(self) | Method for getting stages from pipeline instance.
:return: arrays of stages
:rtype: list of yagocd.resources.stage.StageInstance | 6.368313 | 5.639705 | 1.129193 |
for stage in self.stages():
if stage.data.name == name:
return stage | def stage(self, name) | Method for searching specific stage by it's name.
:param name: name of the stage to search.
:return: found stage or None.
:rtype: yagocd.resources.stage.StageInstance | 5.535012 | 8.265962 | 0.669615 |
values = [values[name]]
instance_name = '_{}'.format(name)
values.append(getattr(self, instance_name, None))
try:
return next(item for item in values if item is not None)
except StopIteration:
raise ValueError("The value for parameter '{}' is req... | def _require_param(self, name, values) | Method for finding the value for the given parameter name.
The value for the parameter could be extracted from two places:
* `values` dictionary
* `self._<name>` attribute
The use case for this method is that some resources are nested and
managers could have dependencies on... | 3.573759 | 4.496383 | 0.794807 |
if not self.VERSION_TO_ACCEPT_HEADER:
return self.ACCEPT_HEADER
return YagocdUtil.choose_option(
version_to_options=self.VERSION_TO_ACCEPT_HEADER,
default=self.ACCEPT_HEADER,
server_version=self._session.server_version
) | def _accept_header(self) | Method for determining correct `Accept` header.
Different resources and different GoCD version servers prefer
a diverse headers. In order to manage all of them, this method
tries to help: if `VERSION_TO_ACCEPT_HEADER` is not provided,
if would simply return default `ACCEPT_HEADER`.
... | 7.27164 | 4.872437 | 1.492403 |
result = self._predecessors
if transitive:
return YagocdUtil.graph_depth_walk(result, lambda v: v.predecessors)
return result | def get_predecessors(self, transitive=False) | Property for getting predecessors (parents) of current pipeline.
This property automatically populates from API call
:return: list of :class:`yagocd.resources.pipeline.PipelineEntity`.
:rtype: list of yagocd.resources.pipeline.PipelineEntity | 10.377913 | 10.678138 | 0.971884 |
result = self._descendants
if transitive:
return YagocdUtil.graph_depth_walk(result, lambda v: v.descendants)
return result | def get_descendants(self, transitive=False) | Property for getting descendants (children) of current pipeline.
It's calculated by :meth:`yagocd.resources.pipeline.PipelineManager#tie_descendants` method during listing of
all pipelines.
:return: list of :class:`yagocd.resources.pipeline.PipelineEntity`.
:rtype: list of yagocd.resour... | 12.270678 | 11.215253 | 1.094106 |
return self._manager.walk(top=self._path, topdown=topdown) | def walk(self, topdown=True) | Artifact tree generator - analogue of `os.walk`.
:param topdown: if is True or not specified, directories are scanned
from top-down. If topdown is set to False, directories are scanned
from bottom-up.
:rtype: collections.Iterator[
(str, list[yagocd.resources.artifact.Artifac... | 9.754908 | 10.233301 | 0.953251 |
if self.data.type == self._manager.FOLDER_TYPE:
raise YagocdException("Can't fetch folder <{}>, only file!".format(self._path))
response = self._session.get(self.data.url)
return response.content | def fetch(self) | Method for getting artifact's content.
Could only be applicable for file type.
:return: content of the artifact. | 9.572053 | 8.513043 | 1.124398 |
# Validate args!
if 'oauth_consumer_key' not in args:
raise web.HTTPError(401, "oauth_consumer_key missing")
if args['oauth_consumer_key'] not in self.consumers:
raise web.HTTPError(401, "oauth_consumer_key not known")
if 'oauth_signature' not in args:
... | def validate_launch_request(
self,
launch_url,
headers,
args
) | Validate a given launch request
launch_url: Full URL that the launch request was POSTed to
headers: k/v pair of HTTP headers coming in with the POST
args: dictionary of body arguments passed to the launch_url
Must have the following keys to be valid:
oauth_consumer_k... | 2.853112 | 2.816817 | 1.012885 |
# inspired by code powering similar functionality in mpld3
# https://github.com/jakevdp/mpld3/blob/master/mpld3/_display.py#L357
from IPython.core.getipython import get_ipython
from IPython.display import display, Javascript, HTML
self.ipython_enabled = True
s... | def enable_ipython(self, **kwargs) | Enable plotting in the iPython notebook.
Once enabled, all lightning plots will be automatically produced
within the iPython notebook. They will also be available on
your lightning server within the current session. | 5.270133 | 5.077212 | 1.037997 |
from IPython.core.getipython import get_ipython
self.ipython_enabled = False
ip = get_ipython()
formatter = ip.display_formatter.formatters['text/html']
formatter.type_printers.pop(Visualization, None)
formatter.type_printers.pop(VisualizationLocal, None) | def disable_ipython(self) | Disable plotting in the iPython notebook.
After disabling, lightning plots will be produced in your lightning server,
but will not appear in the notebook. | 4.947758 | 5.177229 | 0.955677 |
self.session = Session.create(self, name=name)
return self.session | def create_session(self, name=None) | Create a lightning session.
Can create a session with the provided name, otherwise session name
will be "Session No." with the number automatically generated. | 4.489503 | 5.81019 | 0.772695 |
self.session = Session(lgn=self, id=session_id)
return self.session | def use_session(self, session_id) | Use the specified lightning session.
Specify a lightning session by id number. Check the number of an existing
session in the attribute lightning.session.id. | 8.241739 | 7.836317 | 1.051736 |
from requests.auth import HTTPBasicAuth
self.auth = HTTPBasicAuth(username, password)
return self | def set_basic_auth(self, username, password) | Set authenatication. | 3.310418 | 2.944153 | 1.124404 |
if host[-1] == '/':
host = host[:-1]
self.host = host
return self | def set_host(self, host) | Set the host for a lightning server.
Host can be local (e.g. http://localhost:3000), a heroku
instance (e.g. http://lightning-test.herokuapp.com), or
a independently hosted lightning server. | 4.035933 | 4.954961 | 0.814524 |
try:
r = requests.get(self.host + '/status', auth=self.auth,
timeout=(10.0, 10.0))
if not r.status_code == requests.codes.ok:
print("Problem connecting to server at %s" % self.host)
print("status code: %s" % r.status_c... | def check_status(self) | Check the server for status | 2.033027 | 1.945417 | 1.045034 |
datadict = cls.clean(*args, **kwargs)
if 'data' in datadict:
data = datadict['data']
data = cls._ensure_dict_or_list(data)
else:
data = {}
for key in datadict:
if key == 'images':
data[key] = datadict[... | def _clean_data(cls, *args, **kwargs) | Convert raw data into a dictionary with plot-type specific methods.
The result of the cleaning operation should be a dictionary.
If the dictionary contains a 'data' field it will be passed directly
(ensuring appropriate formatting). Otherwise, it should be a
dictionary of data-type spec... | 3.02562 | 2.278565 | 1.327862 |
if not type:
raise Exception("Must provide a plot type")
options, description = cls._clean_options(**kwargs)
data = cls._clean_data(*args)
if 'images' in data and len(data) > 1:
images = data['images']
del data['images']
viz = c... | def _baseplot(cls, session, type, *args, **kwargs) | Base method for plotting data and images.
Applies a plot-type specific cleaning operation to generate
a dictionary with the data, then creates a visualization with the data.
Expects a session and a type, followed by all plot-type specific
positional and keyword arguments, which will be... | 2.598587 | 2.342365 | 1.109386 |
data = self._clean_data(*args, **kwargs)
if 'images' in data:
images = data['images']
for img in images:
self._update_image(img)
else:
self._update_data(data=data) | def update(self, *args, **kwargs) | Base method for updating data.
Applies a plot-type specific cleaning operation, then
updates the data in the visualization. | 3.778011 | 3.237715 | 1.166876 |
data = self._clean_data(*args, **kwargs)
if 'images' in data:
images = data['images']
for img in images:
self._append_image(img)
else:
self._append_data(data=data) | def append(self, *args, **kwargs) | Base method for appending data.
Applies a plot-type specific cleaning operation, then
appends data to the visualization. | 3.637443 | 3.168438 | 1.148024 |
url = self.session.host + '/sessions/' + str(self.session.id) + '/visualizations/' + str(self.id) + '/settings/'
r = requests.get(url)
if r.status_code == 200:
content = r.json()
else:
raise Exception('Error retrieving user data from server')
re... | def _get_user_data(self) | Base method for retrieving user data from a viz. | 3.826863 | 3.115279 | 1.228418 |
checkers = {
'color': check_color,
'alpha': check_alpha,
'size': check_size,
'thickness': check_thickness,
'index': check_index,
'coordinates': check_coordinates,
'colormap': check_colormap,
'bins': check_bins,
'spec': check_spec
}
... | def check_property(prop, name, **kwargs) | Check and parse a property with either a specific checking function
or a generic parser | 2.888116 | 2.902168 | 0.995158 |
if isinstance(co, ndarray):
co = co.tolist()
if not (isinstance(co[0][0], list) or isinstance(co[0][0], tuple)):
co = [co]
if xy is not True:
co = map(lambda p: asarray(p)[:, ::-1].tolist(), co)
return co | def check_coordinates(co, xy=None) | Check and parse coordinates as either a single coordinate list [[r,c],[r,c]] or a
list of coordinates for multiple regions [[[r0,c0],[r0,c0]], [[r1,c1],[r1,c1]]] | 3.233898 | 3.130569 | 1.033007 |
c = asarray(c)
if c.ndim == 1:
c = c.flatten()
c = c[newaxis, :]
if c.shape[1] != 3:
raise Exception("Color must have three values per point")
elif c.ndim == 2:
if c.shape[1] != 3:
raise Exception("Color array must have three values per point")
... | def check_color(c) | Check and parse color specs as either a single [r,g,b] or a list of
[[r,g,b],[r,g,b]...] | 2.933234 | 2.851084 | 1.028814 |
names = set(['BrBG', 'PiYG', 'PRGn', 'PuOr', 'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral',
'Blues', 'BuGn', 'BuPu', 'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd', 'PuBu',
'PuBuGn', 'PuRd', 'Purples', 'RdPu', 'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd',
'Acce... | def check_colormap(cmap) | Check if cmap is one of the colorbrewer maps | 1.745488 | 1.666742 | 1.047245 |
s = check_1d(s, "size")
if any(map(lambda d: d <= 0, s)):
raise Exception('Size cannot be 0 or negative')
return s | def check_size(s) | Check and parse size specs as either a single [s] or a list of [s,s,s,...] | 6.276177 | 5.504175 | 1.140257 |
s = check_1d(s, "thickness")
if any(map(lambda d: d <= 0, s)):
raise Exception('Thickness cannot be 0 or negative')
return s | def check_thickness(s) | Check and parse thickness specs as either a single [s] or a list of [s,s,s,...] | 6.209819 | 5.288258 | 1.174266 |
i = asarray(i)
if (i.ndim > 1) or (size(i) < 1):
raise Exception("Index must be one-dimensional and non-singleton")
return i | def check_index(i) | Checks and parses an index spec, must be a one-dimensional array [i0, i1, ...] | 5.488456 | 4.378602 | 1.253472 |
a = check_1d(a, "alpha")
if any(map(lambda d: d <= 0, a)):
raise Exception('Alpha cannot be 0 or negative')
return a | def check_alpha(a) | Check and parse alpha specs as either a single [a] or a list of [a,a,a,...] | 6.173 | 5.745897 | 1.074332 |
x = asarray(x)
if size(x) == 1:
x = asarray([x])
if x.ndim == 2:
raise Exception("Property: %s must be one-dimensional" % name)
x = x.flatten()
return x | def check_1d(x, name) | Check and parse a one-dimensional spec as either a single [x] or a list of [x,x,x...] | 4.341167 | 3.962763 | 1.09549 |
bounds = array(coords).astype('int')
path = Path(bounds)
grid = meshgrid(range(dims[1]), range(dims[0]))
grid_flat = zip(grid[0].ravel(), grid[1].ravel())
mask = path.contains_points(grid_flat).reshape(dims[0:2]).astype('int')
if z is not None:
if len(dims) < 3:
rais... | def polygon_to_mask(coords, dims, z=None) | Given a list of pairs of points which define a polygon, return a binary
mask covering the interior of the polygon with dimensions dim | 3.703722 | 3.906754 | 0.948031 |
bounds = array(coords).astype('int')
bmax = bounds.max(0)
bmin = bounds.min(0)
path = Path(bounds)
grid = meshgrid(range(bmin[0], bmax[0]+1), range(bmin[1], bmax[1]+1))
grid_flat = zip(grid[0].ravel(), grid[1].ravel())
points = path.contains_points(grid_flat).reshape(grid[0].shape... | def polygon_to_points(coords, z=None) | Given a list of pairs of points which define a polygon,
return a list of points interior to the polygon | 2.792841 | 2.947939 | 0.947388 |
if filename is None:
raise ValueError('Please provide a filename, e.g. viz.save_html(filename="viz.html").')
import os
base = self._html
js = self.load_embed()
if os.path.exists(filename):
if overwrite is False:
raise ValueError(... | def save_html(self, filename=None, overwrite=False) | Save self-contained html to a file.
Parameters
----------
filename : str
The filename to save to | 3.132999 | 3.440988 | 0.910494 |
context = {
'request_path': request.path,
}
return http.HttpResponseTemporaryUnavailable(
render_to_string(template_name, context)) | def temporary_unavailable(request, template_name='503.html') | Default 503 handler, which looks for the requested URL in the
redirects table, redirects if found, and displays 404 page if not
redirected.
Templates: ``503.html``
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/') | 3.888456 | 5.263623 | 0.738741 |
def key(s):
return (s.version, 1 if s.operator in ['>=', '<'] else 2)
def in_bounds(v, lo, hi):
if lo and v not in lo:
return False
if hi and v not in hi:
return False
return True
def err(reason='inconsistent'):
return ValueError('{} sp... | def simplify_specifiers(spec) | Try to simplify a SpecifierSet by combining redundant specifiers. | 2.907666 | 2.79854 | 1.038994 |
self.lineno = self.lineno if lineno is None else lineno
self.type_ = self.type_ if type_ is None else type_
self.offset = self.offset if offset is None else offset
self.callable = True
self.params = SymbolPARAMLIST()
self.body = SymbolBLOCK()
self.__kind... | def reset(self, lineno=None, offset=None, type_=None) | This is called when we need to reinitialize the instance state | 4.644276 | 4.504463 | 1.031039 |
entry = global_.SYMBOL_TABLE.declare_func(func_name, lineno, type_=type_)
if entry is None:
return None
entry.declared = True
return cls(entry, lineno) | def make_node(cls, func_name, lineno, type_=None) | This will return a node with the symbol as a function. | 7.902792 | 7.662048 | 1.03142 |
''' Checks the function types
'''
args = tuple(x if isinstance(x, collections.Iterable) else (x,) for x in args)
kwargs = {x: kwargs[x] if isinstance(kwargs[x], collections.Iterable) else (kwargs[x],) for x in kwargs}
def decorate(func):
types = args
kwtypes = kwargs
gi = "G... | def check_type(*args, **kwargs) | Checks the function types | 2.454309 | 2.431175 | 1.009516 |
if self.STRING_LABELS.get(str_, None) is None:
self.STRING_LABELS[str_] = backend.tmp_label()
return self.STRING_LABELS[str_] | def add_string_label(self, str_) | Maps ("folds") the given string, returning an unique label ID.
This allows several constant labels to be initialized to the same address
thus saving memory space.
:param str_: the string to map
:return: the unique label ID | 4.113895 | 4.434441 | 0.927715 |
if isinstance(type_, symbols.TYPE):
return type_
assert TYPE.is_valid(type_)
return gl.SYMBOL_TABLE.basic_types[type_] | def TYPE(type_) | Converts a backend type (from api.constants)
to a SymbolTYPE object (taken from the SYMBOL_TABLE).
If type_ is already a SymbolTYPE object, nothing
is done. | 12.278584 | 9.401475 | 1.306027 |
quad = Quad(*args)
__DEBUG__('EMIT ' + str(quad))
MEMORY.append(quad) | def emit(*args) | Convert the given args to a Quad (3 address code) instruction | 21.139194 | 14.325183 | 1.475667 |
if not self.HAS_ATTR:
return
self.HAS_ATTR = False
self.emit('call', 'COPY_ATTR', 0)
backend.REQUIRES.add('copy_attr.asm') | def norm_attr(self) | Normalize attr state | 16.111429 | 15.427781 | 1.044313 |
if node.token == 'NUMBER':
return node.t
if node.token == 'UNARY':
mid = node.operator
if mid == 'MINUS':
result = ' -' + Translator.traverse_const(node.operand)
elif mid == 'ADDRESS':
if node.operand.scope == SCOP... | def traverse_const(node) | Traverses a constant and returns an string
with the arithmetic expression | 2.757532 | 2.706004 | 1.019042 |
if len(node.children) > n:
return node.children[n] | def check_attr(node, n) | Check if ATTR has to be normalized
after this instruction has been translated
to intermediate code. | 5.035376 | 6.233776 | 0.807757 |
p = '*' if var.byref else '' # Indirection prefix
if self.O_LEVEL > 1 and not var.accessed:
return
if not var.type_.is_basic:
raise NotImplementedError()
if var.scope == SCOPE.global_:
self.emit('store' + self.TSUFFIX(var.type_), var.mangle... | def emit_var_assign(self, var, t) | Emits code for storing a value into a variable
:param var: variable (node) to be updated
:param t: the value to emmit (e.g. a _label, a const, a tN...) | 5.219869 | 5.140067 | 1.015526 |
for i in range(len(self.LOOPS) - 1, -1, -1):
if loop_type == self.LOOPS[i][0]:
return self.LOOPS[i][1]
raise InvalidLoopError(loop_type) | def loop_exit_label(self, loop_type) | Returns the label for the given loop type which
exits the loop. loop_type must be one of 'FOR', 'WHILE', 'DO' | 2.663501 | 2.729361 | 0.97587 |
for i in range(len(self.LOOPS) - 1, -1, -1):
if loop_type == self.LOOPS[i][0]:
return self.LOOPS[i][2]
raise InvalidLoopError(loop_type) | def loop_cont_label(self, loop_type) | Returns the label for the given loop type which
continues the loop. loop_type must be one of 'FOR', 'WHILE', 'DO' | 2.826164 | 2.847243 | 0.992597 |
syntax_error(expr.lineno, "Can't convert non-numeric value to {0} at compile time".format(type_.name))
return ['<ERROR>']
val = Translator.traverse_const(expr)
if type_.size == 1: # U/byte
if expr.type_.size != 1:
return ['#({... | def default_value(cls, type_, expr): # TODO: This function must be moved to api.xx
assert isinstance(type_, symbols.TYPE)
assert type_.is_basic
assert check.is_static(expr)
if isinstance(expr, (symbols.CONST, symbols.VAR)): # a constant expression like @label + 1
... | Returns a list of bytes (as hexadecimal 2 char string) | 3.035423 | 2.955439 | 1.027063 |
if not isinstance(values, list):
return Translator.default_value(type_, values)
l = []
for row in values:
l.extend(Translator.array_default_value(type_, row))
return l | def array_default_value(type_, values) | Returns a list of bytes (as hexadecimal 2 char string)
which represents the array initial value. | 3.882859 | 3.839931 | 1.011179 |
if not hasattr(i, 'type_'):
return False
if i.type_ != Type.string:
return False
if i.token in ('VAR', 'PARAMDECL'):
return True # We don't know what an alphanumeric variable will hold
if i.token == 'STRING':
for c in i.value:
... | def has_control_chars(i) | Returns true if the passed token is an unknown string
or a constant string having control chars (inverse, etc | 6.172932 | 6.098588 | 1.01219 |
self.emit('fparam' + self.TSUFFIX(gl.PTR_TYPE), node.children[0].t)
self.emit('call', 'USR', node.type_.size)
backend.REQUIRES.add('usr.asm') | def visit_USR(self, node) | Machine code call from basic | 29.461655 | 28.5732 | 1.031094 |
if not isinstance(other, Symbol):
return # Nothing done if not a Symbol object
tmp = re.compile('__.*__')
for attr in (x for x in dir(other) if not tmp.match(x)):
if (
hasattr(self.__class__, attr) and
str(type(getattr(self.__cl... | def copy_attr(self, other) | Copies all other attributes (not methods)
from the other object to this instance. | 4.723786 | 4.561047 | 1.03568 |
if fname is None:
if CURRENT_FILE:
fname = CURRENT_FILE[-1]
else: # If no files opened yet, use owns program fname
fname = sys.argv[0]
if self.defined(id_):
i = self.table[id_]
warning(lineno, '"%s" redefined (pre... | def define(self, id_, lineno, value='', fname=None, args=None) | Defines the value of a macro.
Issues a warning if the macro is already defined. | 5.360931 | 5.297187 | 1.012033 |
if fname is None:
if CURRENT_FILE:
fname = CURRENT_FILE[-1]
else: # If no files opened yet, use owns program fname
fname = sys.argv[0]
self.table[id_] = ID(id_, args, value, lineno, fname) | def set(self, id_, lineno, value='', fname=None, args=None) | Like the above, but issues no warning on duplicate macro
definitions. | 7.853394 | 8.200533 | 0.957669 |
if is_int(op1):
if swap:
return op2, int(op1)
else:
return int(op1), op2
if is_int(op2):
return op1, int(op2)
return None | def _int_ops(op1, op2, swap=True) | Receives a list with two strings (operands).
If none of them contains integers, returns None.
Otherwise, returns a t-uple with (op[0], op[1]),
where op[1] is the integer one (the list is swapped)
unless swap is False (e.g. sub and div used this
because they're not commutative).
The integer oper... | 2.44322 | 2.342931 | 1.042805 |
if is_float(op1):
if swap:
return op2, float(op1)
else:
return float(op1), op2
if is_float(op2):
return op1, float(op2)
return None | def _f_ops(op1, op2, swap=True) | Receives a list with two strings (operands).
If none of them contains integers, returns None.
Otherwise, returns a t-uple with (op[0], op[1]),
where op[1] is the integer one (the list is swapped)
unless swap is False (e.g. sub and div used this
because they're not commutative).
The integer oper... | 2.638116 | 2.666523 | 0.989347 |
assert isinstance(params, SymbolARGLIST)
entry = gl.SYMBOL_TABLE.access_func(id_, lineno)
if entry is None: # A syntax / semantic error
return None
if entry.callable is False: # Is it NOT callable?
if entry.type_ != Type.string:
errmsg.... | def make_node(cls, id_, params, lineno) | This will return an AST node for a function/procedure call. | 9.014995 | 8.578177 | 1.050922 |
''' This will return a node with a param_list
(declared in a function declaration)
Parameters:
-node: A SymbolPARAMLIST instance or None
-params: SymbolPARAMDECL insances
'''
if node is None:
node = clss()
if node.token != 'PARAMLIST':... | def make_node(clss, node, *params) | This will return a node with a param_list
(declared in a function declaration)
Parameters:
-node: A SymbolPARAMLIST instance or None
-params: SymbolPARAMDECL insances | 10.005521 | 2.742689 | 3.64807 |
''' Overrides base class.
'''
Symbol.appendChild(self, param)
if param.offset is None:
param.offset = self.size
self.size += param.size | def appendChild(self, param) | Overrides base class. | 6.823351 | 5.979255 | 1.141171 |
if left is None or right is None:
return None
a, b = left, right # short form names
# Check for constant non-numeric operations
c_type = common_type(a, b) # Resulting operation type or None
if c_type: # there must be a common type for a and b
... | def make_node(cls, operator, left, right, lineno, func=None,
type_=None) | Creates a binary node for a binary operation,
e.g. A + 6 => '+' (A, 6) in prefix notation.
Parameters:
-operator: the binary operation token. e.g. 'PLUS' for A + 6
-left: left operand
-right: right operand
-func: is a lambda function used when con... | 3.390134 | 3.331727 | 1.01753 |
if self is not self.final:
return self.final.is_dynamic
return any([x.is_dynamic for x in self.children]) | def is_dynamic(self) | True if this type uses dynamic (Heap) memory.
e.g. strings or dynamic arrays | 7.342703 | 7.384294 | 0.994368 |
assert isinstance(t, SymbolTYPE)
t = t.final
assert t.is_basic
if cls.is_unsigned(t):
return {cls.ubyte: cls.byte_,
cls.uinteger: cls.integer,
cls.ulong: cls.long_}[t]
if cls.is_signed(t) or cls.is_decimal(t):
... | def to_signed(cls, t) | Return signed type or equivalent | 5.583557 | 5.313506 | 1.050824 |
if id_[-1] in DEPRECATED_SUFFIXES:
id_ = id_[:-1] # Remove it
if scope is not None:
assert len(self.table) > scope
return self[scope][id_]
for sc in self:
if sc[id_] is not None:
return sc[id_]
return None | def get_entry(self, id_, scope=None) | Returns the ID entry stored in self.table, starting
by the first one. Returns None if not found.
If scope is not None, only the given scope is searched. | 5.472394 | 4.825232 | 1.13412 |
id2 = id_
type_ = entry.type_
if id2[-1] in DEPRECATED_SUFFIXES:
id2 = id2[:-1] # Remove it
type_ = symbols.TYPEREF(self.basic_types[SUFFIX_TYPE[id_[-1]]], lineno) # Overrides type_
if entry.type_ is not None and not entry.type_.implicit and type_ ... | def declare(self, id_, lineno, entry) | Check there is no 'id' already declared in the current scope, and
creates and returns it. Otherwise, returns None,
and the caller function raises the syntax/semantic error.
Parameter entry is the SymbolVAR, SymbolVARARRAY, etc. instance
The entry 'declared' field is leave... | 8.27202 | 7.855386 | 1.053038 |
result = self.get_entry(id_, scope)
if isinstance(result, symbols.TYPE):
return True
if result is None or not result.declared:
if show_error:
syntax_error(lineno, 'Undeclared %s "%s"' % (classname, id_))
return False
return Tr... | def check_is_declared(self, id_, lineno, classname='identifier',
scope=None, show_error=True) | Checks if the given id is already defined in any scope
or raises a Syntax Error.
Note: classname is not the class attribute, but the name of
the class as it would appear on compiler messages. | 4.078042 | 4.328437 | 0.942151 |
result = self.get_entry(id_, scope)
if result is None or not result.declared:
return True
if scope is None:
scope = self.current_scope
if show_error:
syntax_error(lineno,
'Duplicated %s "%s" (previous one at %s:%i)' ... | def check_is_undeclared(self, id_, lineno, classname='identifier',
scope=None, show_error=False) | The reverse of the above.
Check the given identifier is not already declared. Returns True
if OK, False otherwise. | 3.777091 | 3.56519 | 1.059436 |
assert CLASS.is_valid(class_)
entry = self.get_entry(id_, scope)
if entry is None or entry.class_ == CLASS.unknown: # Undeclared yet
return True
if entry.class_ != class_:
if show_error:
if entry.class_ == CLASS.array:
... | def check_class(self, id_, class_, lineno, scope=None, show_error=True) | Check the id is either undefined or defined with
the given class.
- If the identifier (e.g. variable) does not exists means
it's undeclared, and returns True (OK).
- If the identifier exists, but its class_ attribute is
unknown yet (None), returns also True. This means the
... | 3.337528 | 3.230715 | 1.033062 |
old_mangle = self.mangle
self.mangle = '%s%s%s' % (self.mangle, global_.MANGLE_CHR, funcname)
self.table.append(SymbolTable.Scope(self.mangle, parent_mangle=old_mangle))
global_.META_LOOPS.append(global_.LOOPS) # saves current LOOPS state
global_.LOOPS = [] | def enter_scope(self, funcname) | Starts a new variable scope.
Notice the *IMPORTANT* marked lines. This is how a new scope is added,
by pushing a new dict at the end (and popped out later). | 6.161984 | 6.809991 | 0.904845 |
def entry_size(entry):
if entry.scope == SCOPE.global_ or \
entry.is_aliased: # aliases or global variables = 0
return 0
if entry.class_ != CLASS.array:
return entry.size
return entry.memsize
... | def leave_scope(self) | Ends a function body and pops current scope out of the symbol table. | 5.127971 | 5.021833 | 1.021135 |
# In the current scope and more than 1 scope?
if id_ in self.table[self.current_scope].keys(filter_by_opt=False) and len(self.table) > 1:
symbol = self.table[self.current_scope][id_]
symbol.offset = None
symbol.scope = SCOPE.global_
if symbol.clas... | def move_to_global_scope(self, id_) | If the given id is in the current scope, and there is more than
1 scope, move the current id to the global scope and make it global.
Labels need this. | 5.932011 | 4.932583 | 1.202618 |
entry = self.table[self.current_scope][id_]
entry.scope = SCOPE.global_
self.table[self.global_scope][entry.mangled] = entry | def make_static(self, id_) | The given ID in the current scope is changed to 'global', but the
variable remains in the current scope, if it's a 'global private'
variable: A variable private to a function scope, but whose contents
are not in the stack, not in the global variable area.
These are called 'static variabl... | 8.880704 | 6.297133 | 1.410277 |
if isinstance(default_type, symbols.BASICTYPE):
default_type = symbols.TYPEREF(default_type, lineno, implicit=False)
assert default_type is None or isinstance(default_type, symbols.TYPEREF)
if not check_is_declared_explicit(lineno, id_):
return None
res... | def access_id(self, id_, lineno, scope=None, default_type=None, default_class=CLASS.unknown) | Access a symbol by its identifier and checks if it exists.
If not, it's supposed to be an implicit declared variable.
default_class is the class to use in case of an undeclared-implicit-accessed id | 4.532135 | 4.252384 | 1.065787 |
result = self.access_id(id_, lineno, scope, default_type)
if result is None:
return None
if not self.check_class(id_, CLASS.var, lineno, scope):
return None
assert isinstance(result, symbols.VAR)
result.class_ = CLASS.var
return result | def access_var(self, id_, lineno, scope=None, default_type=None) | Since ZX BASIC allows access to undeclared variables, we must allow
them, and *implicitly* declare them if they are not declared already.
This function just checks if the id_ exists and returns its entry so.
Otherwise, creates an implicit declared variable entry and returns it.
If the -... | 5.093828 | 5.403093 | 0.942761 |
if not self.check_is_declared(id_, lineno, 'array', scope):
return None
if not self.check_class(id_, CLASS.array, lineno, scope):
return None
return self.access_id(id_, lineno, scope=scope, default_type=default_type) | def access_array(self, id_, lineno, scope=None, default_type=None) | Called whenever an accessed variable is expected to be an array.
ZX BASIC requires arrays to be declared before usage, so they're
checked.
Also checks for class array. | 4.014217 | 3.617508 | 1.109664 |
assert default_type is None or isinstance(default_type, symbols.TYPEREF)
result = self.get_entry(id_, scope)
if result is None:
if default_type is None:
if global_.DEFAULT_IMPLICIT_TYPE == TYPE.auto:
default_type = symbols.TYPEREF(self.ba... | def access_func(self, id_, lineno, scope=None, default_type=None) | Since ZX BASIC allows access to undeclared functions, we must allow
and *implicitly* declare them if they are not declared already.
This function just checks if the id_ exists and returns its entry if so.
Otherwise, creates an implicit declared variable entry and returns it. | 4.188663 | 3.971503 | 1.05468 |
entry = self.access_id(id_, lineno, scope, default_type=type_)
if entry is None:
return self.access_func(id_, lineno)
if entry.callable is False: # Is it NOT callable?
if entry.type_ != self.basic_types[TYPE.string]:
syntax_error_not_array_nor_f... | def access_call(self, id_, lineno, scope=None, type_=None) | Creates a func/array/string call. Checks if id is callable or not.
An identifier is "callable" if it can be followed by a list of para-
meters.
This does not mean the id_ is a function, but that it allows the same
syntax a function does:
For example:
- MyFunction(a, "... | 6.100744 | 6.061376 | 1.006495 |
assert isinstance(type_, symbols.TYPEREF)
if not self.check_is_undeclared(id_, lineno, scope=self.current_scope, show_error=False):
entry = self.get_entry(id_)
if entry.scope == SCOPE.parameter:
syntax_error(lineno,
"Variable ... | def declare_variable(self, id_, lineno, type_, default_value=None) | Like the above, but checks that entry.declared is False.
Otherwise raises an error.
Parameter default_value specifies an initialized variable, if set. | 3.659601 | 3.59163 | 1.018925 |
assert isinstance(type_, symbols.TYPE)
# Checks it's not a basic type
if not type_.is_basic and type_.name.lower() in TYPE.TYPE_NAMES.values():
syntax_error(type_.lineno, "'%s' is a basic type and cannot be redefined" %
type_.name)
return... | def declare_type(self, type_) | Declares a type.
Checks its name is not already used in the current scope,
and that it's not a basic type.
Returns the given type_ Symbol, or None on error. | 5.71261 | 4.768314 | 1.198036 |
if not self.check_is_undeclared(id_, lineno, scope=self.current_scope, show_error=False):
entry = self.get_entry(id_)
if entry.scope == SCOPE.parameter:
syntax_error(lineno,
"Constant '%s' already declared as a parameter "
... | def declare_const(self, id_, lineno, type_, default_value) | Similar to the above. But declares a Constant. | 3.29257 | 3.178233 | 1.035975 |
# TODO: consider to make labels private
id1 = id_
id_ = str(id_)
if not self.check_is_undeclared(id_, lineno, 'label'):
entry = self.get_entry(id_)
syntax_error(lineno, "Label '%s' already used at %s:%i" %
(id_, entry.filename, e... | def declare_label(self, id_, lineno) | Declares a label (line numbers are also labels).
Unlike variables, labels are always global. | 5.133323 | 4.993732 | 1.027953 |
if not self.check_is_undeclared(id_, lineno, classname='parameter',
scope=self.current_scope, show_error=True):
return None
entry = self.declare(id_, lineno, symbols.PARAMDECL(id_, lineno, type_))
if entry is None:
return
... | def declare_param(self, id_, lineno, type_=None) | Declares a parameter
Check if entry.declared is False. Otherwise raises an error. | 7.570578 | 6.117818 | 1.237464 |
assert isinstance(type_, symbols.TYPEREF)
assert isinstance(bounds, symbols.BOUNDLIST)
if not self.check_class(id_, CLASS.array, lineno, scope=self.current_scope):
return None
entry = self.get_entry(id_, self.current_scope)
if entry is None:
ent... | def declare_array(self, id_, lineno, type_, bounds, default_value=None) | Declares an array in the symbol table (VARARRAY). Error if already
exists. | 4.089668 | 3.911434 | 1.045567 |
if not self.check_class(id_, 'function', lineno):
entry = self.get_entry(id_) # Must not exist or have _class = None or Function and declared = False
an = 'an' if entry.class_.lower()[0] in 'aeio' else 'a'
syntax_error(lineno, "'%s' already declared as %s %s at %i" ... | def declare_func(self, id_, lineno, type_=None) | Declares a function in the current scope.
Checks whether the id exist or not (error if exists).
And creates the entry at the symbol table. | 5.381731 | 5.264685 | 1.022232 |
for entry in self.labels:
self.check_is_declared(entry.name, entry.lineno, CLASS.label) | def check_labels(self) | Checks if all the labels has been declared | 15.552096 | 10.244383 | 1.51811 |
for entry in self[scope].values():
if entry.class_ is None:
syntax_error(entry.lineno, "Unknown identifier '%s'" % entry.name) | def check_classes(self, scope=-1) | Check if pending identifiers are defined or not. If not,
returns a syntax error. If no scope is given, the current
one is checked. | 7.410211 | 6.043907 | 1.226063 |
return [x for x in self[self.current_scope].values() if x.class_ == CLASS.var] | def vars_(self) | Returns symbol instances corresponding to variables
of the current scope. | 12.54389 | 9.422091 | 1.331328 |
return [x for x in self[self.current_scope].values() if x.class_ == CLASS.label] | def labels(self) | Returns symbol instances corresponding to labels
in the current scope. | 15.045202 | 8.435833 | 1.783487 |
return [x for x in self[self.current_scope].values() if isinstance(x, symbols.TYPE)] | def types(self) | Returns symbol instances corresponding to type declarations
within the current scope. | 13.652265 | 7.150766 | 1.909203 |
return [x for x in self[self.current_scope].values() if x.class_ == CLASS.array] | def arrays(self) | Returns symbol instances corresponding to arrays
of the current scope. | 13.439099 | 7.991371 | 1.681701 |
return [x for x in self[self.current_scope].values() if x.class_ in
(CLASS.function, CLASS.sub)] | def functions(self) | Returns symbol instances corresponding to functions
of the current scope. | 14.472766 | 9.435399 | 1.53388 |
return [x for x in self[self.current_scope].values() if x.is_aliased] | def aliases(self) | Returns symbol instances corresponding to aliased vars. | 11.038753 | 6.496735 | 1.699123 |
if not isinstance(type_list, list):
type_list = [type_list]
if arg.type_ in type_list:
return True
if len(type_list) == 1:
syntax_error(lineno, "Wrong expression type '%s'. Expected '%s'" %
(arg.type_, type_list[0]))
else:
syntax_error(lineno, ... | def check_type(lineno, type_list, arg) | Check arg's type is one in type_list, otherwise,
raises an error. | 2.294295 | 2.320087 | 0.988883 |
if not config.OPTIONS.explicit.value:
return True
entry = global_.SYMBOL_TABLE.check_is_declared(id_, lineno, classname)
return entry is not None | def check_is_declared_explicit(lineno, id_, classname='variable') | Check if the current ID is already declared.
If not, triggers a "undeclared identifier" error,
if the --explicit command line flag is enabled (or #pragma
option strict is in use).
If not in strict mode, passes it silently. | 11.894952 | 11.919105 | 0.997974 |
if not global_.SYMBOL_TABLE.check_is_declared(id_, lineno, 'function'):
return False
if not global_.SYMBOL_TABLE.check_class(id_, CLASS.function, lineno):
return False
entry = global_.SYMBOL_TABLE.get_entry(id_)
if len(args) != len(entry.params):
c = 's' if len(entry.para... | def check_call_arguments(lineno, id_, args) | Check arguments against function signature.
Checks every argument in a function call against a function.
Returns True on success. | 4.269345 | 4.235202 | 1.008062 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.